OAuth2 源码分析(一.核心类)

原文章链接:https://blog.csdn.net/qq_30905661/article/details/81112305
Spring Security源码解析篇
介绍了Spring Security的原理,复习下几个概念

Principle GrantedAuthority Authentication AbstractAuthenticationToken UsernamePasswordAuthenticationToken
AuthenticationManager AuthenticationProvider DaoAuthenticationProvider ProviderManager
UserDetail CredentialsContainer UserDetailsService UserCache
WebSecurityConfigurerAdapter WebSecurity HttpSecuirty FilterChainProxy
接下来介绍oauth2的相关概念。oauth2是建立在spring security基础上的一套规范,并非框架。

主要角色有

  • 授权服务器 AuthorizationServer 配置client,tokenStore,authenticationManager等
  • 资源服务器 ResourceServer 配置HttpSecurity,哪些uri需要验证;配置ResourceServerSecurityConfigurer,如设置tokenService
  • 客户端 client 包含clientid,secret
  • 用户 user 包含username,password

一般来说,资源服务器和授权服务器都是一个机构提供的,授权服务器给客户端授权,客户端再去请求资源服务器(授权服务器和资源服务器可以是一个应用程序也可以是两个应用程序)。下面例子中的QQ既是资源服务器,也是授权服务器。

用户想登录csdn(客户端),发现还没有注册csdn(客户端)的账号,刚好看见有一个通过QQ登录的方式,遂输入QQ的账户密码,点击授权。此时QQ服务器(授权服务器)对csdn(客户端)和用户密码进行验证,验证成功后给csdn(客户端)发放令牌,csdn凭借令牌去获取用户的QQ头像(资源服务器)等信息。
[

](https://blog.csdn.net/qq_30905661/article/details/81112305)

1. 好基友一辈子OAuth2Authentication和OAuth2AccessToken

1.1 OAuth2Authentication

OAuth2Authentication顾名思义是Authentication的子类,存储用户信息和客户端信息,但多了2个属性

  1. private final OAuth2Request storedRequest;
  2. private final Authentication userAuthentication;

这样OAuth2Authentication可以存储2个Authentication,一个给client(必要),一个给user(只是有些授权方式需要)。除此之外同样有principle,credentials,authorities,details,authenticated等属性。
OAuth2Request用于存储request中的Authentication信息(grantType,responseType,resouceId,clientId,scope等),这里就引出了OAuth2 中的三大request。

1.2 BaseRequest

BaseRequest是抽象类,有3个属性:clienId、scope和requestParameters。

  1. abstract class BaseRequest implements Serializable {
  2. private String clientId;
  3. private Set<String> scope = new HashSet<String>();
  4. private Map<String, String> requestParameters = Collections
  5. .unmodifiableMap(new HashMap<String, String>());
  6. /** setter,getter */
  7. }


继承类见下图,3个类都在OAuth2包中,这些request都会存在于OAuth2的验证流程中,用于传递clientId,scope,requestParameters等属性,与HttpServletRequest有本质区别!
image.png

1.2.1 AuthorizationRequest

向授权服务器AuthorizationEndPoint (/oauth/authorize)请求授权,AuthorizationRequest作为载体存储state,redirect_uri等参数,生命周期很短且不能长时间存储信息,可用OAuth2Request代替存储信息。

  1. public class AuthorizationRequest extends BaseRequest implements Serializable {
  2. // 用户同意授权传递的参数,不可改变
  3. private Map<String, String> approvalParameters = Collections.unmodifiableMap(new HashMap<String, String>());
  4. // 客户端发送出的状态信息,从授权服务器返回的状态应该不变才对
  5. private String state;
  6. // 返回类型集合
  7. private Set<String> responseTypes = new HashSet<String>();
  8. // resource ids 可变
  9. private Set<String> resourceIds = new HashSet<String>();
  10. // 授权的权限
  11. private Collection<? extends GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
  12. // 终端用户是否同意该request发送
  13. private boolean approved = false;
  14. // 重定向uri
  15. private String redirectUri;
  16. // 额外的属性
  17. private Map<String, Serializable> extensions = new HashMap<String, Serializable>();
  18. // 持久化到OAuth2Request
  19. public OAuth2Request createOAuth2Request() {
  20. return new OAuth2Request(getRequestParameters(), getClientId(), getAuthorities(), isApproved(), getScope(), getResourceIds(), getRedirectUri(), getResponseTypes(), getExtensions());
  21. }
  22. // setter,getter
  23. }


1.2.2 TokenRequest

向授权服务器TokenEndPoint(/oauth/token)发送请求获得access_token时,tokenRequest作为载体存储请求中grantType等参数。常和tokenGranter.grant(grantType,tokenRequest)结合起来使用。
TokenRequest携带了新属性grantType,和方法createOAuth2Request(用于持久化)

  1. private String grantType;
  2. public OAuth2Request createOAuth2Request(ClientDetails client) {
  3. Map<String, String> requestParameters = getRequestParameters();
  4. HashMap<String, String> modifiable = new HashMap<String, String>(requestParameters);
  5. // Remove password if present to prevent leaks
  6. modifiable.remove("password");
  7. modifiable.remove("client_secret");
  8. // Add grant type so it can be retrieved from OAuth2Request
  9. modifiable.put("grant_type", grantType);
  10. return new OAuth2Request(modifiable, client.getClientId(), client.getAuthorities(), true, this.getScope(),
  11. client.getResourceIds(), null, null, null);
  12. }


1.2.3 OAuth2Request

用来存储TokenRequest或者AuthorizationRequest的信息,只有构造方法和getter方法,不提供setter方法。它作为OAuth2Authentication的一个属性(StoredRequest),存储request中的authentication信息(grantType,approved,responseTypes)。

1.2.4 OAuth2RequestFactory

工厂类生成OAuth2Request、TokenRequest、AuthenticationRequest。

  1. public interface OAuth2RequestFactory {
  2. /**
  3. * 从request请求参数中获取clientId,scope,state
  4. * clientDetailsService loadClientByClientId(clientId) 获取clientDetails resourcesId Authorities
  5. * 根据以上信息生成AuthenticationRequest
  6. */
  7. AuthorizationRequest createAuthorizationRequest(Map<String, String> authorizationParameters);
  8. /**
  9. * AuthorizationRequest request 有生成OAuth2Request的方法
  10. * request.createOAuth2Request()
  11. */
  12. OAuth2Request createOAuth2Request(AuthorizationRequest request);
  13. OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest);
  14. TokenRequest createTokenRequest(Map<String, String> requestParameters, ClientDetails authenticatedClient);
  15. TokenRequest createTokenRequest(AuthorizationRequest authorizationRequest, String grantType);
  16. }


1.3 OAuth2AccessToken

OAuth2AccessToken是一个接口,提供安全令牌token的基本信息,不包含用户信息,仅包含一些静态属性(scope,tokenType,expires_in等)和getter方法,如String getScope,OAuth2RefreshToken getRefreshToken,String getTokenType,String getValue()等。TokenGranter.grant()返回的值即OAuth2AccessToken。
OAuth2AccessToken和OAuth2Authentication是一对好基友,谁要先走谁是狗!!!
TokenStore同时存储OAuth2AccessToken和OAuth2Authentication,也可根据OAuth2Authentication中的OAuth2Request信息可获取对应的OAuth2AccessToken。
DefaultTokenServices有如下方法,都可以通过一个获得另一个的值

  1. OAuth2AccessToken createAccessToken(OAuth2Authentication authentication)
  2. OAuth2Authentication loadAuthentication(String accessTokenValue)
  3. // 当tokenStore是jdbcTokenStore,表示从数据库中根据OAuth2Authentication获取OAuth2AccessToken
  4. OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);

