Spring OAuth2 - 创建访问令牌

use*_*564 6 spring spring-security access-token oauth-2.0

我正在使用此处描述的方法来创建OAuth2访问令牌:

Spring OAuth2 - 在令牌存储中手动创建访问令牌

此方法适用于spring-security-oauth2 1.0.5.RELEASE,但它不适用于spring-security-oauth2 2.0.6.RELEASE.

有没有办法用spring-security-oauth2 2.0.6.RELEASE做同样的事情?

小智 9

下面是与spring-security-oauth2 2.0.6.RELEASE一起使用的示例Rest Controller方法

@RequestMapping("/token")
public OAuth2AccessToken token(Principal principal) {
    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

    Map<String, String> requestParameters = new HashMap<>();
    String clientId = "acme";
    boolean approved = true;
    Set<String> scope = new HashSet<>();
    scope.add("scope");
    Set<String> resourceIds = new HashSet<>();
    Set<String> responseTypes = new HashSet<>();
    responseTypes.add("code");
    Map<String, Serializable> extensionProperties = new HashMap<>();

    OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, clientId,
            authorities, approved, scope,
            resourceIds, null, responseTypes, extensionProperties);


    User userPrincipal = new User(principal.getName(), "", true, true, true, true, authorities);

    UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities);
    OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);
    OAuth2AccessToken token = defaultTokenServices.createAccessToken(auth);
    return token;
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.

  • DefaultTokenServices service = new DefaultTokenServices(); OAuth2AccessToken token = service.createAccessToken(auth); (4认同)