Spring Security:设置 GrantedAuthorities

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14712685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:42:09  来源:igfitidea点击:

Spring Security: Set GrantedAuthorities

springsecurityauthentication

提问by mpmp

Is there anyway to set the List<GrantedAuthority>in the Authentication/UserDetailsImpl object? In my application, I have two layers of security, one for logging in (which uses my custom login authenticator, in the class I set the Authenticationobject using the UsernamePasswordAuthenticationToken) and one for a "challenge question" where the user is prompted to answer a particular question.

无论如何要List<GrantedAuthority>在 Authentication/UserDetailsImpl 对象中设置?在我的应用程序中,我有两层安全性,一层用于登录(使用我的自定义登录身份验证器,在我使用 设置Authentication对象的类中UsernamePasswordAuthenticationToken),另一层用于提示用户回答特定问题的“挑战问题”题。

What I want to do is add a GrantedAuthorityto the current List<GrantedAuthority>, which was created during the login process, after the user answers the challenge question.

我想要做的是在用户回答质询问题后在登录过程中创建GrantedAuthority的 current 中添加一个List<GrantedAuthority>

Is this possible?

这可能吗?

回答by ziggear

you can do it with following code:

你可以用下面的代码做到这一点:

Collection<SimpleGrantedAuthority> oldAuthorities = (Collection<SimpleGrantedAuthority>)SecurityContextHolder.getContext().getAuthentication().getAuthorities();
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ANOTHER");
List<SimpleGrantedAuthority> updatedAuthorities = new ArrayList<SimpleGrantedAuthority>();
updatedAuthorities.add(authority);
updatedAuthorities.addAll(oldAuthorities);

SecurityContextHolder.getContext().setAuthentication(
        new UsernamePasswordAuthenticationToken(
                SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
                SecurityContextHolder.getContext().getAuthentication().getCredentials(),
                updatedAuthorities)
);

回答by Spanky Quigman

The UserDetails.getAuthorities()method just returns a Collection<GrantedAuthority>object. You can use the appropriate Collectionmethod to add your new authority to that collection.

UserDetails.getAuthorities()方法只返回一个Collection<GrantedAuthority>对象。您可以使用适当的Collection方法将您的新权限添加到该集合中。

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
    ((UserDetails) principal).getAuthorities().add(New GrantedAuthorityImpl("ROLE_FOO"));
}

Selah.

细拉。