image.png

DefaultOAuth2AccessToken是OAuth2AccessToken的实现类,多了构造方法,setter方法和OAuth2AccessToken valueOf(Map tokenParams)。经过json转换后就是我们常见的access_token对象,如下所示。

  1. {
  2. "access_token": "1e95d081-0048-4397-a081-c76f7823fe54",
  3. "token_type": "bearer",
  4. "refresh_token": "7f6db28b-50dc-40a2-b381-3e356e30af2b",
  5. "expires_in": 1799,
  6. "scope": "read write"
  7. }

OAuth2RefreshToken是接口,只有String getValue()方法。
DefaultOAuth2RefreshToken是OAuth2RefreshToken的实现类。

2. TokenGranter、TokenStore、TokenExtractor

2.1 TokenGranter(/oauth/token)

一般在用户请求TokenEndPoints中的路径/oauth/token时,根据请求参数中的grantType,username,password,client_id,client_secret等,调用TokenGranter给用户分发OAuth2AccessToken。
根据grantType(password,authorization-code)和TokenRequest(requestParameters,clientId,grantType)授予人OAuth2AccessToken令牌。

  1. public interface TokenGranter {
  2. OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest);
  3. }


回忆下TokenRequest包含了基本信息clientId,scope,requestParameters,grantType等。根据tokenRequest获取OAuth2Request,初始化获得OAuth2Authentication,再去数据库里找oauth2accesstoken,如果有则直接返回,如果没有则创建新的oauth2accesstoken,并且和OAuth2Authentication一起存入数据库中。

2.1.1 AbstractTokenGranter

TokenGranter抽象继承类AbstractTokenGranter,实现了grant方法,源码如下。
执行顺序为根据tokenRequest====》clientId====》clientDetails====》OAuth2Authentication(getOAuth2Authentication(client,tokenRequest))====》OAuth2AccessToken(tokenService.createAccessToken)

  1. public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
  2. if (!this.grantType.equals(grantType)) {
  3. return null;
  4. }
  5. String clientId = tokenRequest.getClientId();
  6. ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
  7. validateGrantType(grantType, client);
  8. logger.debug("Getting access token for: " + clientId);
  9. // getAccessToken 先获得OAuth2Authentication,再创建OAuth2AccessToken
  10. return getAccessToken(client, tokenRequest);
  11. }
  12. protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) {
  13. return tokenServices.createAccessToken(getOAuth2Authentication(client, tokenRequest));
  14. }
  15. // AbstractTokenGranter的继承类重写了该方法
  16. protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
  17. OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(client, tokenRequest);
  18. return new OAuth2Authentication(storedOAuth2Request, null);
  19. }


实现AbstractTokenGranter的类有5种。其中如果用password的方式进行验证,那么TokenGranter类型是ResourceOwnerPasswordTokenGranter,该类中重写了getOAuth2Authentication方法,里面调用了authenticationManager.manage()方法。
用户可自行定义granter类继承AbstractTokenGranter,重写getOAuth2Authentication()方法,并将该granter类添加至CompositeTokenGranter中。
TokenGranter的继承类如下图所示
image.png

2.1.2 CompositeTokenGranter

有继承类CompositeTokenGranter,包含List tokenGranters属性,grant方法是遍历tokenGranters进行逐一grant,只要有一个有返回值就返回。

  1. public class CompositeTokenGranter implements TokenGranter {
  2. private final List<TokenGranter> tokenGranters;
  3. public CompositeTokenGranter(List<TokenGranter> tokenGranters) {
  4. this.tokenGranters = new ArrayList<TokenGranter>(tokenGranters);
  5. }
  6. public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
  7. for (TokenGranter granter : tokenGranters) {
  8. OAuth2AccessToken grant = granter.grant(grantType, tokenRequest);
  9. if (grant!=null) {
  10. return grant;
  11. }
  12. }
  13. return null;
  14. }
  15. public void addTokenGranter(TokenGranter tokenGranter) {
  16. if (tokenGranter == null) {
  17. throw new IllegalArgumentException("Token granter is null");
  18. }
  19. tokenGranters.add(tokenGranter);
  20. }
  21. }


2.2 TokenStore(/oauth/token)

一般在TokenGranter执行grant方法完毕后,将OAuth2AccessToken和OAuth2Authentication存储起来,方便以后根据其中一个查询另外一个(如根据access_token查询获得OAuth2Authentication)。
存储OAuth2AccessToken和OAuth2Authentication(比Authentication多了两个属性storedRequest,userAuthentication),存储方法如下。还有各种read,remove方法
void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication);
实现类有5类,其中JdbcTokenStore是通过连接数据库来存储OAuth2AccessToken的,这也是我们一般存储token的方法。条件是数据库里的表结构必须按照标准建立。(JwtTokenStore不存储token和authentication,直接根据token解析获得authentication)
image.png

oauth_access_token表结构如下,可见表里存储了OAuth2AccessToken和OAuth2Authentication两个对象,值得注意的是token_id并不等于OAuth2AccessToken.getValue(),value经过MD5加密后才是token_id。同理authentication_id 和 refresh_token也是经过加密转换存储的。
第一次获得token,直接存入数据库表里。
如果重复post请求/oauth/token, JdbcTokenStore会先判断表中是否已有该用户的token,如果有先删除,再添加。
image.png

2.3 TokenExtractor (OAuth2AuthentiactionProcessingFilter)

用户携带token访问资源,过滤器进行到OAuth2AuthentiactionProcessingFilter时,从HttpServletRequest中获取access_token(可以从header或者params中获取),拼接成PreAuthenticatedAuthenticationToken(Authentication子类)
Authentication extract(HttpServletRequest request);
BearerTokenExtractor是它的实现类,实现了从request中获取Authentication的方法。
1.header中 Authentication:Bearer xxxxxxxx—xxx
2.request parameters中 access_token=xxxx-xxxx-xxxx

  1. protected String extractToken(HttpServletRequest request) {
  2. // 1.直接从header中提取key为Authentication,value是以Bearer 开头的header
  3. // 如Authentication:Bearer f732723d-af7f-41bb-bd06-2636ab2be135
  4. String token = extractHeaderToken(request);
  5. // bearer type allows a request parameter as well
  6. if (token == null) {
  7. logger.debug("Token not found in headers. Trying request parameters.");
  8. // 2.如果header中不包含,则从param中获取"access_token"对应的值
  9. token = request.getParameter(OAuth2AccessToken.ACCESS_TOKEN);
  10. if (token == null) {
  11. logger.debug("Token not found in request parameters. Not an OAuth2 request.");
  12. }
  13. else {
  14. request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, OAuth2AccessToken.BEARER_TYPE);
  15. }
  16. }
  17. return token;
  18. }


2.4 ResourceServerTokenServices

