Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 298
user1406564 Avatar asked Feb 12 '15 09:02

user1406564


1 Answers

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.

like image 147
Ruslan Danilin Avatar answered Nov 18 '22 23:11

Ruslan Danilin