首页 > 解决方案 > Spring Security 使用空的基本身份验证凭据响应空主体

问题描述

我正在尝试制作一个基本的身份验证服务,对于某些业务逻辑,我需要接受所有基本的身份验证凭据并让它们访问另一个服务(如果凭据错误,它将失败)。因此,当基本身份验证不存在或为空凭据时,我试图抛出异常。

这是我的安全配置器:

@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 以空的正文回答我。你们能帮帮我吗?

标签: javaspring-securitybasic-authentication

解决方案


据我了解,您的问题与我几天前遇到的问题相似:每当在没有授权或身份验证令牌过期的情况下调用端点时,我都需要返回 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*/);
    }
}

然后,代替 /*custom exception*/ 添加一些东西 as 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,我认为不需要)。


推荐阅读