两个方法。用户携access_token访问资源服务器时,资源服务器会将该字符串进行解析,获得OAuth2Authentication和OAuth2AccessToken。
loadAuthentication根据字符串accessToken获得OAuth2Authentication;
readAccessToken根据字符串accessToken获得OAuth2AccessToken。

  1. public interface ResourceServerTokenServices {
  2. /**
  3. * Load the credentials for the specified access token.
  4. *
  5. * @param accessToken The access token value.
  6. * @return The authentication for the access token.
  7. * @throws AuthenticationException If the access token is expired
  8. * @throws InvalidTokenException if the token isn't valid
  9. */
  10. OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException;
  11. /**
  12. * Retrieve the full access token details from just the value.
  13. *
  14. * @param accessToken the token value
  15. * @return the full access token with client id etc.
  16. */
  17. OAuth2AccessToken readAccessToken(String accessToken);
  18. }


有两重要继承类,DefaultTokenServices和RemoteTokenServices

2.4.1 DefaultTokenServices

实现了两个接口AuthorizationServerTokenServices和ResourceServerTokenServices。常在granter().grant()方法中调用tokenServices.createAccessToken()方法获得oauth2accesstoken。
image.png

其中重要方法createAccessToken(OAuth2Authentication oauth2)源码如下

  1. @Transactional
  2. public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
  3. OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication);
  4. OAuth2RefreshToken refreshToken = null;
  5. // 如果数据库中已存了authentication和accesstoken,则直接提取
  6. if (existingAccessToken != null) {
  7. if (existingAccessToken.isExpired()) {
  8. if (existingAccessToken.getRefreshToken() != null) {
  9. refreshToken = existingAccessToken.getRefreshToken();
  10. // The token store could remove the refresh token when the
  11. // access token is removed, but we want to
  12. // be sure...
  13. tokenStore.removeRefreshToken(refreshToken);
  14. }
  15. tokenStore.removeAccessToken(existingAccessToken);
  16. }
  17. else {
  18. // Re-store the access token in case the authentication has changed
  19. tokenStore.storeAccessToken(existingAccessToken, authentication);
  20. return existingAccessToken;
  21. }
  22. }
  23. // Only create a new refresh token if there wasn't an existing one
  24. // associated with an expired access token.
  25. // Clients might be holding existing refresh tokens, so we re-use it in
  26. // the case that the old access token
  27. // expired.
  28. if (refreshToken == null) {
  29. refreshToken = createRefreshToken(authentication);
  30. }
  31. // But the refresh token itself might need to be re-issued if it has
  32. // expired.
  33. else if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
  34. ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken;
  35. if (System.currentTimeMillis() > expiring.getExpiration().getTime()) {
  36. refreshToken = createRefreshToken(authentication);
  37. }
  38. }
  39. // 第一次创建access_token,并且存储到数据库中
  40. OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken);
  41. tokenStore.storeAccessToken(accessToken, authentication);
  42. // In case it was modified
  43. refreshToken = accessToken.getRefreshToken();
  44. if (refreshToken != null) {
  45. tokenStore.storeRefreshToken(refreshToken, authentication);
  46. }
  47. return accessToken;
  48. }


2.4.2 RemoteTokenServices

当授权服务和资源服务不在一个应用程序的时候,资源服务可以把传递来的accesstoken递交给授权服务的/oauth/check_token进行验证,而资源服务自己无需去连接数据库验证access_token,这时就用到了RemoteTokenServices。
loadAuthentication方法,设置head表头Authorization 存储clientId和clientSecret信息,请求参数包含access_token字符串,向AuthServer的CheckTokenEndpoint(/oauth/check_token)发送请求,返回验证结果map(包含clientId,grantType,scope,username等信息),拼接成OAuth2Authentication。
**
重要!!!_**
AuthServer需要配置checkTokenAcess,否则默认为“denyAll()”,请求访问/oauth/check_token会提示没权限。

  1. @Override
  2. public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
  3. oauthServer.realm(QQ_RESOURCE_ID).allowFormAuthenticationForClients();
  4. // 访问/oauth/check_token 需要client验证
  5. oauthServer.checkTokenAccess("isAuthenticated()");、
  6. // 也可配置访问/oauth/check_token无需验证
  7. // oauthServer.checkTokenAccess("permitAll()");
  8. }


不支持readAccessToken方法。

  1. public class RemoteTokenServices implements ResourceServerTokenServices {
  2. protected final Log logger = LogFactory.getLog(getClass());
  3. private RestOperations restTemplate;
  4. private String checkTokenEndpointUrl;
  5. private String clientId;
  6. private String clientSecret;
  7. private String tokenName = "token";
  8. private AccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
  9. @Override
  10. public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
  11. MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
  12. formData.add(tokenName, accessToken);
  13. HttpHeaders headers = new HttpHeaders();
  14. headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
  15. Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers);
  16. if (map.containsKey("error")) {
  17. logger.debug("check_token returned error: " + map.get("error"));
  18. throw new InvalidTokenException(accessToken);
  19. }
  20. Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
  21. return tokenConverter.extractAuthentication(map);
  22. }
  23. @Override
  24. public OAuth2AccessToken readAccessToken(String accessToken) {
  25. throw new UnsupportedOperationException("Not supported: read access token");
  26. }
  27. }


3. ClientDetails ClientDetailsService
这两个概念简单的有些可怕,完全就是UserDetails和UserDetailsService的翻版。一个是对应user,一个是对应client。
client需要事先注册到授权服务器,这样授权服务器会根据client的授权请求获取clientId,secret等信息,进行验证后返回token。

3.1 ClientDetails

client的信息,存于授权服务器端,这样只需要知道客户端的clientId,就可以获取到客户端能访问哪些资源,是否需要密码,是否限制了scope,拥有的权限等等。

  1. public interface ClientDetails extends Serializable {
  2. String getClientId();
  3. // client能访问的资源id
  4. Set<String> getResourceIds();
  5. // 验证client是否需要密码
  6. boolean isSecretRequired();
  7. String getClientSecret();
  8. // client是否限制了scope
  9. boolean isScoped();
  10. // scope集合
  11. Set<String> getScope();
  12. // 根据哪些grantType验证通过client
  13. Set<String> getAuthorizedGrantTypes();
  14. // 注册成功后跳转的uri
  15. Set<String> getRegisteredRedirectUri();
  16. // client拥有的权限
  17. Collection<GrantedAuthority> getAuthorities();
  18. // client的token时效
  19. Integer getAccessTokenValiditySeconds();
  20. // client的refreshToken时效
  21. Integer getRefreshTokenValiditySeconds();
  22. // true:默认自动授权;false:需要用户确定才能授权
  23. boolean isAutoApprove(String scope);
  24. // 额外的信息
  25. Map<String, Object> getAdditionalInformation();
  26. }


3.2 ClientDetailsService

根据clientId获取clientDetails

  1. public interface ClientDetailsService {
  2. /**
  3. * Load a client by the client id. This method must not return null.
  4. *
  5. * @param clientId The client id.
  6. * @return The client details (never null).
  7. * @throws ClientRegistrationException If the client account is locked, expired, disabled, or invalid for any other reason.
  8. */
  9. ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException;
  10. }

