복붙노트

[SPRING] AuthenticationFailureHandler를 사용하는 Spring Security의 인증 실패 응답 커스터마이즈

SPRING

AuthenticationFailureHandler를 사용하는 Spring Security의 인증 실패 응답 커스터마이즈

현재, 사용자가 인증에 실패 할 때마다 스프링 보안은 다음과 같이 응답합니다.

{"error": "invalid_grant","error_description": "Bad credentials"}

그리고 저는 다음과 같은 응답 코드로이 응답을 향상시키고 싶습니다 :

{"responsecode": "XYZ","error": "invalid_grant","error_description": "Bad credentials"}

몇 가지 살펴본 후,이 작업을 수행하기 위해 필요한 작업은 AuthenticationFailureHandler를 구현하는 것입니다. 그러나 잘못된 로그인 자격 증명을 제출할 때마다 onAuthenticationFailure 메서드에 도달하지 못하는 것 같습니다. 코드를 밟아서 onAuthenticationFailure 메서드에 로그인하여 도달하지 않았 음을 확인했습니다.

내 오류 처리기는 다음과 같습니다.

@Component
public class SSOAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler{

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
        super.onAuthenticationFailure(request, response, exception);
        response.addHeader("responsecode", "XYZ");  
    }
}

내 WebSecurityConfigurerAdapter에는 다음이 포함됩니다.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired SSOAuthenticationFailureHandler authenticationFailureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.formLogin().failureHandler(authenticationFailureHandler);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(service).passwordEncoder(passwordEncoder());
        auth.authenticationEventPublisher(defaultAuthenticationEventPublisher());
    }

    @Bean
    public DefaultAuthenticationEventPublisher defaultAuthenticationEventPublisher(){
        return new DefaultAuthenticationEventPublisher();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public SSOAuthenticationFailureHandler authenticationHandlerBean() {
        return new SSOAuthenticationFailureHandler();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }
}

내 질문은 다음과 같습니다.

고맙습니다!

해결법

  1. ==============================

    1.configure 메소드의 HttpSecurity 객체에서 .exceptionHandling ()을 호출하여 Spring Security에 예외 처리를 추가 할 수 있습니다. 잘못된 자격 증명 만 처리하려는 경우 .accessDeniedHandler (accessDeniedHandler ())를 무시할 수 있습니다.

    configure 메소드의 HttpSecurity 객체에서 .exceptionHandling ()을 호출하여 Spring Security에 예외 처리를 추가 할 수 있습니다. 잘못된 자격 증명 만 처리하려는 경우 .accessDeniedHandler (accessDeniedHandler ())를 무시할 수 있습니다.

    액세스 거부 처리기는 @PreAuthorized, @PostAuthorized 및 @Secured를 사용하는 것과 같이 메소드 수준에서 앱을 확보 한 상황을 처리합니다.

    보안 설정의 예는 다음과 같습니다.

    SecurityConfig.java
    /* 
       The following two are the classes we're going to create later on.  
       You can autowire them into your Security Configuration class.
    */
    @Autowired
    private CustomAuthenticationEntryPoint unauthorizedHandler;
    
    @Autowired
    private CustomAccessDeniedHandler accessDeniedHandler;    
    
    /*
      Adds exception handling to you HttpSecurity config object.
    */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
            .disable()
            .exceptionHandling()
                .authencationEntryPoint(unauthorizedHandler)  // handles bad credentials
                .accessDeniedHandler(accessDeniedHandler);    // You're using the autowired members above.
    
    
        http.formLogin().failureHandler(authenticationFailureHandler);
    }
    
    /*
      This will be used to create the json we'll send back to the client from
      the CustomAuthenticationEntryPoint class.
    */
    @Bean
    public Jackson2JsonObjectMapper jackson2JsonObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        return new Jackson2JsonObjectMapper(mapper);
    }   
    

    CustomAuthenticationEntryPoint.java

    이 파일은 별도의 파일로 만들 수 있습니다. 진입 점이 잘못된 자격 증명을 처리합니다. 이 메소드 내에서 HttpServletResponse 객체에 자체 JSON을 작성하고 작성해야합니다. 잘 보안 구성에서 작성한 Jackson 객체 맵퍼 bean을 사용하십시오.

     @Component
    public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
    
        private static final long serialVersionUID = -8970718410437077606L;
    
        @Autowired  // the Jackson object mapper bean we created in the config
        private Jackson2JsonObjectMapper jackson2JsonObjectMapper;
    
        @Override
        public void commence(HttpServletRequest request,
                             HttpServletResponse response,
                             AuthenticationException e) throws IOException {
    
            /* 
              This is a pojo you can create to hold the repsonse code, error, and description.  
              You can create a POJO to hold whatever information you want to send back.
            */ 
            CustomError error = new CustomError(HttpStatus.FORBIDDEN, error, description);
    
            /*
              Here we're going to creat a json strong from the CustomError object we just created.
              We set the media type, encoding, and then get the write from the response object and write
          our json string to the response.
            */
            try {
                String json = jackson2JsonObjectMapper.toJson(error);
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
                response.getWriter().write(json);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
    
        }
    }
    

    CustomAccessDeniedHandler.java

    이것은 권한 부여 오류를 처리합니다. 적절한 특권. 잘못된 자격 증명 예외로 위에서 수행 한 것과 같은 방식으로 구현할 수 있습니다.

    @Component
    public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    
        @Override
        public void handle(HttpServletRequest request, HttpServletResponse response,
            AccessDeniedException e) throws IOException, ServletException {
    
        // You can create your own repsonse here to handle method level access denied reponses..
        // Follow similar method to the bad credentials handler above.
        }
    
    }
    

    바라기를 이것은 다소 도움이된다.

  2. from https://stackoverflow.com/questions/42839910/customize-authentication-failure-response-in-spring-security-using-authenticatio by cc-by-sa and MIT license