2015-01-07 41 views
0

我们的应用程序的身份验证是通过siteminder代理发生的,但授权是通过我们的应用程序控制的。Spring安全 - 预认证 - 数据库中定义的授权和集合角色

我正在使用org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter检查标题。我还定义了UserDetailsS​​ervice来加载用户的详细信息。

我还需要为用户设置角色,以便我可以使用弹簧安全标记库和其他弹簧方法来检查角色并显示选项。

我该如何实施?

我已经在我的用户详细信息服务实现中尝试了下面的语句,但似乎没有工作。

Authentication auth = new UsernamePasswordAuthenticationToken(user, null, roles); 
    SecurityContextHolder.getContext().setAuthentication(auth); 

我也读过关于AbstractPreAuthenticatedProcessingFilter类,但看起来像这可能没有用于此目的。

在这个问题上的任何帮助将是非常有益的。

谢谢!

+0

您的_RequestHeaderAuthenticationFilter_扩展了您正在讨论的_AbstractPreAuthenticatedProcessingFilter_。你很好。但是您还需要设置_PreAuthenticatedAuthenticationProvider_。你需要提供你的安全配置文件给别人来帮助你更好。 – Angad

+0

谢谢你对Angad的回应。我使用Spring Security提供的PreAuthenticatedAuthenticationProvider,但没有扩展它来设置角色。 – Sanjeev

回答

1

我试图在UserDetailsS​​ervice 实现中设置角色(使用我的问题中的语句)并且它不起作用。

解决方案1: 我写了一个子类PreAuthenticatedAuthenticationProvider并重写为下面的身份验证方法:

public class CustomPreAuthenticatedAuthenticationProvider extends PreAuthenticatedAuthenticationProvider { 


    @Autowired 
    DBConfig dbConfig; 

    @Override 
    public Authentication authenticate(Authentication authentication)throws AuthenticationException { 
     Authentication auth = super.authenticate(authentication); 

     User user = (User)auth.getPrincipal(); 

     Set<Role> roles = new HashSet<Role>(); 

     String[] rolesArray = dbConfig.getRoles(user.getAccessLevel()); 
     for(String role: rolesArray){ 
      Role r = new Role(); 
      r.setName(role); 
      roles.add(r); 
     } 

     user.setRoles(roles); 

     auth = new UsernamePasswordAuthenticationToken(user, null, roles); 

     return auth; 
    } 


} 

解决方案2: 我试图在控制器设置的角色(认证后的主页),它的工作。但看起来像解决方案-1是一个标准的解决方案。

+1

解决方案-1显然更可取。但我更喜欢在UserDetailsS​​ervice中保留角色获取逻辑。为此,你需要的是用普通类型_PreAuthenticatedAuthenticationToken_实现Spring提供的类_AuthenticationUserDetailsS​​ervice_并且重写_loadUserDetails()_方法来编写你的角色逻辑 – Angad