有两个子类InMemoryClientDetailsService(内存) 和 JdbcClientDetailsService(数据库,OAUTH_CLIENT_DETAILS、OAUTH_CLIENT_TOKEN表等)。说白了就是一个是把ClientDetails存内存里,一个存数据库里(oauth_client_details表)。
一般在AuthServer中配置ClientDetailsServiceConfigurer。
1、配置JdbcDetailsService

  1. @Bean
  2. public ClientDetailsService clientDetails() {
  3. return new JdbcClientDetailsService(dataSource);
  4. }
  5. /**
  6. * 配置客户端 a configurer that defines the client details service.
  7. * Client details can be initialized, or you can just refer to an existing store.
  8. */
  9. @Override
  10. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  11. clients.withClientDetails(clientDetails());
  12. }

2、配置InMemoryClientDetailsService

  1. @Override
  2. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  3. // @formatter:off
  4. clients.inMemory().withClient("aiqiyi")
  5. .resourceIds(QQ_RESOURCE_ID)
  6. .authorizedGrantTypes("authorization_code", "refresh_token", "implicit")
  7. .authorities("ROLE_CLIENT")
  8. // , "get_fanslist"
  9. .scopes("get_fanslist")
  10. .secret("secret")
  11. .redirectUris("http://localhost:8081/aiqiyi/qq/redirect")
  12. .autoApprove(true)
  13. .autoApprove("get_user_info")
  14. .and()
  15. .withClient("youku")
  16. .resourceIds(QQ_RESOURCE_ID)
  17. .authorizedGrantTypes("authorization_code", "refresh_token", "implicit")
  18. .authorities("ROLE_CLIENT")
  19. .scopes("get_user_info", "get_fanslist")
  20. .secret("secret")
  21. .redirectUris("http://localhost:8082/youku/qq/redirect");
  22. // @formatter:on
  23. }


3.3 ClientDetailsServiceBuilder

创建InMemoryClientDetailsService或者JdbcClientDetailsService,有内部类ClientBuilder。

  1. public class ClientDetailsServiceBuilder<B extends ClientDetailsServiceBuilder<B>> extends
  2. SecurityConfigurerAdapter<ClientDetailsService, B> implements SecurityBuilder<ClientDetailsService> {
  3. private List<ClientBuilder> clientBuilders = new ArrayList<ClientBuilder>();
  4. public InMemoryClientDetailsServiceBuilder inMemory() throws Exception {
  5. return new InMemoryClientDetailsServiceBuilder();
  6. }
  7. public JdbcClientDetailsServiceBuilder jdbc() throws Exception {
  8. return new JdbcClientDetailsServiceBuilder();
  9. }
  10. @SuppressWarnings("rawtypes")
  11. public ClientDetailsServiceBuilder<?> clients(final ClientDetailsService clientDetailsService) throws Exception {
  12. return new ClientDetailsServiceBuilder() {
  13. @Override
  14. public ClientDetailsService build() throws Exception {
  15. return clientDetailsService;
  16. }
  17. };
  18. }
  19. // clients.inMemory().withClient("clientId").scopes().secret()...
  20. public ClientBuilder withClient(String clientId) {
  21. ClientBuilder clientBuilder = new ClientBuilder(clientId);
  22. this.clientBuilders.add(clientBuilder);
  23. return clientBuilder;
  24. }
  25. @Override
  26. public ClientDetailsService build() throws Exception {
  27. for (ClientBuilder clientDetailsBldr : clientBuilders) {
  28. addClient(clientDetailsBldr.clientId, clientDetailsBldr.build());
  29. }
  30. return performBuild();
  31. }
  32. protected void addClient(String clientId, ClientDetails build) {
  33. }
  34. protected ClientDetailsService performBuild() {
  35. throw new UnsupportedOperationException("Cannot build client services (maybe use inMemory() or jdbc()).");
  36. }
  37. public final class ClientBuilder {
  38. // ...
  39. public ClientDetailsServiceBuilder<B> and() {
  40. return ClientDetailsServiceBuilder.this;
  41. }
  42. }
  43. }


4. 资源服务器配置 ResourceServerConfigurerAdapter

配置哪些路径需要认证后才能访问,哪些不需要。自然就联想到了HttpSecurity(配置HttpSecurity就相当于配置了不同uri对应的filters)。
Spring Security中我们是这样配置WebSecurityConfigurerAdapter的。

  1. @Configuration
  2. @EnableWebSecurity
  3. public class SecurityConfig extends WebSecurityConfigurerAdapter
  4. {
  5. @Override
  6. protected void configure(HttpSecurity http) throws Exception {
  7. http
  8. .csrf().disable()
  9. .authorizeRequests()
  10. .anyRequest().authenticated()//所有请求必须登陆后访问
  11. .and().httpBasic()
  12. .and()
  13. .formLogin()
  14. .loginPage("/login")
  15. .defaultSuccessUrl("/index")
  16. .failureUrl("/login?error")
  17. .permitAll()//登录界面,错误界面可以直接访问
  18. .and()
  19. .logout().logoutUrl("/logout").logoutSuccessUrl("/login")
  20. .permitAll().and().rememberMe();//注销请求可直接访问
  21. }
  22. @Override
  23. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  24. auth.inMemoryAuthentication().withUser("user").password("password").roles("USER").and()
  25. .withUser("admin").password("password").roles("USER", "ADMIN");
  26. }
  27. }

作为资源服务器ResourceServerConfigurerAdapter,需要和@EnableResourceServer搭配,然后和上面一样需配置HttpSecurity就好了。还能配置ResourceServerSecurityConfigurer,设置tokenService等

  1. /**
  2. * 配置资源服务器
  3. */
  4. @Configuration
  5. @EnableResourceServer
  6. protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
  7. @Autowired
  8. private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
  9. @Autowired
  10. private CustomLogoutSuccessHandler customLogoutSuccessHandler;
  11. @Override
  12. public void configure(HttpSecurity http) throws Exception {
  13. http
  14. .exceptionHandling()
  15. .authenticationEntryPoint(customAuthenticationEntryPoint)
  16. .and()
  17. .logout()
  18. .logoutUrl("/oauth/logout")
  19. .logoutSuccessHandler(customLogoutSuccessHandler)
  20. .and()
  21. .authorizeRequests()
  22. // hello路径允许直接访问
  23. .antMatchers("/hello/").permitAll()
  24. // secure路径需要验证后才能访问
  25. .antMatchers("/secure/**").authenticated();
  26. }
  27. // 远程连接authServer服务
  28. @Autowired
  29. public RemoteTokenServices remoteTokenServices;
  30. @Override
  31. public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
  32. resources.tokenServices(remoteTokenServices);
  33. }
  34. }


5. 授权服务器配置 AuthorizationServerConfigurerAdapter

