【发布时间】:2020-05-29 11:09:51
【问题描述】:
我正在尝试制作基本身份验证服务,对于某些业务逻辑,我需要接受所有基本身份验证凭据并让它们访问另一个服务(如果凭据错误,它将失败)。 因此,当基本身份验证不存在或为空凭据时,我试图抛出异常。
这是我的安全配置器:
@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 Unauthorized”(我真的很想获得我的自定义异常,您可以在我的 CustomAuthProvider 中看到)。 当我只发送 1 个凭据(用户名或密码),或者一个都不发送时,我的服务会在 POSTMAN 以空的正文回答我。你们能帮帮我吗?
【问题讨论】:
标签: java spring-security basic-authentication