Spring Security OAuth2根据授权码获取Token源码
1、用户在认证中心登录完成后, 回调至redirect_url,并在 URL后携带授权码 格式为:URL?code=xxxx;
2、用户系统拿到授权码后发起获取token的请求
-
请求路径: /oauth/token
-
请求方法: POST
-
请求Content-Type: application/x-www-form-urlencoded
-
请求header: Authorization:Basic {base64Encoder(client_id+client_secret)}
-
请求参数: grant_type=authorization_code,code={code}, redirect_uri={redirect_uri}
3、请求到达OAuth Server处理
org.springframework.security.oauth2.provider.endpoint.TokenEndpoint类中的postAccessToken方法处理请求
@RequestMapping(value = "/oauth/token", method=RequestMethod.POST)
public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters)
参数介绍:
principal参数 :存储了 client 的相关信息
parameters 参数:存储了请求参数
方法体内容(只保留关键步骤):
// 获取clientId
String clientId = getClientId(principal);
// 根据clientId查询client信息
ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
// 根据请求参数 + client信息创建TokenRequest
TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient);
// 格局授权类型和请求参数生成token
OAuth2AccessToken token = getTokenGranter