我正在尝试提供基本的身份验证服务,对于某些业务逻辑,我需要接受所有基本的身份验证凭据,并使其打入另一项服务(如果凭据错误,将会失败)。因此,当基本身份验证不存在或凭据为空时,我正在尝试引发异常。
这是我的SecurityConfigurer:
@Configuration
@EnableWebSecurity
public class SecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Autowired
STGAuthenticationProvider authProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and().httpBasic();
}
}
这是我的CustomAuthProvider:
@Component
public class STGAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
if(!StringUtils.isBlank(username) && !StringUtils.isBlank(password)) {
return new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>());
} else {
throw new STGNoCredentialsException(Constants.Error.NO_CREDENTIALS);
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}
实际上,如果我发送的请求没有身份验证,我的应用程序会给我“ 401未经授权”(我真的很想获得我的自定义Exception,您可以在我的CustomAuthProvider上看到)。当我仅发送1份凭据(用户名或密码),或者没有人发送时,我的服务在POSTMAN中用空的正文回答我。你们可以帮我吗?
。exceptionHandling()。authenticationEntryPoint(...)
添加到您的WebSecurityConfigurerAdapter中,如下所示