Spring Cloud下基于OAUTH2认证授权的实现示例

 更新时间:2018年03月09日 10:38:17   作者:智顶笔记  
这篇文章主要介绍了Spring Cloud下基于OAUTH2认证授权的实现示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

Spring Cloud需要使用OAUTH2来实现多个微服务的统一认证授权,通过向OAUTH服务发送某个类型的grant type进行集中认证和授权,从而获得access_token,而这个token是受其他微服务信任的,我们在后续的访问可以通过access_token来进行,从而实现了微服务的统一认证授权。

本示例提供了四大部分:

  1. discovery-service:服务注册和发现的基本模块
  2. auth-server:OAUTH2认证授权中心
  3. order-service:普通微服务,用来验证认证和授权
  4. api-gateway:边界网关(所有微服务都在它之后)

OAUTH2中的角色:

  1. Resource Server:被授权访问的资源
  2. Authotization Server:OAUTH2认证授权中心
  3. Resource Owner: 用户
  4. Client:使用API的客户端(如Android 、IOS、web app)

Grant Type:

  1. Authorization Code:用在服务端应用之间
  2. Implicit:用在移动app或者web app(这些app是在用户的设备上的,如在手机上调起微信来进行认证授权)
  3. Resource Owner Password Credentials(password):应用直接都是受信任的(都是由一家公司开发的,本例子使用
  4. Client Credentials:用在应用API访问。

1.基础环境

使用Postgres作为账户存储,Redis作为Token存储,使用docker-compose在服务器上启动PostgresRedis

Redis:
 image: sameersbn/redis:latest
 ports:
 - "6379:6379"
 volumes:
 - /srv/docker/redis:/var/lib/redis:Z
 restart: always

PostgreSQL:
 restart: always
 image: sameersbn/postgresql:9.6-2
 ports:
 - "5432:5432"
 environment:
 - DEBUG=false

 - DB_USER=wang
 - DB_PASS=yunfei
 - DB_NAME=order
 volumes:
 - /srv/docker/postgresql:/var/lib/postgresql:Z

2.auth-server

2.1 OAuth2服务配置

Redis用来存储token,服务重启后,无需重新获取token.

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
 @Autowired
 private AuthenticationManager authenticationManager;
 @Autowired
 private RedisConnectionFactory connectionFactory;


 @Bean
 public RedisTokenStore tokenStore() {
  return new RedisTokenStore(connectionFactory);
 }


 @Override
 public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
  endpoints
    .authenticationManager(authenticationManager)
    .tokenStore(tokenStore());
 }

 @Override
 public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
  security
    .tokenKeyAccess("permitAll()")
    .checkTokenAccess("isAuthenticated()");
 }

 @Override
 public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  clients.inMemory()
    .withClient("android")
    .scopes("xx") //此处的scopes是无用的,可以随意设置
    .secret("android")
    .authorizedGrantTypes("password", "authorization_code", "refresh_token")
   .and()
    .withClient("webapp")
    .scopes("xx")
    .authorizedGrantTypes("implicit");
 }
}

2.2 Resource服务配置

auth-server提供user信息,所以auth-server也是一个Resource Server

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

 @Override
 public void configure(HttpSecurity http) throws Exception {
  http
    .csrf().disable()
    .exceptionHandling()
    .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
   .and()
    .authorizeRequests()
    .anyRequest().authenticated()
   .and()
    .httpBasic();
 }
}
@RestController
public class UserController {

 @GetMapping("/user")
 public Principal user(Principal user){
  return user;
 }
}

2.3 安全配置

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {



 @Bean
 public UserDetailsService userDetailsService(){
  return new DomainUserDetailsService();
 }

 @Bean
 public PasswordEncoder passwordEncoder() {
  return new BCryptPasswordEncoder();
 }

 @Override
 protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth
    .userDetailsService(userDetailsService())
    .passwordEncoder(passwordEncoder());
 }

 @Bean
 public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
  return new SecurityEvaluationContextExtension();
 }

 //不定义没有password grant_type
 @Override
 @Bean
 public AuthenticationManager authenticationManagerBean() throws Exception {
  return super.authenticationManagerBean();
 }

}

2.4 权限设计

采用用户(SysUser) 角色(SysRole) 权限(SysAuthotity)设置,彼此之间的关系是多对多。通过DomainUserDetailsService 加载用户和权限。

2.5 配置

spring:
 profiles:
 active: ${SPRING_PROFILES_ACTIVE:dev}
 application:
  name: auth-server

 jpa:
 open-in-view: true
 database: POSTGRESQL
 show-sql: true
 hibernate:
  ddl-auto: update
 datasource:
 platform: postgres
 url: jdbc:postgresql://192.168.1.140:5432/auth
 username: wang
 password: yunfei
 driver-class-name: org.postgresql.Driver
 redis:
 host: 192.168.1.140

server:
 port: 9999


eureka:
 client:
 serviceUrl:
  defaultZone: http://${eureka.host:localhost}:${eureka.port:8761}/eureka/



logging.level.org.springframework.security: DEBUG

logging.leve.org.springframework: DEBUG

##很重要
security:
 oauth2:
 resource:
  filter-order: 3

2.6 测试数据

