问题描述
我已经设置了一个类似于此处示例的 LDAP 自定义身份验证提供程序 - https://www.baeldung.com/spring-security-authentication-provider
有一个登录控制器来处理登录错误并检查用户是否在批准的列表中。 Controller 调用自定义身份验证提供程序,即 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
并为 invalis 凭据返回 null。
为什么 Spring 会在身份验证失败时抛出此异常?解决方法是将 Controller 中的异常作为登录失败处理,但仍然最好理解为什么会发生这种情况。
解决方法
您是否确认 CustomAuthenticationProvider
是从您的控制器中调用的?该异常很明显来自 ProviderManager
类。来自 ProviderManager
javadoc:
如果没有提供者返回非空响应,或者表示它甚至可以处理身份验证,则 ProviderManager 将抛出 ProviderNotFoundException。
如果您遵循了 Baeldung 示例,则 spring 将在调用堆栈中比您的控制器更进一步地处理身份验证过程。
,仅从 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
类中注入您的自定义提供,并将该字段设置为身份验证提供者之一。