spring cloud Finchley.RELEASE使用Oauth2建立auth-server中的大坑,暂时没有解决

以来项


    com.alibaba
    fastjson


    com.github.ulisesbocchio
    jasypt-spring-boot-starter
    ${jasypt.version}


    org.springframework.cloud
    spring-cloud-starter-openfeign


    io.github.openfeign
    feign-core


    commons-lang
    commons-lang



    org.springframework.boot
    spring-boot-starter-data-redis



    org.springframework.boot
    spring-boot-starter-cache


    com.alibaba
    transmittable-thread-local


    javax.servlet
    javax.servlet-api
    ${javax.servlet-api.version}
    provided



    
    


    cn.hutool
    hutool-all



    org.springframework.boot
    spring-boot-starter-aop



    cn.schealth365.skynet
    skynet-cloud-common
    ${project.version}



    io.jsonwebtoken
    jjwt
    ${jjwt.version}


    org.springframework
    spring-webmvc


    org.springframework.cloud
    spring-cloud-starter-security

 

AuthorizationServerConfigurerAdapter适配实现类:

 

@Configuration
@EnableAuthorizationServer
public class SkynetAuthorizationServerConfigurerAdapter extends AuthorizationServerConfigurerAdapter {

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Qualifier("dataSource")
    @Autowired
    private DataSource dataSource;



    @Autowired
    private UserDetailsService userDetailsService;


    @Autowired
    private RedisConnectionFactory redisConnectionFactory;


//    @Bean
//    public ClientDetailsService clientDetails() {
//        JdbcClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);;
//        clientDetailsService.setSelectClientDetailsSql(SecurityConstants.DEFAULT_SELECT_STATEMENT);
//        clientDetailsService.setFindClientDetailsSql(SecurityConstants.DEFAULT_FIND_STATEMENT);
//        return clientDetailsService;
//    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        //clients.withClientDetails(clientDetails());
        //clients.withClientDetails(clientDetails());
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        //token增强配置
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(
                Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
        //return tokenEnhancerChain;
//
//        endpoints.tokenServices(tokenServices);
        //endpoints.setClientDetailsService(clientDetails());

        endpoints
                .tokenStore(redisTokenStore())
                .tokenEnhancer(tokenEnhancerChain)
                .authenticationManager(authenticationManager)
                .reuseRefreshTokens(false)
                .userDetailsService(userDetailsService)
                .exceptionTranslator(loggingExceptionTranslator());


        //endpoints.tokenServices(defaultTokenServices());
    }

//    @Bean
//    public TokenEnhancerChain defaultTokenChain() {
//        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
//        tokenEnhancerChain.setTokenEnhancers(
//                Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
//        return tokenEnhancerChain;
//    }

    @Bean
    public WebResponseExceptionTranslator loggingExceptionTranslator() {
        return new DefaultWebResponseExceptionTranslator() {
            @Override
            public ResponseEntity translate(Exception e) throws Exception {
                // This is the line that prints the stack trace to the log. You can customise this to format the trace etc if you like
                e.printStackTrace();

                // Carry on handling the exception
                ResponseEntity responseEntity = super.translate(e);
                HttpHeaders headers = new HttpHeaders();
                headers.setAll(responseEntity.getHeaders().toSingleValueMap());
                OAuth2Exception excBody = responseEntity.getBody();
                return new ResponseEntity<>(excBody, headers, responseEntity.getStatusCode());
            }
        };
    }

//    @Bean
//    public ResourceServerTokenServices defaultTokenServices() {
//        final DefaultTokenServices tokenServices = new DefaultTokenServices();
//        //tokenServices.setTokenStore(redisTokenStore());
//        //tokenServices.setClientDetailsService(clientDetails());
//        tokenServices.setReuseRefreshToken(false);
//        tokenServices.setSupportRefreshToken(true);
//        //tokenServices.setTokenEnhancer(defaultTokenChain());
//        tokenServices.setAccessTokenValiditySeconds( (int) TimeUnit.DAYS.toSeconds(30));
//        tokenServices.setRefreshTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(30));
//        return tokenServices;
//    }

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

    }

    @Bean

    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        SkynetCloudJwtAccessTokenConverter jwtAccessTokenConverter = new SkynetCloudJwtAccessTokenConverter();
        jwtAccessTokenConverter.setSigningKey(CommonConstants.SIGN_KEY);
        return jwtAccessTokenConverter;
    }

    /**
     * tokenstore 定制化处理
     *
     * @return TokenStore
     * 1. 如果使用的 redis-cluster 模式请使用 SkyRedisTokenStore
     * SkyRedisTokenStore tokenStore = new SkyRedisTokenStore();
     * tokenStore.setRedisTemplate(redisTemplate);
     */
    @Bean
    public TokenStore redisTokenStore() {
        RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
        tokenStore.setPrefix(SecurityConstants.SCHEALTH_PREFIX);

        return tokenStore;
    }

    /**
     * jwt 生成token 定制化处理
     *
     * @return TokenEnhancer
     */
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return (accessToken, authentication) -> {
            final Map additionalInfo = new HashMap<>(2);
            additionalInfo.put("license", SecurityConstants.SCHEALTH_LICENSE);
            UserDetailsImpl user = (UserDetailsImpl) authentication.getUserAuthentication().getPrincipal();
            if (user != null) {
                additionalInfo.put("userId", user.getUserId());
            }
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
            return accessToken;
        };
    }

}

 

经过这样写,最关键的问题是DefaultTokenService中的clientDetailsService还是InMemoryClientDetailsService,网上都说

clients.jdbc(dataSource);可以取代InMemoryClientDetailsService,搞不懂

 

欢迎遇到同样问题的人共同讨论

 

你可能感兴趣的:(java,框架设计)