data.sql里初始化了两个用户admin->ROLE_ADMIN->query_demo,wyf->ROLE_USER

3.order-service

3.1 Resource服务配置

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{

 @Override
 public void configure(HttpSecurity http) throws Exception {
  http
    .csrf().disable()
    .exceptionHandling()
    .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
   .and()
    .authorizeRequests()
    .anyRequest().authenticated()
   .and()
    .httpBasic();
 }
}

3.2 用户信息配置

order-service是一个简单的微服务,使用auth-server进行认证授权,在它的配置文件指定用户信息在auth-server的地址即可:

security:
 oauth2:
 resource:
  id: order-service
  user-info-uri: http://localhost:8080/uaa/user
  prefer-token-info: false

3.3 权限测试控制器

具备authorityquery-demo的才能访问,即为admin用户

@RestController
public class DemoController {
 @GetMapping("/demo")
 @PreAuthorize("hasAuthority('query-demo')")
 public String getDemo(){
  return "good";
 }
}

4 api-gateway

api-gateway在本例中有2个作用:

  1. 本身作为一个client,使用implicit
  2. 作为外部app访问的方向代理

4.1 关闭csrf并开启Oauth2 client支持

@Configuration
@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter{
 @Override
 protected void configure(HttpSecurity http) throws Exception {

  http.csrf().disable();
 }
}

4.2 配置

zuul:
 routes:
 uaa:
  path: /uaa/**
  sensitiveHeaders:
  serviceId: auth-server
 order:
  path: /order/**
  sensitiveHeaders:
  serviceId: order-service
 add-proxy-headers: true

security:
 oauth2:
 client:
  access-token-uri: http://localhost:8080/uaa/oauth/token
  user-authorization-uri: http://localhost:8080/uaa/oauth/authorize
  client-id: webapp
 resource:
  user-info-uri: http://localhost:8080/uaa/user
  prefer-token-info: false

5 演示

5.1 客户端调用

使用Postmanhttp://localhost:8080/uaa/oauth/token发送请求获得access_token(admin用户的如7f9b54d4-fd25-4a2c-a848-ddf8f119230b)

admin用户

wyf用户

5.2 api-gateway中的webapp调用

暂时没有做测试,下次补充。

6 源码地址

https://github.com/wiselyman/uaa-zuul

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • SpringBoot中忽略实体类中的某个属性不返回给前端的方法(示例详解)

    SpringBoot中忽略实体类中的某个属性不返回给前端的方法(示例详解)

    本文介绍了在Spring Boot中使用Jackson和Fastjson忽略实体类属性不返回给前端的方法,在Jackson中,同时使用@JsonProperty和@JsonIgnore时,@JsonIgnore可能失效,Fastjson中可以使用@JSONField(serialize=false)来实现,本文结合实例代码介绍的非常详细,需要的朋友参考下吧
    2024-11-11
  • Java创建线程的方式解析

    Java创建线程的方式解析

    这篇文章主要介绍了Java创建线程的方式解析,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下,希望对你的学习有所帮助
    2022-07-07
  • springboot中@ConfigurationProperties无效果的解决方法

    springboot中@ConfigurationProperties无效果的解决方法

    本文主要介绍了springboot中@ConfigurationProperties无效果,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-06-06
  • java 线程池keepAliveTime的含义说明

    java 线程池keepAliveTime的含义说明

    这篇文章主要介绍了java 线程池keepAliveTime的含义说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • java 文件上传(单文件与多文件)

    java 文件上传(单文件与多文件)

    这篇文章主要介绍了java 文件上传(单文件与多文件)的相关资料,希望通过本文能帮助到大家,需要的朋友可以参考下
    2017-10-10
  • JAVA值传递和引用传递方式

    JAVA值传递和引用传递方式

    文章总结:在Java中,处理不可变集合时,直接修改操作会抛出异常,正确的做法是使用可变集合类型,如ArrayList,或者通过流操作(stream().filter())来实现修改,理解Java方法参数的传递方式(值传递)是关键,这决定了如何正确地修改对象的状态
    2024-11-11
  • idea创建properties文件,解决乱码问题

    idea创建properties文件,解决乱码问题

    这篇文章主要介绍了idea创建properties文件,解决乱码问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-07-07
  • java简单读取properties配置文件的方法示例

    java简单读取properties配置文件的方法示例

    这篇文章主要介绍了java简单读取properties配置文件的方法,涉及java针对properties配置的载入及文件属性读取相关操作技巧,需要的朋友可以参考下
    2017-09-09
  • Spring整合Mybatis的全过程

    Spring整合Mybatis的全过程

    这篇文章主要介绍了Spring整合Mybatis的全过程,包括spring配置文件书写映射器接口的实例代码,本文给大家介绍的非常详细,需要的朋友可以参考下
    2021-06-06
  • Spring Boot 2 实战:自定义启动运行逻辑实例详解

    Spring Boot 2 实战:自定义启动运行逻辑实例详解

    这篇文章主要介绍了Spring Boot 2 实战:自定义启动运行逻辑,结合实例形式详细分析了Spring Boot 2自定义启动运行逻辑详细操作技巧与注意事项,需要的朋友可以参考下
    2020-05-05

最新评论