注册client信息,可以同时配置多个不同类型的client。

  1. /**
  2. * 配置认证服务器 @EnableAuthorizationServer自动注册到spring context中
  3. */
  4. @EnableAuthorizationServer
  5. protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {
  6. private static final String ENV_OAUTH = "authentication.oauth.";
  7. private static final String PROP_CLIENTID = "clientid";
  8. private static final String PROP_SECRET = "secret";
  9. private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";
  10. private RelaxedPropertyResolver propertyResolver;
  11. @Autowired
  12. private DataSource dataSource;
  13. @Bean
  14. public TokenStore tokenStore() {
  15. return new JdbcTokenStore(dataSource);
  16. }
  17. @Autowired
  18. @Qualifier("authenticationManagerBean")
  19. private AuthenticationManager authenticationManager;
  20. /**
  21. * 可以设置tokenStore,tokenGranter,authenticationManager,requestFactory等接口使用什么继承类,但一般沿用默认的就好了
  22. * 如果使用的是密码方式授权,则必须设置authenticationManager
  23. */
  24. @Override
  25. public void configure(AuthorizationServerEndpointsConfigurer endpoints)
  26. throws Exception {
  27. endpoints
  28. .tokenStore(tokenStore())
  29. .authenticationManager(authenticationManager);
  30. }
  31. /**
  32. * 注册clients到授权服务器,这里是注册到内存中,且配置了scopes,authorities等信息
  33. */
  34. @Override
  35. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  36. clients
  37. .inMemory()
  38. .withClient(propertyResolver.getProperty(PROP_CLIENTID))
  39. .scopes("read", "write")
  40. .authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name())
  41. .authorizedGrantTypes("password", "refresh_token")
  42. .secret(propertyResolver.getProperty(PROP_SECRET))
  43. // 给客户端的token时效为1800秒
  44. .accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 1800));
  45. }
  46. @Override
  47. public void setEnvironment(Environment environment) {
  48. this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
  49. }
  50. }


6.TokenEndPoint,AuthorizationEndPoint,CheckTokenEndPoint

6.1 TokenEndPoint

客户端post请求”/oauth/token”,验证用户信息并获取OAuth2AccessToken,必须先经过client验证。这一步的最终目的是存储OAuth2AccessToken+OAuth2Authentication并返回OAuth2AccessToken。

  1. @RequestMapping(value = "/oauth/token", method=RequestMethod.POST)
  2. public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam
  3. Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
  4. if (!(principal instanceof Authentication)) {
  5. throw new InsufficientAuthenticationException(
  6. "There is no client authentication. Try adding an appropriate authentication filter.");
  7. }
  8. String clientId = getClientId(principal);
  9. ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
  10. TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
  11. ...
  12. // AuthorizationServerEndpointsConfigurer
  13. OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);
  14. if (token == null) {
  15. throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
  16. }
  17. return getResponse(token);
  18. }


6.2 AuthorizationEndPoint

这个一般只适用于authorization code模式,客户端请求authorization server中的/oauth/authorize(请求前先得登录oauth server获得authentication),验证client信息后根据redirect_uri请求重定向回client,同时带上code值。client附带code值再次向/oauth/token请求,返回accesstoken。
具体流程将在下章中介绍,这里只引出相关概念。

  1. @RequestMapping(value = "/oauth/authorize")
  2. public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
  3. SessionStatus sessionStatus, Principal principal) {
  4. // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should
  5. // query off of the authorization request instead of referring back to the parameters map. The contents of the
  6. // parameters map will be stored without change in the AuthorizationRequest object once it is created.
  7. AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);
  8. Set<String> responseTypes = authorizationRequest.getResponseTypes();
  9. if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
  10. throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
  11. }
  12. if (authorizationRequest.getClientId() == null) {
  13. throw new InvalidClientException("A client id must be provided");
  14. }
  15. try {
  16. if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {
  17. throw new InsufficientAuthenticationException(
  18. "User must be authenticated with Spring Security before authorization can be completed.");
  19. }
  20. ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId());
  21. // The resolved redirect URI is either the redirect_uri from the parameters or the one from
  22. // clientDetails. Either way we need to store it on the AuthorizationRequest.
  23. String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI);
  24. String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client);
  25. if (!StringUtils.hasText(resolvedRedirect)) {
  26. throw new RedirectMismatchException(
  27. "A redirectUri must be either supplied or preconfigured in the ClientDetails");
  28. }
  29. authorizationRequest.setRedirectUri(resolvedRedirect);
  30. // We intentionally only validate the parameters requested by the client (ignoring any data that may have
  31. // been added to the request by the manager).
  32. oauth2RequestValidator.validateScope(authorizationRequest, client);
  33. // Some systems may allow for approval decisions to be remembered or approved by default. Check for
  34. // such logic here, and set the approved flag on the authorization request accordingly.
  35. authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest,
  36. (Authentication) principal);
  37. // TODO: is this call necessary?
  38. boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal);
  39. authorizationRequest.setApproved(approved);
  40. // Validation is all done, so we can check for auto approval...
  41. if (authorizationRequest.isApproved()) {
  42. if (responseTypes.contains("token")) {
  43. return getImplicitGrantResponse(authorizationRequest);
  44. }
  45. if (responseTypes.contains("code")) {
  46. // 生成code值并返回
  47. return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest,
  48. (Authentication) principal));
  49. }
  50. }
  51. // Place auth request into the model so that it is stored in the session
  52. // for approveOrDeny to use. That way we make sure that auth request comes from the session,
  53. // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session.
  54. model.put("authorizationRequest", authorizationRequest);
  55. return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal);
  56. }
  57. catch (RuntimeException e) {
  58. sessionStatus.setComplete();
  59. throw e;
  60. }
  61. }

6.3 CheckTokenEndpoint

当采用RemoteTokenServices时,resouceServer无法自行验证access_token字符串是否正确,遂递交给另一个应用程序中的authserver里CheckTokenEndpoint(/oauth/check_token)进行检验,检验结果返回给resourceServer。

  1. @RequestMapping(value = "/oauth/check_token")
  2. @ResponseBody
  3. public Map<String, ?> checkToken(@RequestParam("token") String value) {
  4. OAuth2AccessToken token = resourceServerTokenServices.readAccessToken(value);
  5. if (token == null) {
  6. throw new InvalidTokenException("Token was not recognised");
  7. }
  8. if (token.isExpired()) {
  9. throw new InvalidTokenException("Token has expired");
  10. }
  11. OAuth2Authentication authentication = resourceServerTokenServices.loadAuthentication(token.getValue());
  12. Map<String, ?> response = accessTokenConverter.convertAccessToken(token, authentication);
  13. return response;
  14. }

7.总结

复习下这章讲到的知识点。
四大角色:ResouceServer AuthorizationServer client user
OAuth2AccessToken OAuth2Authentiaction
OAuth2Request TokenRequest AuthorizationRequest
TokenGranter TokenStore TokenExtractor DefaultTokenServices RemoteTokenServices
ResourceServerConfigurerAdapter AuthorizationServerConfigurerAdapter
TokenEndPoint(/oauth/token) AuthorizationEndPoint(/oauth/authorize) CheckTokenEndpoint(/oauth/check_token)

OAuth2 源码分析(二.授权码模式源码)

原文链接:https://blog.csdn.net/qq_30905661/article/details/82424552
上一章介绍了与OAuth2相关的核心类,让我们再复习一遍,如果有遗忘的地方请移步到上一章查看。
四大角色:ResouceServer AuthorizationServer client user
OAuth2AccessToken OAuth2Authentiaction
OAuth2Request TokenRequest AuthorizationRequest
TokenGranter TokenStore TokenExtractor DefaultTokenServices
ResourceServerConfigurerAdapter AuthorizationServerConfigurerAdapter
TokenEndPoint(/oauth/token) AuthorizationEndPoint(/oauth/authorize)
上面介绍的全是乐高积木的小部件,如何把积木拼起来才是关键。说到oauth2不可避免的就要聊到5种授权模式。
(1)授权码模式(Authorization Code)
(2)授权码简化模式(Implicit)
(3)Pwd模式(Resource Owner Password Credentials)
(4)Client模式(Client Credentials)
(5)扩展模式(Extension)
无论哪一种,核心思想都是client向authorization server发出请求,请求参数有client_id,client_secret,scope,response_type或redirect_uri等,authorization server经过验证后,返回client一个access_token。凭借这个access_token,client再去resource server中获取资源。这章只介绍授权码模式的流程

