我用Spring Security OAuth2成功地通过了Github认证。但是,通过Github获得的用户角色是USER_ROLE。
所以我想知道我是否可以通过判断授权成功后获得的Github用户信息来修改相应的角色,以便控制用户的权限。
例如,getPrincipal ()获取唯一的“名称”。然后将角色修改为name(如ADMIN)。最后,使用@PreAuthorize ("hasRole ('ROLE_ADMIN')")控制权限。
或者还有其他更好的解决方案吗?我想在这个应用程序中集成Github的OAuth2授权和基于角色的权限管理。
发布于 2018-01-01 17:23:50
最简单的方法是获取当前的身份验证,并创建它的一个新实例,然后按照直接设置SecurityContextHolder内容中所述在SecurityContextHolder上设置它。请确保您了解在多线程中执行身份验证的含义(请参阅reference to understand)。在当前鉴权中添加GrantedAuthority的示例如下:
// update the current Authentication
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(auth.getAuthorities());
authorities.add(new GrantedAuthorityImpl('ROLE_NEWROLE'));
Authentication newAuth = new UsernamePasswordToken(auth.getPrincipal(),auth.getCredentials(),authorities)
SecurityContextHolder.getContext().setAuthentication(newAuth);发布于 2018-01-02 18:27:38
我最终通过重新构建OAuth2ClientAuthenticationProcessingFilter并覆盖successfulAuthentication方法解决了这个问题。
关键的一点是,在认证成功后,第一步是确定它是否是来自于主体的我的Github帐户。
然后通过SecurityContextHolder.getContext().getAuthentication() get获取当前成功的认证OAuth2Authentication。然后构建一个新的身份验证并在SecurityContextHolder中构建一个新的OAuth2Authentication。
public class CustomOAuth2ClientAuthenticationProcessingFilter extends OAuth2ClientAuthenticationProcessingFilter {
public CustomOAuth2ClientAuthenticationProcessingFilter(String defaultFilterProcessesUrl) {
super(defaultFilterProcessesUrl);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
if (authResult.getPrincipal().equals("cciradih")) {
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
SecurityContextHolder.getContext().setAuthentication(new OAuth2Authentication(oAuth2Authentication.getOAuth2Request(), new Authentication() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return AuthorityUtils.createAuthorityList("ROLE_ADMIN", "ROLE_USER");
}
@Override
public Object getCredentials() {
return oAuth2Authentication.getCredentials();
}
@Override
public Object getDetails() {
return oAuth2Authentication.getUserAuthentication().getDetails();
}
@Override
public Object getPrincipal() {
return oAuth2Authentication.getPrincipal();
}
@Override
public boolean isAuthenticated() {
return oAuth2Authentication.getUserAuthentication().isAuthenticated();
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
}
@Override
public String getName() {
return oAuth2Authentication.getName();
}
}));
}
}
}https://stackoverflow.com/questions/48045845
复制相似问题