1. 程式人生 > 實用技巧 >spring-security-oauth2 中優雅的擴充套件自定義(簡訊驗證碼)登入方式-系列2

spring-security-oauth2 中優雅的擴充套件自定義(簡訊驗證碼)登入方式-系列2

跟蹤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了出來並修改了能用...不說了,直接上程式碼,有些需要注意的地方我會通過註釋來描述.

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;
    }
    
    
}