1.授权码模式流程图

image.png

没了解原理前是看着挺费劲的,一般的验证只需要client发出一次请求就能获得access_token,但授权码模式多了一个Authorization code。这样就分两步走,第一步请求/oauth/authorize获得Authorization code,第二步请求/oauth/token获得access_token。
这里就以登录csdn为例来解释授权码模式。
1.打开csdn登录页面,选择QQ登录。此时client为csdn,qq为authroization server和resouce server。qq授权服务器里存储了很多client信息,csdn只是众多client中的一个。
image.png

2.页面跳转至QQ授权页面,url地址是
https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=100270989&redirect_uri=https%3A%2F%2Fpassport.csdn.net%2Faccount%2Flogin%3Foauth_provider%3DQQProvider&state=test
里面有3个关键的参数,response_type,client_id以及redirect_uri。点击了下图中授权并登录的按钮后,页面自动跳转到了csdn主页,且获取到了QQ相关信息。看似很简单的跳转其实包含了很多步骤。
image.png

  1. ![image.png](https://cdn.nlark.com/yuque/0/2022/png/503586/1641456395922-32655b07-ef90-41dc-998a-f67a06fe4912.png#clientId=ued3eaad2-d50a-4&crop=0&crop=0&crop=1&crop=1&from=paste&id=ua11b6d16&margin=%5Bobject%20Object%5D&name=image.png&originHeight=171&originWidth=246&originalType=url&ratio=1&rotation=0&showTitle=false&size=19040&status=done&style=none&taskId=u05b1a11b-be9d-4d9b-b5d5-40974d6684d&title=)

3.用户填写用户名、密码后,点击授权并登录,首先访问qq授权服务器的/login路径,spring security验证username和password后给用户发放JSessionId的cookie,session中存储了Authentication。
4.再访问qq授权服务器/oauth/authorize,请求参数有response_type,redirect_uri,client_id,验证通过后请求重定向到redirect_uri,且传递Authorization code。
5.redirect_uri路径指向的是client中的一个endpoint,client接收到了code,表明client信息已经在QQ授权服务器验证成功。再凭借这个code值外加client_id,client_secret,grant_type=authorization_code,code,redirect_uri等参数,去访问QQ的/oauth/token,返回access_token。
6.获得access_token后,client再去找qq的资源服务器要资源。
一句话概括,就是按顺序依次获得authentication —-> Authorization code ——> access_token。

2. 源码分析

为了方便理解,这里先给出来自github lexburner的例子,项目地址是https://github.com/lexburner/oauth2-demo
项目内有Aiqiyi和qq两个服务,分别是client和authorization server,操作说明详见readme.md,这里不做赘述。
image.png

2.1 第一次请求/oauth/authorize

请求的完整url如下,有参数client_id,response_type,redirect_uri。

  1. http://localhost:8080/oauth/authorize?client_id=aiqiyi&response_type=code&redirect_uri=http://localhost:8081/aiqiyi/qq/redirect

访问AuthorizationEndPoint中的/oauth/authorize,里面会判断client信息和用户信息,如果user没有Authentication,则会报错,跳转到ExceptionTranslationFilter类中,请求转发到/login路径,并将现请求路径存储到session的saverequest中。

  1. @RequestMapping(value = "/oauth/authorize")
  2. public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
  3. SessionStatus sessionStatus, Principal principal) {
  4. AuthorizationRequest authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters);
  5. Set<String> responseTypes = authorizationRequest.getResponseTypes();
  6. if (!responseTypes.contains("token") && !responseTypes.contains("code")) {
  7. throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes);
  8. }
  9. // 判断clientId是否为空
  10. if (authorizationRequest.getClientId() == null) {
  11. throw new InvalidClientException("A client id must be provided");
  12. }
  13. try {
  14. // 判断user是否认证,认证失败则跳转到/login路径
  15. if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) {
  16. throw new InsufficientAuthenticationException(
  17. "User must be authenticated with Spring Security before authorization can be completed.");
  18. }
  19. // 验证client信息
  20. ClientDetails client = getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId());
  21. ...
  22. }
  23. }

2.2 ExceptionTranslationFilter

  1. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
  2. throws IOException, ServletException {
  3. HttpServletRequest request = (HttpServletRequest) req;
  4. HttpServletResponse response = (HttpServletResponse) res;
  5. try {
  6. chain.doFilter(request, response);
  7. logger.debug("Chain processed normally");
  8. }
  9. catch (IOException ex) {
  10. throw ex;
  11. }
  12. catch (Exception ex) {
  13. // Try to extract a SpringSecurityException from the stacktrace
  14. Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
  15. RuntimeException ase = (AuthenticationException) throwableAnalyzer
  16. .getFirstThrowableOfType(AuthenticationException.class, causeChain);
  17. if (ase == null) {
  18. ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(
  19. AccessDeniedException.class, causeChain);
  20. }
  21. if (ase != null) {
  22. // 进入到此方法中
  23. handleSpringSecurityException(request, response, chain, ase);
  24. }
  25. ...
  26. }
  27. }
  28. private void handleSpringSecurityException(HttpServletRequest request,
  29. HttpServletResponse response, FilterChain chain, RuntimeException exception)
  30. throws IOException, ServletException {
  31. if (exception instanceof AuthenticationException) {
  32. logger.debug(
  33. "Authentication exception occurred; redirecting to authentication entry point",
  34. exception);
  35. // 没有验证身份信息,跳转到/login界面
  36. sendStartAuthentication(request, response, chain,
  37. (AuthenticationException) exception);
  38. }
  39. ...
  40. }
  41. protected void sendStartAuthentication(HttpServletRequest request,
  42. HttpServletResponse response, FilterChain chain,
  43. AuthenticationException reason) throws ServletException, IOException {
  44. SecurityContextHolder.getContext().setAuthentication(null);
  45. // 将saveRequest存到session中,方便身份验证成功后调用
  46. requestCache.saveRequest(request, response);
  47. logger.debug("Calling Authentication entry point.");
  48. // 请求重定向到/login
  49. authenticationEntryPoint.commence(request, response, reason);
  50. }

2.3 requestCache.saveRequest(request,response)

