user1406564
user1406564

Reputation: 91

Spring OAuth2 - Create an access token

I'm using the method here described to create an OAuth2 access token:

Spring OAuth2 - Manually creating an access token in the token store

This method works with spring-security-oauth2 1.0.5.RELEASE but it doesn't work with spring-security-oauth2 2.0.6.RELEASE.

Is there a way to make the same thing with spring-security-oauth2 2.0.6.RELEASE?

Upvotes: 6

Views: 9661

Answers (1)

Ruslan Danilin
Ruslan Danilin

Reputation: 190

Here is example Rest Controller method that works with spring-security-oauth2 2.0.6.RELEASE

@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;
}

Hope it helps.

Upvotes: 9

Related Questions