美文网首页一个Java码农眼中的技术世界SpringJava 杂谈
spring-security-oauth2 中优雅的扩展自定义

spring-security-oauth2 中优雅的扩展自定义

作者: 邪影oO | 来源:发表于2018-11-20 16:27 被阅读1次

    之前搜了一下,都是使用 Filter 方式去实现,感觉这样破坏了 spring-security-oauth2 中的原有机制.啃了半天源码,发现一种稍微优雅一些的方式.

    本篇重点讨论如何实现自定义的登录方式,所以如何配制 spring-security-oauth2 就不说了.

    一些说明

    • 之前已经配好使用 spring-security-oauth2 + JWT 的认证方式,这次仅是改造
    • 本篇部分涉及的代码都是认证服务器的代码

    跟踪spring的登录逻辑发现,帐号密码的验证是在 tokenGranter 中完成的, 帐号密码对应的是 org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
    而spring找到对应的 tokenGranter 是通过登录时的一个表单参数"grant_type" 来找到的,这样的话,那我是不是可以通过扩展一个 TokenGranter 来达成我要的效果呢?

    spring 默认是同时支持多重 grant_type 的(根据客户端的配制决定特定客户端支持特定的 grant_type), 而AuthorizationServerConfigurerAdapter 的配制中 tokenGranter 又只能设置一个,那么spirng是怎么实现多个的呢?经过折腾我发现了一个 org.springframework.security.oauth2.provider.CompositeTokenGranter , 原来是通过它来实现的. 那么又有思路了.

    接下来研究如何向 CompositeTokenGranter 中增加我自定义的 TokenGranter , 结果发现spring在创建 CompositeTokenGranter 的时候已经把内置的 TokenGranter 写死了,没法通过它的机制扩展.唯一的方法就是我直接使用 CompositeTokenGranter . 那么我还是想要内置的 TokenGranter 也一起工作怎么办...?最后我无奈的选侧了把创建内置 TokenGranter 的代码copy了出来并修改了能用...不说了,直接上代码,有些需要注意的地方我会通过注释来描述.

    由于是已有项目的改造,所以怎么配制 spring-security-oauth2 + JWT ,怎么配制认证服务器和资源服务器,甚至oauth2 是什么?我就不多说了,网上一搜一大把.如果有同学实在需要的话,我再另开一篇来写吧

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.http.HttpMethod;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.core.authority.AuthorityUtils;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.oauth2.common.OAuth2AccessToken;
    import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
    import org.springframework.security.oauth2.provider.ClientDetails;
    import org.springframework.security.oauth2.provider.ClientDetailsService;
    import org.springframework.security.oauth2.provider.CompositeTokenGranter;
    import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
    import org.springframework.security.oauth2.provider.TokenGranter;
    import org.springframework.security.oauth2.provider.TokenRequest;
    import org.springframework.security.oauth2.provider.client.BaseClientDetails;
    import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;
    import org.springframework.security.oauth2.provider.client.InMemoryClientDetailsService;
    import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
    import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter;
    import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
    import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter;
    import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
    import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
    import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
    import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
    import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
    import org.springframework.security.oauth2.provider.token.TokenEnhancer;
    import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
    import org.springframework.security.oauth2.provider.token.TokenStore;
    import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
    import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
    import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
    
    
    /**
     * @ClassName: OAuth2AuthorizationServerConfig
     * @Description: spring-security OAuth2 配制,使用 jwt
     */
    @Configuration
    @EnableAuthorizationServer
    public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    
        @Autowired
        private AuthenticationManager authenticationManager;
        
        @Autowired
        private UserDetailsService userDetailsService;  // 这是提供根据用户名查用户的方式给spring使用的
        
        @Bean
        /**
        之前有个  public void configure(ClientDetailsServiceConfigurer clients) 配制客户端的方法,但是因为直接使  
        用 CompositeTokenGranter ,所以它不生效了,就在这里配制,同时使用这样的配制方式,后面可以改成从库里获取,自己实现一个 ClientDetailsService 就行
        由于之前的 Builder方式只能在 ClientDetailsServiceConfigurer 中使用,所以这里暂时先这样了,后面我要改为从库里获取
        */
        public ClientDetailsService clientDetailsService() {
        BaseClientDetails result = new BaseClientDetails();
        result.setClientId("weixin_client");
        List<String> authorizedGrantTypes = new ArrayList<>();
        authorizedGrantTypes.add("password");
        authorizedGrantTypes.add("refresh_token");
        result.setAuthorizedGrantTypes(authorizedGrantTypes);  // 这个 client 支持的 grant_type 
        result.setClientSecret("$2a$10$9s0p62wfKh7WT64a/VYFpOAk19GsrHh5C7Ty9.wPRWX40cjq7Rmu."); // 这个密码是用  org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder 搞出来的,明文是 123456
        List<String> scopes = new ArrayList<>();
        scopes.add("select");
        result.setScope(scopes);
        result.setAuthorities(AuthorityUtils.createAuthorityList("client"));
    
        Map<String, ClientDetails> clientDetails = new HashMap<String, ClientDetails>();
        clientDetails.put(result.getClientId(), result);
    
        InMemoryClientDetailsService clientDetailsService = new InMemoryClientDetailsService();
        clientDetailsService.setClientDetailsStore(clientDetails);
        return clientDetailsService;
        }
    
        private AuthorizationCodeServices authorizationCodeServices() {
          return new InMemoryAuthorizationCodeServices();  //使用默认
        }
    
        private OAuth2RequestFactory requestFactory() {
          return new DefaultOAuth2RequestFactory(clientDetailsService());  //使用默认
        }
    
    /**
    这是从spring 的代码中 copy出来的,默认的几个 TokenGranter, 我们自定义的就加到这里就行了,目前我还没有加
    */
        private List<TokenGranter> getDefaultTokenGranters() { 
        ClientDetailsService clientDetails = clientDetailsService();
        AuthorizationServerTokenServices tokenServices = tokenServices();
        AuthorizationCodeServices authorizationCodeServices = authorizationCodeServices();
        OAuth2RequestFactory requestFactory = requestFactory();
    
        List<TokenGranter> tokenGranters = new ArrayList<TokenGranter>();
        tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices,
            authorizationCodeServices, clientDetails, requestFactory));
        tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetails, requestFactory));
        ImplicitTokenGranter implicit = new ImplicitTokenGranter(tokenServices, clientDetails,
            requestFactory);
        tokenGranters.add(implicit);
        tokenGranters.add(
            new ClientCredentialsTokenGranter(tokenServices, clientDetails, requestFactory));
        if (authenticationManager != null) {
            tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager,
                tokenServices, clientDetails, requestFactory));
        }
        return tokenGranters;
        }
    
    /**
    通过 tokenGranter 塞进去的就是它了
    */
        private TokenGranter tokenGranter() {
        TokenGranter tokenGranter = new TokenGranter() {
            private CompositeTokenGranter delegate;
    
            @Override
            public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
            if (delegate == null) {
                delegate = new CompositeTokenGranter(getDefaultTokenGranters());
            }
            return delegate.grant(grantType, tokenRequest);
            }
        };
        return tokenGranter;
        }
        
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.tokenStore(tokenStore())
    //      .accessTokenConverter(accessTokenConverter())
                .tokenGranter(tokenGranter())
    //      .tokenEnhancer(tokenEnhancerChain)  // 设了 tokenGranter 后该配制失效,需要在 tokenServices() 中设置
            .authenticationManager(authenticationManager)
            .userDetailsService(userDetailsService)  //refresh_token 需要配制它,否则会 UserDetailsService is required
            .allowedTokenEndpointRequestMethods(HttpMethod.POST);
        }
        
        @Bean
        public TokenEnhancer tokenEnhancer() {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(new CustomTokenEnhancer(), accessTokenConverter()));   // CustomTokenEnhancer 是我自定义一些数据放到token里用的
            return tokenEnhancerChain;
        }
        
        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            //允许表单认证
            oauthServer.allowFormAuthenticationForClients();
    //        .checkTokenAccess("permitAll()");  // 允许 check_token, 因为用了JWT,客户端可以验证签名,生产中可以不用
        }
        
    
        @Bean
        public TokenStore tokenStore() {
            return new JwtTokenStore(accessTokenConverter());
        }
    
        @Bean
        public JwtAccessTokenConverter accessTokenConverter() {
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("authorizationKey.jks"), "123456".toCharArray());
        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("klw"));
        return converter;
        }
    
        @Bean
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
            defaultTokenServices.setTokenStore(tokenStore());
            defaultTokenServices.setSupportRefreshToken(true);
            defaultTokenServices.setTokenEnhancer(tokenEnhancer());   // 如果没有设置它,JWT就失效了.
            return defaultTokenServices;
        }
        
        
    }
    
    

    到这里,我们就可以愉快的自己扩展 TokenGranter了, 参考 ResourceOwnerPasswordTokenGranter, 并把它加到 getDefaultTokenGranters() 返回的那个 list 中

    未完待续...

    相关文章

      网友评论

        本文标题:spring-security-oauth2 中优雅的扩展自定义

        本文链接:https://www.haomeiwen.com/subject/rgrxqqtx.html