在使用Spring Security进行身份验证方面需要帮助。这是为了验证REST API,没有UI(formlogin等)。
配置有身份验证提供程序和身份验证入口点以处理异常。 下面是安全配置和身份验证提供程序类。请检查。问题是 1.当我们调用不带身份验证的API(不带凭据)时,它提供了带有响应正文的有效异常-“访问此资源需要完全身份验证”。 2.当我们使用错误的凭据(错误的用户名/密码)调用API时-它仅提供http状态代码为401,没有响应正文。
安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().fullyAuthenticated();
// http.authorizeRequests().anyRequest().permitAll();
http.addFilterAfter(securityFilter, BasicAuthenticationFilter.class);
http.exceptionHandling()
.authenticationEntryPoint(new AuthenticationEntryPoint());
http.httpBasic();
http.csrf().disable();
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
}
身份验证提供者:
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Authentication auth = null;
try {
auth = authenticationProvider().authenticate(authentication);
} catch (BadCredentialsException e) {
LOGGER.info("User Authenticated Status Active Directory 1:" + e.getMessage());
throw new BadCredentialsException("Authentication Failed :" + e.getMessage());
} catch (Exception e) {
LOGGER.info("User Authenticated Status Active Directory:" + e.getMessage());
throw new BadCredentialsException("Authentication Failed :" + e.getMessage());
}
return auth;
}
```
http.authorizeRequests().anyRequest().fullyAuthenticated() - // working for No Auth but not for incorrect credentials
http.authorizeRequests().anyRequest().permitAll(); - // working for incorrect credentials but not if user provided no credentials - it is allowing all request with no basic auth details which is invalid
I tried with different ways by using authentication failure handler , security filter bean - but no luck.
Please advise on the above issue on how to handle.