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

后端 未结 7 933
天涯浪人
天涯浪人 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:48

    Other way, to manually generate an OAuth2 Accesss Token we can use an instance of TokenService

    @Autowired
    private AuthorizationServerEndpointsConfiguration configuration;
    
    @Override
    public String generateOAuth2AccessToken(User user, List roles, List scopes) {
    
        Map requestParameters = new HashMap();
        Map extensionProperties = new HashMap();
    
        boolean approved = true;
        Set responseTypes = new HashSet();
        responseTypes.add("code");
    
        // Authorities
        List authorities = new ArrayList();
        for(Role role: roles)
            authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));
    
        OAuth2Request oauth2Request = new OAuth2Request(requestParameters, "clientIdTest", authorities, approved, new HashSet(scopes), new HashSet(Arrays.asList("resourceIdTest")), null, responseTypes, extensionProperties);
    
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), "N/A", authorities);
    
        OAuth2Authentication auth = new OAuth2Authentication(oauth2Request, authenticationToken);
    
        AuthorizationServerTokenServices tokenService = configuration.getEndpointsConfigurer().getTokenServices();
    
        OAuth2AccessToken token = tokenService.createAccessToken(auth);
    
        return token.getValue();
    }
    

提交回复
热议问题