Spring oauth2的token构建

Spring oauth2的Oauth2AccessToken构建

​ spring security在拿到用户的认证通过后会生成Authentication对象,例如通过简单的表单认证会生成UsernamePasswordAuthenticationToken具体类型,social生成的是SocialAuthenticationToken对象,但是如何生成OAuth2的token呢,在访问spring Oauth2提供的oauth/token接口可以走完整个流程,拿到token 是没问题的,在我们不想通过这个接口,特别是在social通过第三方授权时,是无法通过这个接口拿到token的。怎么办呢?这时我们我们可以自己走完后面的流程构建Oauth2AccessToken。

Oauth2AccessTokenOauth2AccessToken的构建过程如下:

Spring oauth2的token构建_第1张图片

步骤:

  1. 构建ClientDetails对象,通过ClientDetailsService拿到ClientDetails信息。
  2. 通过ClientDetails构建TokenRequest对象
  3. 调用TokenRequest对象的createOAuth2Request(clientDetails)方法构建OAuth2Request
  4. SecurityContext上下文获得Authentication,Authentication的类型要看具体的认证途径
  5. 通过OAuth2RequestAuthentication生成OAuth2Authentication
  6. 把OAuth2Authentication交给AuthorizationServerTokenServices处理,调用createAccessToken方法获取OAuth2AccessToken

示例代码如下:

@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private AuthorizationServerTokenServices defaultAuthorizationServerTokenServices;

public OAuth2AccessToken createMyToken() {
	String clientId="test_client"; 
	ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);          	SecurityContext context = SecurityContextHolder.getContext();        		   
    SecurityContextHolder.clearContext();
    TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_MAP, clientId,    clientDetails.getScope(), "custom");  
	OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);         	   Authentication authentication = context.getAuthentication();  
    OAuth2Authentication oAuth2Authentication = new  OAuth2Authentication(oAuth2Request,authentication);
    OAuth2AccessToken accessToken = 	defaultAuthorizationServerTokenServices.createAccessToken(oAuth2Authentication);        	return  accessToken; 
}

你可能感兴趣的:(笔记)