一. 流程
- 用户发起获取token的请求。
- 过滤器会验证path是否是认证的请求/oauth/token,如果为false,则直接返回没有后续操作。
- 过滤器通过clientId查询生成一个Authentication对象。
- 然后会通过username(clientId)和生成的Authentication对象生成一个UserDetails对象,并检查用户是否存在。
- 以上全部通过会进入地址/oauth/token,即TokenEndpoint的postAccessToken方法中。
- postAccessToken方法中会验证Scope,然后验证是否是refreshToken请求等。
- 之后调用AbstractTokenGranter中的grant方法。
- 然后通过DefaultTokenServices类从tokenStore中获取OAuth2AccessToken对象。
然后将OAuth2AccessToken对象包装进响应流返回。
二. 源码执行流程
2.1 发起获取token请求/oauth/token
,必须带上客户端凭证Authorization
客户端凭证值的格式为
Basic空格 + client_id:client_secret
经过Base64加密后的值, 例如:
Authorization: Basic YWstaGx3eXk6YWtobQQQQ==
![](https://img.haomeiwen.com/i17163728/abea6c7116137d82.png)
2.2 请求经过拦截器BasicAuthenticationFilter
进行拦截授权处理
-
请求先经过拦截器
org.springframework.security.web.authentication.www.BasicAuthenticationFilter#doFilterInternal
, 调用方法org.springframework.security.web.authentication.www.BasicAuthenticationConverter#convert
解析客户凭证,获取到client_id
和client_secret
,然后返回UsernamePasswordAuthenticationToken
image.png
image.png
-
跟据
UsernamePasswordAuthenticationToken
找到对应的AuthenticationProvider
进行下一步处理
image.png
-
调用方法
org.springframework.security.authentication.ProviderManager#authenticate
遍历所有的AuthenticationProvider
找到对应的Provider
处理,UsernamePasswordAuthenticationToken
对应的Provider
是org.springframework.security.authentication.dao.DaoAuthenticationProvider
![](https://img.haomeiwen.com/i17163728/3f53607b24c6652d.png)
-
调用方法
org.springframework.security.authentication.dao.DaoAuthenticationProvider#retrieveUser
根据client_id
和UsernamePasswordAuthenticationToken
获取UserDetails
image.png
image.png
-
UserDetails
是调用方法org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService#loadUserByUsername
获取的
image.png
-
调用方法
org.springframework.security.authentication.dao.DaoAuthenticationProvider#additionalAuthenticationChecks
根据UserDetails
和Authentication
校验客户凭证的client_secret
是否正确
image.png
以上步骤全部成功,就会执行到下步骤
2.3 正式执行/oauth/token
的业务方法
org.springframework.security.oauth2.provider.endpoint.TokenEndpoint#postAccessToken
![](https://img.haomeiwen.com/i17163728/90e40e0e9b81c9e0.png)
-
调用方法
org.springframework.security.oauth2.provider.OAuth2RequestValidator#validateScope(TokenRequest, ClientDetails)
验证scope
image.png
-
调用
org.springframework.security.oauth2.provider.CompositeTokenGranter#grant
根据grantType
遍历所有的TokenGranter
, 找到对应的TokenGranter
进行处理
image.png
-
调用
org.springframework.security.oauth2.provider.token.DefaultTokenServices#createAccessToken(org.springframework.security.oauth2.provider.OAuth2Authentication)
生成token信息
![](https://img.haomeiwen.com/i17163728/9afe93b8c586abb3.png)
![](https://img.haomeiwen.com/i17163728/9ce3860f74d6e1ac.png)
网友评论