requestCache的常用的实现类是HttpSessionRequestCache,一般是访问url时系统判断用户未获得授权,ExceptionTranslationFilter会存储savedRequest到session中,名为“SPRING_SECURITY_SAVED_REQUEST”。
SavedRequest里面包含原先访问的url地址、cookie、header、parameter等信息,一旦Authentication认证成功,successHandler.onAuthenticationSuccess(SavedRequestAwareAuthenticationSuccessHandler)会从session中抽取savedRequest,继续访问原先的url。

  1. public class HttpSessionRequestCache implements RequestCache {
  2. static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";
  3. /**
  4. * HttpSessionRequestCache Stores the current request, provided the configuration properties allow it.
  5. */
  6. public void saveRequest(HttpServletRequest request, HttpServletResponse response) {
  7. if (requestMatcher.matches(request)) {
  8. DefaultSavedRequest savedRequest = new DefaultSavedRequest(request,
  9. portResolver);
  10. if (createSessionAllowed || request.getSession(false) != null) {
  11. // Store the HTTP request itself. Used by
  12. // AbstractAuthenticationProcessingFilter
  13. // for redirection after successful authentication (SEC-29)
  14. request.getSession().setAttribute(this.sessionAttrName, savedRequest);
  15. logger.debug("DefaultSavedRequest added to Session: " + savedRequest);
  16. }
  17. }
  18. else {
  19. logger.debug("Request not saved as configured RequestMatcher did not match");
  20. }
  21. }
  22. }

2.4 重定向到/login

由于是第一次访问qq认证服务器,所以需要用户登录校验身份。在WebSecurityConfigurerAdapter的继承类中,找到存储在缓存中的用户名密码,填写完毕。
image.png

点击“Sign In”按钮后,post请求/login路径,按照FilterChainProxy的filter链运行到UsernamePasswordAuthenticationFilter,验证通过后执行successHandler.onAuthenticationSuccess(request, response, authResult),获取session中的savedrequest,重定向到原先的地址/oauth/authorize,并附带完整请求参数。

  1. public class SavedRequestAwareAuthenticationSuccessHandler extends
  2. SimpleUrlAuthenticationSuccessHandler {
  3. protected final Log logger = LogFactory.getLog(this.getClass());
  4. private RequestCache requestCache = new HttpSessionRequestCache();
  5. @Override
  6. public void onAuthenticationSuccess(HttpServletRequest request,
  7. HttpServletResponse response, Authentication authentication)
  8. throws ServletException, IOException {
  9. // HttpSessionRequestCache.getRequest ,找名为SPRING_SECURITY_SAVED_REQUEST的session
  10. SavedRequest savedRequest = requestCache.getRequest(request, response);
  11. if (savedRequest == null) {
  12. super.onAuthenticationSuccess(request, response, authentication);
  13. return;
  14. }
  15. String targetUrlParameter = getTargetUrlParameter();
  16. if (isAlwaysUseDefaultTargetUrl()
  17. || (targetUrlParameter != null && StringUtils.hasText(request
  18. .getParameter(targetUrlParameter)))) {
  19. requestCache.removeRequest(request, response);
  20. super.onAuthenticationSuccess(request, response, authentication);
  21. return;
  22. }
  23. clearAuthenticationAttributes(request);
  24. // Use the DefaultSavedRequest URL
  25. // 获得原先存储在SavedRequest中的redirectUrl,即/oauth/authorize
  26. String targetUrl = savedRequest.getRedirectUrl();
  27. logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
  28. getRedirectStrategy().sendRedirect(request, response, targetUrl);
  29. }
  30. public void setRequestCache(RequestCache requestCache) {
  31. this.requestCache = requestCache;
  32. }
  33. }

2.5 第二次请求/oauth/authorize

这次请求就硬气多了,请求中携带了Authentication的session,系统验证通过,生成授权码,存储在InMemoryAuthorizationCodeServices中的concurrenthashmap中,且返回给请求参数中的redirect_uri,即http://localhost:8081/aiqiyi/qq/redirect。

  1. http://localhost:8080/oauth/authorize?client_id=aiqiyi&response_type=code&redirect_uri=http://localhost:8081/aiqiyi/qq/redirect
  1. @RequestMapping(value = "/oauth/authorize")
  2. public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters,
  3. SessionStatus sessionStatus, Principal principal) {
  4. ...
  5. if (authorizationRequest.isApproved()) {
  6. if (responseTypes.contains("token")) {
  7. return getImplicitGrantResponse(authorizationRequest);
  8. }
  9. if (responseTypes.contains("code")) {
  10. // 返回code给redirect_uri
  11. return new ModelAndView(getAuthorizationCodeResponse(authorizationRequest,
  12. (Authentication) principal));
  13. }
  14. }
  15. ...
  16. }
  1. public class InMemoryAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {
  2. protected final ConcurrentHashMap<String, OAuth2Authentication> authorizationCodeStore = new ConcurrentHashMap<String, OAuth2Authentication>();
  3. @Override
  4. protected void store(String code, OAuth2Authentication authentication) {
  5. this.authorizationCodeStore.put(code, authentication);
  6. }
  7. @Override
  8. public OAuth2Authentication remove(String code) {
  9. OAuth2Authentication auth = this.authorizationCodeStore.remove(code);
  10. return auth;
  11. }
  12. }

到了这里我们总结下刚才都发生了什么。首先aiqiyi向qq发出/oauth/authorize的请求,qq服务器的AuthorizationEndPoint判断用户是否登录,如果没有登录则先跳转到/login界面,同时存储首次request的信息,保存在session中。用户登录并授权后,程序自动获取刚存储在session中的savedrequest,再次访问/oauth/authorize。验证client信息和user信息成功后,重定向到redirect_uri,并传参数code。
aiqiyi接到code后,再附带client_id,client_secret,grant_type,redirect_uri等信息post请求/oauth/token,从而获得access_token。

2.6 client接收code并向oauth server请求/oauth/token

以下代码自行写在client的controller里,用于接收qq服务端传递来的code,并请求/oauth/token。

  1. @RequestMapping("/aiqiyi/qq/redirect")
  2. public String getToken(@RequestParam String code){
  3. log.info("receive code {}",code);
  4. HttpHeaders headers = new HttpHeaders();
  5. headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  6. MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
  7. params.add("grant_type","authorization_code");
  8. params.add("code",code);
  9. params.add("client_id","aiqiyi");
  10. params.add("client_secret","secret");
  11. params.add("redirect_uri","http://localhost:8081/aiqiyi/qq/redirect");
  12. HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
  13. ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:8080/oauth/token", requestEntity, String.class);
  14. String token = response.getBody();
  15. log.info("token => {}",token);
  16. return token;
  17. }

2.7 TokenEndPoint生成access_token

具体代码在上一章已介绍,这里不做详述。注意的是会从InMemoryAuthorizationCodeServices中提取hashmap验证code是否正确。

3 总结

image.png

github地址:https://github.com/lexburner/oauth2-demo

OAuth2 源码分析(三.密码模式源码)

原文链接:https://blog.csdn.net/qq_30905661/article/details/82704746
上章介绍了授权码模式,现在再来介绍密码模式,简单的如同砍瓜切菜。
所谓密码模式,即用户提供username,password,clientId,clientSecret,grantType=password等信息,请求/oauth/token,获得access_token,用户即可通过access_token访问资源。
还是以oauth2-demo-master项目为例,只用添加client的认证方法password。
image.png

启动QQ项目,程序自动会启动几个endpoints,如/oauth/token,/oauth/authorize等。

1. 访问/oauth/token

此时FilterChainProxy的filter顺序如下。重要的Filter有ClientCredentialsTokenEndpointFilter和BasicAuthenticationFilter,前者从request parameters中抽取client信息,后者从header Authorization Basic XXXX中抽取client信息。
image.png

1.1 parameters

