跟蹤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; } }
到這里,我們就可以愉快的自己擴展 TokenGranter了, 參考 ResourceOwnerPasswordTokenGranter, 並把它加到 getDefaultTokenGranters() 返回的那個 list 中