Spring Security 配置httpBasic()时不应用BasicAuthenticEntryPoint

j91ykkif  于 2023-04-30  发布在  Spring
关注(0)|答案(1)|浏览(141)

我已经在这里搜索了BasicAuthenticationEntryPoint的问题,但我不明白我的实际问题。我是一个应用程序,我用基本的身份验证用户/通行证(Authorization: Basic xxxxxxxxxx头)保护所有端点。但是当身份验证失败时,我需要创建一些自定义异常,因此我创建了自己的入口点类,以便能够合并我的异常。
但是这个入口点只有在**httpBasic()**从SecurityConfig中删除时才有效,否则将跳过。

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    ....

        http
            .authorizeHttpRequests()
                .anyRequest().authenticated()
                .and()
            .httpBasic()
                .and()
            .exceptionHandling()
                .authenticationEntryPoint(customBasicAuthEntryPoint);

        return http.build();
    }

    @Component
    public class CustomBasicAuthEntryPoint extends BasicAuthenticationEntryPoint {
 
        private final ObjectMapper objectMapper;

        public CustomBasicAuthEntryPoint(ObjectMapper objectMapper) {
            this.objectMapper = objectMapper;
    }   
    
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {

        Error error = new Error();

        if (authException instanceof BadCredentialsException){
            error.setMessage("Unauthorized please add a basic auth");
            error.setStatusCode(HttpStatus.UNAUTHORIZED.value());
            error.setTimestamp(Timestamp.from(Instant.now()));
        }
        else{
            error.setMessage(authException.getMessage());
            error.setStatusCode(response.getStatus());
            error.setTimestamp(Timestamp.from(Instant.now()));
        }

        response.setStatus(error.getStatusCode());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        objectMapper.writeValue(response.getWriter(), error);
    }    
}

我做错了什么?

rur96b6h

rur96b6h1#

我通过更改配置顺序来解决此问题

http
     .authorizeHttpRequests()
        .anyRequest().authenticated()
        .and()
     .httpBasic()
        .and()
     .exceptionHandling()
        .authenticationEntryPoint(customBasicAuthEntryPoint);

通过

http
     .authorizeHttpRequests()
         .anyRequest().authenticated()
         .and()
     .httpBasic()
         .authenticationEntryPoint(customBasicAuthEntryPoint)
         .and();

有道理

相关问题