Spring Security使用空的基本身份验证凭据响应空的主体

问题描述 投票:1回答:1

我正在尝试提供基本的身份验证服务,对于某些业务逻辑,我需要接受所有基本的身份验证凭据,并使其打入另一项服务(如果凭据错误,将会失败)。因此,当基本身份验证不存在或凭据为空时,我正在尝试引发异常。

这是我的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中用空的正文回答我。你们可以帮我吗?

java spring-security basic-authentication
1个回答
0
投票
据我所知,您的问题与几天前的情况类似:每当在没有授权或身份验证令牌的情况下调用端点时,我都需要返回401而不是403。关于您的代码,我将

。exceptionHandling()。authenticationEntryPoint(...)

添加到您的WebSecurityConfigurerAdapter中,如下所示
© www.soinside.com 2019 - 2024. All rights reserved.