首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当用户身份验证失败时,Spring安全性ProviderNotFoundException

当用户身份验证失败时,Spring安全性ProviderNotFoundException
EN

Stack Overflow用户
提问于 2021-01-01 01:48:14
回答 2查看 3.4K关注 0票数 2

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

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

如果提供了错误的凭据,则会调用两次自定义Auth提供程序。引发两个异常。

第一个例外:

代码语言:javascript
运行
复制
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]

第二个例外:

代码语言:javascript
运行
复制
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]

这是自定义提供程序:

代码语言:javascript
运行
复制
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
    }
}

这位是财务主任:

代码语言:javascript
运行
复制
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);
        }
    }
}

更新这里是Web配置:

代码语言:javascript
运行
复制
@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中的异常作为登录失败来处理,但是理解这种情况的原因还是很好的。

EN

回答 2

Stack Overflow用户

发布于 2021-01-01 02:21:19

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

如果没有提供程序返回非空响应,或者指示它甚至可以处理身份验证,ProviderManager将抛出一个ProviderNotFoundException。

如果您已经遵循了Baeldung的示例,那么spring在调用堆栈中处理的auth进程比您的控制器要高得多。

票数 3
EN

Stack Overflow用户

发布于 2021-01-01 15:31:59

仅仅从AuthenticationProvider实现并不能解决您的目的。您需要向AuthenticationManagerBuilder注册您的提供者。希望您在注册Auth提供者上没有错过这一步

你可以这样做:

代码语言:javascript
运行
复制
@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类中注入自定义提供程序,并将该字段设置为auth提供程序之一。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65526778

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档