用postman发送请求,所有参数写在parameters中,返回access_token。
localhost:8080/oauth/token?username=250577914&password=123456&grant_type=password&client_id=aiqiyi&client_secret=secret
image.png

ClientCredentialsTokenEndpointFilter会从parameter中抽取client_id,client_secret信息,并进行client的身份验证。

  1. @Override
  2. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
  3. throws AuthenticationException, IOException, ServletException {
  4. if (allowOnlyPost && !"POST".equalsIgnoreCase(request.getMethod())) {
  5. throw new HttpRequestMethodNotSupportedException(request.getMethod(), new String[] { "POST" });
  6. }
  7. String clientId = request.getParameter("client_id");
  8. String clientSecret = request.getParameter("client_secret");
  9. // If the request is already authenticated we can assume that this
  10. // filter is not needed
  11. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  12. if (authentication != null && authentication.isAuthenticated()) {
  13. return authentication;
  14. }
  15. if (clientId == null) {
  16. throw new BadCredentialsException("No client credentials presented");
  17. }
  18. if (clientSecret == null) {
  19. clientSecret = "";
  20. }
  21. clientId = clientId.trim();
  22. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId,
  23. clientSecret);
  24. return this.getAuthenticationManager().authenticate(authRequest);
  25. }

1.2 Basic Auth

Postman发送请求如下,Basic Auth中填写client_id和client_secret信息。点击updaterequests后,postman会将client信息用base64加密,写在header——Authorization中。
image.png

image.png

这样一来,ClientCredentialsTokenEndpointFilter会由于参数中没有client_id自动跳过。BasicAuthenticationFilter会获取header中的Authorization Basic,提取出客户端信息。

  1. @Override
  2. protected void doFilterInternal(HttpServletRequest request,
  3. HttpServletResponse response, FilterChain chain)
  4. throws IOException, ServletException {
  5. final boolean debug = this.logger.isDebugEnabled();
  6. String header = request.getHeader("Authorization");
  7. if (header == null || !header.startsWith("Basic ")) {
  8. chain.doFilter(request, response);
  9. return;
  10. }
  11. try {
  12. // Base64 反解码
  13. String[] tokens = extractAndDecodeHeader(header, request);
  14. assert tokens.length == 2;
  15. String username = tokens[0];
  16. if (authenticationIsRequired(username)) {
  17. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
  18. username, tokens[1]);
  19. authRequest.setDetails(
  20. this.authenticationDetailsSource.buildDetails(request));
  21. Authentication authResult = this.authenticationManager
  22. .authenticate(authRequest);
  23. SecurityContextHolder.getContext().setAuthentication(authResult);
  24. this.rememberMeServices.loginSuccess(request, response, authResult);
  25. onSuccessfulAuthentication(request, response, authResult);
  26. }
  27. }
  28. catch (AuthenticationException failed) {
  29. ...
  30. }
  31. chain.doFilter(request, response);
  32. }

无论是哪一种方式访问/oauth/token,都事先验证了client信息,并作为authentication存储在SecurityContextHolder中。传递到TokenEndPoint的principal是client,paramters包含了user的信息和grantType。
image.png

2. 携带Access_token访问api

2.1 access_token放在parameter中

OAuth2AuthentiactionProcessingFilter,从request中提取access_token,构建PreAuthenticatedAuthenticationToken并验证。

  1. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
  2. ServletException {
  3. final boolean debug = logger.isDebugEnabled();
  4. final HttpServletRequest request = (HttpServletRequest) req;
  5. final HttpServletResponse response = (HttpServletResponse) res;
  6. try {
  7. // 从request中提取access_token
  8. Authentication authentication = tokenExtractor.extract(request);
  9. if (authentication == null) {
  10. if (stateless && isAuthenticated()) {
  11. SecurityContextHolder.clearContext();
  12. }
  13. }
  14. else {
  15. request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, authentication.getPrincipal());
  16. if (authentication instanceof AbstractAuthenticationToken) {
  17. AbstractAuthenticationToken needsDetails = (AbstractAuthenticationToken) authentication;
  18. needsDetails.setDetails(authenticationDetailsSource.buildDetails(request));
  19. }
  20. // OAuth2AuthenticationManager 验证PreAuthenticatedAuthenticationToken
  21. Authentication authResult = authenticationManager.authenticate(authentication);
  22. eventPublisher.publishAuthenticationSuccess(authResult);
  23. SecurityContextHolder.getContext().setAuthentication(authResult);
  24. }
  25. }
  26. catch (OAuth2Exception failed) {
  27. SecurityContextHolder.clearContext();
  28. eventPublisher.publishAuthenticationFailure(new BadCredentialsException(failed.getMessage(), failed),
  29. new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
  30. authenticationEntryPoint.commence(request, response,
  31. new InsufficientAuthenticationException(failed.getMessage(), failed));
  32. return;
  33. }
  34. chain.doFilter(request, response);
  35. }

tokenExtractor.extract(request)实际调用的是BearTokenExtractor里的extract方法,从Authorization header “Bearer xxxx”中抽取token,或者从request parameters抽取名为“access_token”的参数值。

  1. @Override
  2. public Authentication extract(HttpServletRequest request) {
  3. String tokenValue = extractToken(request);
  4. if (tokenValue != null) {
  5. // 记为PreAuthenticatedAuthenticationToken
  6. PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(tokenValue, "");
  7. return authentication;
  8. }
  9. return null;
  10. }

构建后的authentication参数如下,tokenType=”Bearer”,principal=token值。再根据OAuth2AuthenticationManager验证该authentication的合法性。
image.png

2.2 access_token存于header中

postman发送如下请求,将access_token写在Authorization的header里,前缀是Bearer。
image.png

同样是OAuth2AuthenticationProcessingFilter拦截,从request header中提取token,记为PreAuthenticatedAuthenticationToken,用OAuth2AuthenticationManager进行验证。

3. 访问/oauth/check_token

当oauthserver和resourceserver不在一个应用程序时,访问resource,会自动转交到oauthserver的/oauth/check_token,获得access_token的验证结果。

3.1 配置ResouceServer

配置application.yml

  1. server:
  2. port: 8081
  3. security:
  4. oauth2:
  5. client:
  6. client-id: aiqiyi
  7. client-secret: secret
  8. access-token-uri: http://localhost:8080/oauth/token
  9. user-authorization-uri: http://localhost:8080/oauth/authorize
  10. user-logout-uri: http://localhost:8080/oauth/logout
  11. resource:
  12. id: qq
  13. token-info-uri: http://localhost:8080/oauth/check_token
  14. prefer-token-info: true
  15. filter-order: 3
  16. basic:
  17. enabled: false

配置ResouceServerConfigurerAdapter

  1. @Configuration
  2. @EnableResourceServer
  3. @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
  4. public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
  5. @Value("${security.oauth2.resource.id}")
  6. public String RESOURCE_ID;
  7. @Autowired
  8. public RemoteTokenServices remoteTokenServices;
  9. @Override
  10. public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
  11. // 存入resource_id,到时候与oauthserver中client对应的resourceid进行比对
  12. resources.resourceId(RESOURCE_ID).stateless(true);
  13. resources.tokenServices(remoteTokenServices);
  14. }
  15. }

源码:https://github.com/lexburner/oauth2-demo