当前位置: 首页 > 知识库问答 >
问题:

Java Spring 安全性配置 - 多个身份验证提供程序

慕佑运
2023-03-14

spring security 中有几个对多个身份验证提供程序的引用,但在 Java config 中找不到示例。

以下链接给出了XML符号:Spring Security中的多个身份验证提供者

我们需要使用LDAP或DB进行身份验证

下面是我们的示例代码:

@Configuration
@EnableWebSecurity
public class XSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Autowired
    private AuthenticationProvider authenticationProviderDB;


    @Override
    @Order(1)

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
    }


    @Order(2)
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProviderDB);
    }

    @Override
      public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
             .antMatchers("/scripts/**","/styles/**","/images/**","/error/**");
      }
    ______

    @Override
    @Order(1)
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
        .authorizeRequests()
            .antMatchers("/","/logout","/time").permitAll()
                    .antMatchers("/admin").hasRole("ADMIN")         
                        .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/index")
            .loginProcessingUrl("/perform_login")
            .usernameParameter("email")
            .passwordParameter("password")
            .failureUrl("/index?failed=true")
            .defaultSuccessUrl("/summary",true)
            .permitAll()
            .and()
         .logout().logoutUrl("/logout")
                  .logoutSuccessUrl("/index?logout=true").permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/error403")
        .and().authenticationProvider(authenticationProvider);

    }

    @Order(1)
    protected void configureDB(HttpSecurity http) throws Exception {
        http.csrf().disable()
        .authorizeRequests()
            .antMatchers("/","/logout").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/index")
            .loginProcessingUrl("/perform_login")
            .usernameParameter("email")
            .passwordParameter("password")
            .failureUrl("/index?failed=true")
            .defaultSuccessUrl("/summary",true)
            .permitAll()
            .authenticationProvider(authenticationProviderDB)
    //This line giving compilation error stating authenticationProvider is not available in formloginconfigurer

         .and()
         .logout().logoutUrl("/logout")
                  .logoutSuccessUrl("/index?logout=true").permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/error403");
    }

}

共有3个答案

斜高翰
2023-03-14

这是一个成功的配置,有助于在java config中配置多个身份验证提供者。非常感谢你的意见。它确实有助于确定这个问题。关键是拥有

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider);
    auth.authenticationProvider(authenticationProviderDB);

}

完整代码如下

@Configuration
@EnableWebSecurity
public class XSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LDAPAuthenticationProvider authenticationProvider;

    @Autowired
    private DBAuthenticationProvider authenticationProviderDB;

    @Override
      public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
             .antMatchers("/scripts/**","/styles/**","/images/**","/error/**");
      }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider);
        auth.authenticationProvider(authenticationProviderDB);

    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
        .authorizeRequests()
            .antMatchers("/","/logout").permitAll()
            .antMatchers("/admin").hasRole("ADMIN")         
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/index")
            .loginProcessingUrl("/perform_login")
            .usernameParameter("user")
            .passwordParameter("password")
            .failureUrl("/index?failed=true")
            .defaultSuccessUrl("/test",true)
            .permitAll()
            .and()
         .logout().logoutUrl("/logout")
                  .logoutSuccessUrl("/index?logout=true").permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/error");
    }


}
严阳成
2023-03-14

在Spring Boot中,这对我很有用:

按顺序测试每个身份验证提供程序。如果通过,则跳过其以下身份验证提供程序

< code > auth . userDetailsService(userDetailsService)...

那么:

< code>auth.ldapAuthentication()....

@EnableRedisHttpSession
@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private CustomUserDetailsService userDetailsService;

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

    //each Authentication provider is tested in order
    //if one passes then its following Authentication providers are skipped

    //DataBase Authentication
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());



    LdapContextSource ldapContextSource = new LdapContextSource();


    ldapContextSource.setUrl("ldap://192.168.XXX.XXX:389");
    ldapContextSource.setBase("dc=companyname,dc=com");
    ldapContextSource.setUserDn("cn=user,cn=testgroup,ou=Test,dc=companyname,dc=com");
    ldapContextSource.setPassword("user1234");
    ldapContextSource.afterPropertiesSet();



    //LDAP Authentication
    auth.ldapAuthentication()
        //The {0} in the (uid={0}) will be replaced by the username entered in the form.
        .userSearchBase("ou=Group")
        .userSearchFilter("uid={0}")

        //.userDnPatterns("uid={0},ou=people")//does the same thing 

        //Specifies where the search for Roles start
        //.groupSearchBase("ou=mathematicians")
        //in groups we search for member
        //.groupSearchFilter("member={0}")
        //.contextSource().ldif("classpath:test-server.ldif");

    .contextSource(ldapContextSource);



}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()


            .antMatchers("/hello").access("hasRole('ROLE_ADMIN')")
            .antMatchers("/index").fullyAuthenticated()
            .antMatchers("/").fullyAuthenticated()
            .antMatchers("/home").fullyAuthenticated()
            .anyRequest().permitAll()

            .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .usernameParameter("username").passwordParameter("password")
            .and()
            .logout()
                .logoutSuccessUrl("/login?logout")
                .permitAll()
            .and()
                .exceptionHandling()
                .accessDeniedPage("/403")
            .and()
                .csrf()
                .disable();



}

