【问题标题】:Spring Security - Preauthentication - Authorization and Set Roles Defined in DBSpring Security - Preauthentication - 数据库中定义的授权和设置角色
【发布时间】:2015-03-06 00:16:08
【问题描述】:

我们的应用程序的身份验证是通过 siteminder 代理进行的,但授权是通过我们的应用程序控制的。

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

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

我该如何实现?

我在我的用户详细信息服务实现中尝试了以下语句,但似乎不起作用。

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

我还阅读了有关 AbstractPreAuthenticatedProcessingFilter 类的信息,但看起来这可能对此没有用处。

在这个问题上的任何帮助都会非常有帮助。

谢谢!

【问题讨论】:

  • 您的 RequestHeaderAuthenticationFilter 扩展了您正在谈论的 AbstractPreAuthenticatedProcessingFilter。你在那里很好。但是您还需要设置 PreAuthenticatedAuthenticationProvider。您需要提供您的安全配置文件以供他人更好地帮助您。
  • 感谢安加德的回复。我使用的是 Spring Security 提供的 PreAuthenticatedAuthenticationProvider,但没有扩展它来设置角色。

标签: spring-security roles pre-authentication


【解决方案1】:

我试图在 UserDetailsS​​ervice 中设置角色(使用我的问题中的语句) 实施,但没有奏效。

解决方案-1: 我写了一个子类 PreAuthenticatedAuthenticationProvider 并重写了如下的 authenticate 方法:

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: 我尝试在控制器中设置角色(身份验证后的主页)并且它有效。但是看起来 Solution-1 是一个标准的解决方案。

【讨论】:

  • Solution-1 显然更可取。不过,我更喜欢将角色获取逻辑保留在 UserDetailsS​​ervice 中。为此,您需要使用通用类型 PreAuthenticatedAuthenticationToken 实现 Spring 提供的类 AuthenticationUserDetailsS​​ervice 并覆盖 loadUserDetails() 方法来编写您的角色逻辑
猜你喜欢
  • 1970-01-01
  • 2016-07-01
  • 2020-06-16
  • 2018-03-21
  • 1970-01-01
  • 2021-02-15
  • 2011-12-24
  • 2020-08-25
相关资源
最近更新 更多