Spring 安全性使用空的基本身份验证凭据响应空正文



我正在尝试制作基本的身份验证服务,对于某些业务逻辑,我需要加速所有基本的身份验证凭据并使它们命中另一个服务(如果凭据错误,它将失败(。 因此,我尝试在基本身份验证不存在或为空凭据时引发异常。

这是我的安全配置器:

@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();
}
}

这是我的自定义身份验证提供程序:

@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 未经授权"(我真的很想获得我的自定义异常,您可以在我的自定义身份验证提供程序中看到(。 当我只发送 1 个凭据(用户名或密码(或没有人发送时,我的服务在 POSTMAN 用空体回答我。你们能帮我吗?

据我了解,您的问题与我几天前遇到的问题类似:每当调用未授权或身份验证令牌过期的端点时,我需要返回 401 而不是 403。
关于您的代码,我会将.exceptionHandling((.authenticationEntryPoint(...(添加到您的 WebSecurityConfigurerAdapter 中,如下所示

@Configuration
@EnableWebSecurity
public class SecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
/* other stuff */
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and().httpBasic()
.exceptionHandling().authenticationEntryPoint(/*custom exception*/);
}
}

然后,代替/*自定义异常*/添加一些内容作为new MyAuthException(),其中 MyAuthException 如下所示:

@Component
public class MyAuthException implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) /*throws ...*/ {
response.setStatus(/* your status */);
response.getWriter().write(/*the body of your answer*/);
/* whatever else you want to add to your response */
/* or you could throw an exception, I guess*/
}
}

(我不记得了,现在我无法检查这个类是否需要标记为@Component,我认为不需要(。

相关内容

最新更新