【问题标题】:Spring 4 - Authentication with preAuthorize & PostAuthorizeSpring 4 - 使用 preAuthorize 和 PostAuthorize 进行身份验证
【发布时间】:2014-08-16 14:25:32
【问题描述】:

注意:我的应用程序使用最新版本的 Spring 框架,4.0.6、3.2.4 以确保安全性,并且它不使用 xml 而只使用 Java-Config 来配置应用程序。

我有一组服务,我想通过角色和其他业务特定授权条件来保护这些服务。这些服务被分组到一个模块(一个 jar)中,供 REST 应用程序和 Web 应用程序使用。我已经在 Web 应用程序中有一个 AuthenticationProvider(REST 应用程序处于初始阶段)。我在 Web 应用程序中使用 @EnableGlobalMethodSecurity。话虽如此,我现在也需要保护服务中的方法。在这种情况下,我是否需要提供另一个身份验证提供程序?或者,将身份验证提供程序移动到服务模块以便 web/rest 应用程序使用服务 jar 中的身份验证提供程序是否正确?如果我在服务模块的 ApplicationServiceConfig.java 中配置@EnableGlobalMethodSecurity,我会得到打击异常。

com.name.mvoice.project.service.ApplicationServiceConfig: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: An AuthenticationManager is required

如果应用程序需要双重身份验证,一个来自 RDBMS,另一个来自 LDAP,我该如何配置安全性。条件应该是用户信息应该在两个系统中都存在并启用。我是否需要在现有的身份验证管理器本身中编写此内容,还是应该为 LDAP 提供单独的身份验证提供程序?如果有怎么办?

WebSecurityConfig.java

 @Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
        throws Exception {
    AuthenticationProvider dbAuthenticationProvider = new DatabaseAuthenticationProvider();
    auth.authenticationProvider(dbAuthenticationProvider );
    // is it right to do like this
   AuthenticationProvider ldapAuthenticationProvider = new LDAPAuthenticationProvider();
    auth.authenticationProvider(ldapAuthenticationProvider );
 }

不过,我看到AuthenticationManagerBuilder.authenticationProvider 将提供的身份验证提供程序添加到列表中!

【问题讨论】:

    标签: java spring spring-mvc authentication spring-4


    【解决方案1】:

    不,这不会给你想要的结果。默认的 Spring Security 实现一次只使用一个AuthenticationProvider。您对auth.authenticationProvider() 的第二次调用将强制 Spring Security 仅使用 LDAP 提供程序。

    实现你想要的

    第 1 步:例如,创建一个您自己的类

    public class CompositeAuthenticationProvider implements AuthenticationProvider {}
    

    第 2 步:然后,将数据库和 LDAP 提供程序注入其中。

    第 3 步:在 CompositeAuthenticationProvider 类的 authenticate 方法中,按照您认为合适的方式编排数据库和 LDAP 提供程序之间的请求。根据您从两个提供商处获得的结果返回响应。

    【讨论】:

    • 好的,知道了。但是为什么 AuthenticationManagerBuilder.authenticationProvider 将提供的提供程序添加到列表中?我在 spring 文档的某个地方读到,提供的身份验证提供者中的任何一个都应该返回一个正确的值,然后 spring 会接受它。我没有深入研究 spring 代码。
    • 我也没有深入研究文档,但我已经概述了经过大量试验和错误后我在自己的项目中使用的方法。
    • 好的。让我试试。对我的第一个问题有任何想法吗?
    猜你喜欢
    • 2011-10-17
    • 2018-01-18
    • 2014-07-03
    • 2022-01-12
    • 2017-11-25
    • 2017-08-14
    • 2012-11-27
    • 2013-12-08
    相关资源
    最近更新 更多