gpt4 book ai didi

java - Spring OAuth2 - 在 token 存储中手动创建访问 token

转载 作者:IT老高 更新时间:2023-10-28 13:47:45 24 4
gpt4 key购买 nike

我有一种情况,我想自己创建一个访问 token (所以不是通过通常的过程)。我想出了这样的事情:

@Inject
private DefaultTokenServices defaultTokenServices;

...

OAuth2Authentication auth = xxx;
OAuth2AccessToken token = defaultTokenServices.createAccessToken(auth);

唯一的问题是我不确定如何创建 OAuth2Authentication(在我的代码中带有 xxx 的部分)。我有用户和客户信息,并且我知道我想授予该 token 的权限。

最佳答案

在这里,您的用例可能会根据您使用的流程而略有不同。这适用于密码授予流程。有一些自定义类,如 token 存储、 token 增强器等。但这实际上只是根据我们自己的需要修改的 spring 类的扩展版本。

        HashMap<String, String> authorizationParameters = new HashMap<String, String>();
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<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_UNTRUSTED_CLIENT"));
authorizationRequest.setAuthorities(authorities);

HashSet<String> resourceIds = new HashSet<String>();
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);

关于java - Spring OAuth2 - 在 token 存储中手动创建访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18536521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com