一. 流程
- 用户发起获取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==

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

-
调用方法
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

-
调用方法
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信息










