【问题标题】:Update user authorities in database Spring boot OAuth 2.0更新数据库中的用户权限 Spring boot OAuth 2.0
【发布时间】:2020-06-09 18:56:37
【问题描述】:

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

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 表的数据库表中的权限。实际上,我正在开发一个用户权限经常变化的社交应用程序。

Spring 是否提供开箱即用的此功能?

或者你有什么自定义逻辑?

【问题讨论】:

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


    【解决方案1】:

    您可以使用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);
        }
    

    【讨论】:

      猜你喜欢
      • 2014-11-30
      • 2021-05-21
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 2018-11-10
      • 2018-09-12
      • 1970-01-01
      • 2010-10-27
      相关资源
      最近更新 更多