gpt4 book ai didi

java - 更新数据库中的用户权限 Spring boot OAuth 2.0

转载 作者:行者123 更新时间:2023-12-05 06:15:58 25 4
gpt4 key购买 nike

我们可以通过重置 Spring SecurityContextHolder 中的 Authentication 对象(安全 token )来动态更新登录用户的权限,而无需注销和登录通过使用此代码。

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

List<GrantedAuthority> updatedAuthorities = new ArrayList<>(auth.getAuthorities());
updatedAuthorities.add(...); //add your role here [e.g., new SimpleGrantedAuthority("ROLE_NEW_ROLE")]

Authentication newAuth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), updatedAuthorities);

SecurityContextHolder.getContext().setAuthentication(newAuth);

但此代码不会更新数据库中的权限,我想更新 OAuth oauth_access_tokenoauth_refresh_token 表的数据库表中的权限。实际上,我正在开发一个用户权限经常更改的社交应用程序。

Does Spring provide this feature out of the box?

Or do you have any custom Logic?

最佳答案

您可以使用TokenStore::storeAccessToken

这适用于我的应用程序,无需用户注销/登录即可更改权限

private final TokenStore tokenStore;

public void updateAuthorities() {
var auth = (OAuth2Authentication)SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> newAuthorities = <Your autorities list>;
var newAuth = new UsernamePasswordAuthenticationToken(
auth.getPrincipal(),
auth.getCredentials(),
newAuthorities
);
newAuth.setDetails(auth.getDetails());
var oauth2Auth = new OAuth2Authentication(auth.getOAuth2Request(), newAuth);
oauth2Auth.setDetails(auth.getDetails());
oauth2Auth.setAuthenticated(true);
OAuth2AccessToken existingAccessToken = this.tokenStore.getAccessToken(auth);
tokenStore.storeAccessToken(existingAccessToken, oauth2Auth);
SecurityContextHolder.getContext().setAuthentication(oauth2Auth);
}

关于java - 更新数据库中的用户权限 Spring boot OAuth 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62289939/

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