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

后端 未结 7 944
天涯浪人
天涯浪人 2020-12-07 17:00

I have a situation where I would like to create an access token myself (so not through the usual process). I have come up with something like this:

@Inject
p         


        
7条回答
  •  日久生厌
    2020-12-07 17:31

    I based my solution on Mop So's answer but instead of using:

    return tokenEndpoint.getAccessToken(principal, parameters);
    

    I used:

    tokenEndpoint.postAccessToken(principal, parameters);
    

    Why? Because if you use tokenEndpoint.getAccessToken(principal, parameters) the endpoing will throw you a HttpRequestMethodNotSupportedException because it has not been called with a GET method. At least, this is what happened to me with spring-security-oauth2-2.0.13.RELEASE

    public OAuth2AccessToken getAccessToken() throws HttpRequestMethodNotSupportedException {
        HashMap parameters = new HashMap<>();
        parameters.put("client_id", CLIENT_ID);
        parameters.put("client_secret", CLIENT_SECRET);
        parameters.put("grant_type", "client_credentials");
    
        ClientDetails clientDetails = clientDetailsStore.get(CLIENT_ID);
    
        // Create principal and auth token
        User userPrincipal = new User(CLIENT_ID, CLIENT_SECRET, true, true, true, true, clientDetails.getAuthorities());
    
        UsernamePasswordAuthenticationToken principal = new UsernamePasswordAuthenticationToken(userPrincipal, CLIENT_SECRET,
                clientDetails.getAuthorities());
    
        ResponseEntity accessToken = tokenEndpoint.postAccessToken(principal, parameters);
    
        return accessToken.getBody();
    }
    

提交回复
热议问题