basicauthenticationentrypoint未返回www authenticate标头

nle07wnf  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(206)

我在玩springsecurity,试图了解它是如何工作的。我试图将basicauthenticationentrypoint设置为响应发射器,以防未经授权尝试访问我的api。我就是这么做的:

@Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, "/auth").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new AuthenticationFilter(authenticationManager()))
                .addFilter(new AuthorizationFilter(authenticationManager()))
                .addFilter(new ExceptionTranslationFilter(new BasicAuthenticationEntryPoint()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
                //.and()
                //.exceptionHandling().authenticationEntryPoint(new BasicAuthenticationEntryPoint());
    }

我得到的答复是:

{
    "timestamp": "2021-02-05T20:00:26.066+00:00",
    "status": 403,
    "error": "Forbidden",
    "message": "Access Denied",
    "path": "/find/shipmentNumber/1"
}

也没有头像。
我正在检查basicauthenticationentrypoint的源代码,希望添加提到的头:

public class BasicAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean {

    private String realmName;

    @Override
    public void afterPropertiesSet() {
        Assert.hasText(this.realmName, "realmName must be specified");
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {
        response.addHeader("WWW-Authenticate", "Basic realm=\"" + this.realmName + "\"");
        response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
    }

    public String getRealmName() {
        return this.realmName;
    }

    public void setRealmName(String realmName) {
        this.realmName = realmName;
    }

}

但是,如果我这样做,它会起作用:

@Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST, "/auth").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new AuthenticationFilter(authenticationManager()))
                .addFilter(new AuthorizationFilter(authenticationManager()))
                //.addFilter(new ExceptionTranslationFilter(new BasicAuthenticationEntryPoint()))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling().authenticationEntryPoint(new BasicAuthenticationEntryPoint());
    }

有人能解释一下为什么不使用第一种方法吗?正在使用authenticationentrypoint的另一个实现吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题