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

标签 java spring-boot spring-security oauth-2.0 spring-security-oauth2

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

相关文章:

java - 自移动到 Spring Boot 1.1.4.RELEASE 以来,@Value 和 application.properties 出现问题

java - Spring Boot Oauth2 授权服务器不接受有效 token

java - 我应该用种子为我的 BCryptPasswordEncoder 初始化 SecureRandom 吗?

java - 没有长时间运行的对话 - IllegalArgumentException : Stack must not be null

java - 实现简单的Hadoop调度程序,如何从外部程序提交Hadoop作业?

spring-boot - 无法从 Spring Boot jar 中读取文本文件

java - 多个子域的 Web 应用程序身份验证

java - 将SmartID Reader JNI库添加到现有的gradle项目中

java - 为 Android 设置 Libgdx Bullet 包装器时出现问题

java - Spring Boot Controller 路径扩展了另一条路径