Shendor
Shendor

Reputation: 787

Spring generate oauth2 access token programmatically

I have a Web Sesrvices protected by spring security OAuth2 and I can get access token using http request oauth/token... I have another requirement: to generate the access token in java and authenticate the user using:

SecurityContextHolder.getContext().setAuthentication(oauthToken);

in order to have access to web services via this token. This is my curent code:

UserDetails user = (UserDetails)userService.getUserByUserName(userName);

    if (user == null) {
        throw new InvalidAuthorizationException("User " + userName + " was not found");
    } else {
         //TODO: how to create 'oauthToken' ?
         SecurityContextHolder.getContext().setAuthentication(oauthToken);

    }

How can I do this?

Upvotes: 6

Views: 4489

Answers (1)

Luke Bajada
Luke Bajada

Reputation: 1842

The easiest solution in your case would be to go to TokenEndpoint.java and mimic the calls done in postAccessToken method.

Remember that the creation of the access token is in the hands of the Authorization Server so if you're doing this logic on the client side it is not advisable and does not adhere to the RFC6749 - The OAuth 2.0 Authorization Framework.

Keep in mind also that in the Security Context you need to set an Authentication object and not a Token. The token is found in the authentication.

Upvotes: 2

Related Questions