我们可以通过重置 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_token
和 oauth_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/