@Bean(name = "passwordEncoder")
public PasswordEncoder passwordencoder() {
    return new BCryptPasswordEncoder();
}
}
郎意
2023-03-14

也许这将帮助你:-

java prettyprint-override">@Configuration
@EnableWebSecurity
@Profile("container")
public class XSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private AuthenticationProvider authenticationProvider;

@Autowired
private AuthenticationProvider authenticationProviderDB;

@Override
@Order(1)

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider);
}

@Order(2)
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProviderDB);
}

@Override
  public void configure(WebSecurity web) throws Exception {
    web
      .ignoring()
         .antMatchers("/scripts/**","/styles/**","/images/**","/error/**");
  }

@Override
public void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/rest/**").authenticated()
            .antMatchers("/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .successHandler(new AuthenticationSuccessHandler() {
                @Override
                public void onAuthenticationSuccess(
                        HttpServletRequest request,
                        HttpServletResponse response,
                        Authentication a) throws IOException, ServletException {
                            //To change body of generated methods,
                            response.setStatus(HttpServletResponse.SC_OK);
                        }
            })
            .failureHandler(new AuthenticationFailureHandler() {

                @Override
                public void onAuthenticationFailure(
                        HttpServletRequest request,
                        HttpServletResponse response,
                        AuthenticationException ae) throws IOException, ServletException {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        }
            })
            .loginProcessingUrl("/access/login")
            .and()
            .logout()
            .logoutUrl("/access/logout")                
            .logoutSuccessHandler(new LogoutSuccessHandler() {
                @Override
                public void onLogoutSuccess(
                        HttpServletRequest request, 
                        HttpServletResponse response, 
                        Authentication a) throws IOException, ServletException {
                    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
                }
            })
            .invalidateHttpSession(true)
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(new Http403ForbiddenEntryPoint())
            .and()
            .csrf()//Disabled CSRF protection
            .disable();
    }
} 
 类似资料:
  • 我的问题是,我希望有两个身份验证提供商 之前:我有我的UserDetailServiceImpl,我根据数据库中的数据验证了用户的身份(不确定是哪个提供者) 现在:我使用了ActiveDirectoryLdapAuthentiation提供程序,如下所示 我成功了,所以我可以认证。 问题是: 我现在无法再使用数据库用户登录,现在只有LDAP。 未使用UserDetailsService,因此用户具

  • 我正在尝试为正在进行的 spring-boot 项目实现身份验证和授权服务。我已经实现了一个基于 JPA 的身份验证提供程序,它工作正常。如何将 LDAP 身份验证提供程序添加到同一项目并根据用户身份验证类型在身份验证方法之间切换? 下面是我的代码 虽然我的LDAP证书是正确的,但它没有达到那个方法。如何从DB ex(LDAP、JPA、SSO)获取我的应用程序的身份验证方法,并执行相应的身份验证提

  • 问题内容: 在Spring Security中,有多个身份验证提供程序的参考,但是找不到Java config中的示例。 以下链接给出了XML表示法: Spring Security中的多个身份验证提供程序 我们需要使用LDAP或DB进行身份验证 下面是我们的示例代码: 问题答案: 也许这会帮助你:

  • 我想为Spring Security配置L 我配置spring-security.xml指出m 如何设置为 Spring,使用我的自定义类而不是他的 deafaul LDAP 身份验证提供程序?

  • 我有一个使用bouncycastle库的Java applet。当我在Eclipse上运行应用程序时,一切正常,但当我在带有标记的浏览器上使用applet时,当我添加安全BouncyCastleProvider时,它会引发异常。 我的stackTrace是: 我正在使用bcpkix-jdk15on-1.48.jar和bcprov-jdk15on-1.48.jar版本的BouncyCastle。为什

  • 我实现了自己的UserDetailsService。我正在Java中配置Spring Security性。我如何创建默认身份验证提供程序与我的自定义用户服务详细信息服务和一些密码编码器? 但是,当我运行这段代码时,我有异常: 我想我做错了什么