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

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

    Here it is, your use case may differ slightly based on the flow you are using. This is what works for a password grant flow. There are a few custom class like token store, token enhancer ect. but that is really just extended versions of the spring classes modified for our own needs.

            HashMap authorizationParameters = new HashMap();
            authorizationParameters.put("scope", "read");
            authorizationParameters.put("username", "mobile_client");
            authorizationParameters.put("client_id", "mobile-client");
            authorizationParameters.put("grant", "password");
    
            DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest(authorizationParameters);
            authorizationRequest.setApproved(true);
    
            Set authorities = new HashSet();
            authorities.add(new SimpleGrantedAuthority("ROLE_UNTRUSTED_CLIENT"));
            authorizationRequest.setAuthorities(authorities);
    
            HashSet resourceIds = new HashSet();
            resourceIds.add("mobile-public");
            authorizationRequest.setResourceIds(resourceIds);
    
            // Create principal and auth token
            User userPrincipal = new User(user.getUserID(), "", true, true, true, true, authorities);
    
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userPrincipal, null, authorities) ;
    
            OAuth2Authentication authenticationRequest = new OAuth2Authentication(authorizationRequest, authenticationToken);
            authenticationRequest.setAuthenticated(true);
    
            CustomTokenStore tokenStore = new CustomTokenStore();
    
            // Token Enhancer
            CustomTokenEnhancer tokenEnhancer = new CustomTokenEnhancer(user.getUserID());
    
            CustomTokenServices tokenServices = new CustomTokenServices();
            tokenServices.setTokenEnhancer(tokenEnhancer);
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setTokenStore(tokenStore);
    
            OAuth2AccessToken accessToken = tokenServices.createAccessTokenForUser(authenticationRequest, user);
    

提交回复
热议问题