用户身份验证失败时的 Spring Security ProviderNotFoundException

Posted

技术标签:

【中文标题】用户身份验证失败时的 Spring Security ProviderNotFoundException【英文标题】:Spring Security ProviderNotFoundException when user authentication fails 【发布时间】:2021-04-08 03:02:56 【问题描述】:

我已经设置了一个类似于此处示例的 LDAP 自定义身份验证提供程序 - https://www.baeldung.com/spring-security-authentication-provider

有一个登录控制器来处理登录错误并检查用户是否在批准的列表中。控制器调用自定义身份验证提供程序,authenticationManager.authenticate() 方法。

当提供错误的凭据时,自定义身份验证提供程序会被调用两次。抛出两个异常。

第一个例外:

31-12-2020 15:42:55.577 [http-nio-9090-exec-6] ERROR c.c.t.a.CustomAuthenticationProvider.hasAccess - test is not authenticated
javax.naming.AuthenticationException: [LDAP: error code 49 - 80090308: LdapErr: DSID-0C09044E, comment: AcceptSecurityContext error, data 52e, v2580 ]
        at com.sun.jndi.ldap.LdapCtx.mapErrorCode(Unknown Source) ~[na:1.8.0_261]
        at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source) ~[na:1.8.0_261]
        at com.sun.jndi.ldap.LdapCtx.processReturnCode(Unknown Source) ~[na:1.8.0_261]
        at com.sun.jndi.ldap.LdapCtx.connect(Unknown Source) ~[na:1.8.0_261]
        at com.sun.jndi.ldap.LdapCtx.ensureOpen(Unknown Source) ~[na:1.8.0_261]
        at com.sun.jndi.ldap.LdapCtx.ensureOpen(Unknown Source) ~[na:1.8.0_261]
        at com.sun.jndi.ldap.LdapCtx.reconnect(Unknown Source) ~[na:1.8.0_261]
        at javax.naming.ldap.InitialLdapContext.reconnect(Unknown Source) ~[na:1.8.0_261]
        at com.tools.auth.CustomAuthenticationProvider.hasAccess(CustomAuthenticationProvider.java:65) [classes!/:1.0.0-SNAPSHOT]
        at com.tools.auth.CustomAuthenticationProvider.authenticate(CustomAuthenticationProvider.java:32) [classes!/:1.0.0-SNAPSHOT]
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174) [spring-security-core-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199) [spring-security-core-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
        at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:502) [spring-security-config-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
        at com.tools.web.JwtAuthenticationRestController.authenticate(JwtAuthenticationRestController.java:70) [classes!/:1.0.0-SNAPSHOT]

第二个例外:

c.c.t.a.CustomAuthenticationProvider.authenticate - User does not have access
31-12-2020 15:42:55.613 [http-nio-9090-exec-6] ERROR c.c.t.w.JwtAuthenticationRestController.authenticate - Exception logging in user
org.springframework.security.authentication.ProviderNotFoundException: No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:227) ~[spring-security-core-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
        at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$AuthenticationManagerDelegator.authenticate(WebSecurityConfigurerAdapter.java:502) ~[spring-security-config-5.0.3.RELEASE.jar!/:5.0.3.RELEASE]
        at com.tools.web.JwtAuthenticationRestController.authenticate(JwtAuthenticationRestController.java:70) [classes!/:1.0.0-SNAPSHOT]

这是自定义提供程序:

public class CustomAuthenticationProvider implements AuthenticationProvider 

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException 
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        if (hasAccess(name, password)) 
            Authentication auth = new UsernamePasswordAuthenticationToken(name,
                    password);
            return auth;
         else 
            return null;
        
    

    public boolean supports(Class<?> authentication) 
        return true;
    

    public boolean hasAccess(final String username, final String password) 
    //LDAP access happens here
    

这是控制器:

public class JwtAuthenticationRestController 

    @Autowired
    private AuthenticationManager authenticationManager;

    @CrossOrigin
    @RequestMapping(value = "/authenticate", method = RequestMethod.POST)
    public ResponseEntity<?> createAuthenticationToken(@RequestBody JwtTokenRequest authenticationRequest)
            throws AuthenticationException 
        authenticate(authenticationRequest.getUsername(), authenticationRequest.getPassword());
         //generate token
        return ResponseEntity.ok(new JwtTokenResponse(token));
    

    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<String> handleAuthenticationException(AuthenticationException e) 
    //handle exception. set custom response.
    

    private void authenticate(String username, String password)    
        try 
            // Check against the approved user list
            //Authenticate the user - Exception thrown here
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        catch (Exception e) 
            throw new AuthenticationException("APPLICATION_ERROR", e);
        
    

更新这是网络安全配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class JWTWebSecurityConfig extends WebSecurityConfigurerAdapter 

    @Autowired
    private JwtUnAuthorizedResponseAuthenticationEntryPoint jwtUnAuthorizedResponseAuthenticationEntryPoint;

    @Autowired
    private JwtTokenAuthorizationOncePerRequestFilter jwtAuthenticationTokenFilter;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception 
        auth.authenticationProvider(new CustomAuthenticationProvider());
       

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception 
        return super.authenticationManagerBean();
    

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception 
        httpSecurity
            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(jwtUnAuthorizedResponseAuthenticationEntryPoint).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
            .anyRequest().authenticated();

        httpSecurity
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        httpSecurity
            .headers()
            .frameOptions().sameOrigin()  
            .cacheControl(); 
    

    @Override
    public void configure(WebSecurity webSecurity)  
        webSecurity
            .ignoring()
            .antMatchers(
                HttpMethod.POST,
                "/authenticate" //authentication path
            )
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .and()
            .ignoring()
            .antMatchers(
                HttpMethod.GET,
                        "\"login" //Ignore security for Login page.
                )
            .and()
            .ignoring()
            .antMatchers("/h2-console/**/**");    
    

仅当由于密码无效而导致身份验证失败时才会发生这种情况。我检查了自定义提供程序是否抛出 javax.naming.AuthenticationException 并为无效凭据返回 null。

为什么 Spring 会因身份验证失败而抛出此异常?解决方法是将 Controller 中的异常处理为登录失败,但最好理解为什么会发生这种情况。

【问题讨论】:

你能提供你的 Spring Security 配置吗?您是否已将 AuthenticationProvider 添加到 authenticationManager 中?? @JuanBC 在安全配置中添加了 Auth Provider。我也在问题中添加了安全配置。 【参考方案1】:

仅从 AuthenticationProvider 实施不会解决您的目的。您需要使用AuthenticationManagerBuilder 注册您的提供商。希望你没有错过Register the Auth Provider的那一步

你可以这样做:


@Configuration
@EnableWebSecurity
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter 

private final CustomAuthenticationProvider customAuthenticationProvider;

@Autowired
public MyWebSecurityConfig(CustomAuthenticationProvider customAuthenticationProvider)
 this.customAuthenticationProvider = customAuthenticationProvider;


@Override
public void configure(AuthenticationManagerBuilder authBuilder) throws Exception 
  authBuilder.authenticationProvider(CustomAuthenticationProvider );


在您的 WebSecurityConfig 类中注入您的 custom-provide,并将该字段设置为身份验证提供程序之一。

【讨论】:

是的。这个做完了。我在问题中添加了安全配置代码。【参考方案2】:

您是否验证了 CustomAuthenticationProvider 是从您的控制器中调用的?这个异常很明显来自ProviderManager 类。来自ProviderManagerjavadoc:

如果没有提供者返回非空响应,或者表明它甚至可以处理身份验证,则 ProviderManager 将抛出 ProviderNotFoundException。

如果您遵循 Baeldung 示例,那么 Spring 在调用堆栈中处理身份验证过程的位置比您的控制器更靠前。

【讨论】:

根据日志,在控制器中针对两种情况(有效/无效凭据)调用 CustomAuthenticationProvider。 什么日志?我在您的课程中没有看到任何日志记录。您发布的部分堆栈跟踪清楚地显示了源自ProviderManager.authenticate(ProviderManager.java:227) 的异常该类是spring security 的一部分。如果它正在被调用,那么它会在您的控制器到达之前发生。

以上是关于用户身份验证失败时的 Spring Security ProviderNotFoundException的主要内容,如果未能解决你的问题,请参考以下文章

我们可以将输入的用户名传递给spring security中的身份验证失败url吗?

Spring Security - 用户身份验证有时会失败并且用户被重定向到登录页面

使用 Twitch 进行身份验证时的 Spring-Boot OAuth2 奇怪行为

使用 javaconfig 使用 Spring Security 对身份验证进行摘要

Grails Spring Security 插件身份验证失败

Spring Security:如果身份验证失败,则重定向到登录页面