Spring Cloud Security Oauth2 搭建统一授权服务

Spring Cloud Security Oauth2 授权服务配置

github代码链接
使用spring-cloud-security-oauth2 搭建统一授权服务:

  • 授权服务配置
  • 资源服务配置
  • 安全配置
  • *其他服务如何进行授权验证

1.引入pom配置

  <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-securityartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-oauth2artifactId>
   dependency>

2.创建授权配置信息

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration  extends AuthorizationServerConfigurerAdapter {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisConnectionFactory connectionFactory;

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

    @Bean
    public ClientDetailsService clientDetailsService(){
        return new SecurityClientDetailsServiceImpl();
    }

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


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService())//若无,refresh_token会有UserDetailsService is required错误
             //   .tokenStore(tokenStore());
        .tokenStore(new InMemoryTokenStore());
    }

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService());
    }
}
  • 继承AuthorizationServerConfigurerAdapter,此类包含授权的方法 对进行配置
  • AuthorizationServerEndpointsConfigurer 令牌端点的存储方式,本地使用InMemoryTokenStore 此处配置了redis的存储方式 生产环境可以进行使用
  • AuthorizationServerSecurityConfigurer 中的permitAll() 让本身的oauth的访问不需要授权 ,isAuthenticated()检查access_token需要进行授权
  • SecurityClientDetailsServiceImpl 实现客户端自定义配置

3.资源服务配置信息

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration 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().antMatchers("/noAuth").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

}
  • 资源服务配置对该服务中的某些资源进行控制

4.安全服务配置

@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

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



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

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
  • 使用自定义用户信息 ,查询的用户来自与SecurityUserDetailsServiceImpl返回的数据

5.重写用户和客户端信息

/**
自定义实现ClientDetailsService
**/
@Service
public class SecurityClientDetailsServiceImpl implements ClientDetailsService 
/**
自定义实现UserDetailsService 
**/
public class SecurityUserDetailsServiceImpl implements UserDetailsService 
  • 自定义实现对客户端和用户信息的控制

6.配置文件

授权服务的配置

security:
    oauth2:
      resource:
        filter-order: 3
  • 必须加这个 我了解的是拦截器的顺序问题

客户端服务配置

security:
  oauth2:
    resource:
      id: carbon-provider-bank
      user-info-uri: http://localhost:9005/user
      prefer-token-info: false
management:
  security:
    enabled: false
  • 用户验证是否进行了授权

7.增加user-info-uri接口

@RestController
public class UserController extends BaseController{

    @Autowired
    private IBankFeginService bankFeginService;

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

8.获取当前用户信息

public static Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            return authentication;
        }
        throw  new AuthenticationServiceException("authentication not found");
    }
  • 获取当前登入用户的账号,在WebContextUtil 工具类中

9.访问

已账号密码模式为例子

http://localhost:9005/oauth/token
post 请求
请求类型(可选)
Authorization basic auth
Username client_id
Password secret

参数 是否必须 含义
username 必须 用户账号
password 必须 用户密码
grant_type 必须 授权类型 填写password
scope 可选 授权类型 请求用户授权时向用户显示的可进行授权的列表。

-访问方式文档在项目里面
以上就是授权服务的基本配置,有关授权服务配置的代码 会在后面进行逐渐的完善

你可能感兴趣的:(springcloud笔记)