복붙노트

[SPRING] 무효 신임장에 대한 기본 인증이 / error로 리디렉션되는 스프링 보안

SPRING

무효 신임장에 대한 기본 인증이 / error로 리디렉션되는 스프링 보안

나는 기본 인증을 사용하여 스프링 보안으로 실행되는 스프링 부트 응용 프로그램을 가지고있다. 적절한 기본 인증 자격 증명이 제공되면 모든 것이 좋지만 잘못된 인증 자격 증명의 경우 HttpRequestMethodNotSupportedException이 봄이됩니다. 요청 메소드 'POST'가 지원되지 않는 예외입니다.

로그에 따르면 인증 실패는 봄까지 확인되었지만 그 결과는 나오지 않습니다.

2015-08-12 09 : 33 : 10.922 정보 16988 --- [nio-8080-exec-4] osbaaudit.listener.AuditListener : AuditEvent [timestamp = Wed Aug 12 09:33:10 AEST 2015, principal = anonymousUser, type = AUTHORIZATION_FAILURE, data = {type = org.springframework.security.access.AccessDeniedException, message = 액세스가 거부되었습니다.}] 2015-08-12 09 : 33 : 10.927 TRACE 16988 --- [nio-8080-exec-4] osweb.servlet.DispatcherServlet : 스레드에 바인딩 된 요청 컨텍스트 : FirewalledRequest [org.apache.catalina.core.ApplicationHttpRequest@483e1fc6 ] 2015-08-12 09 : 33 : 10.927 DEBUG 16988 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : 이름이 'dispatcherServlet'인 DispatcherServlet이 [/ myapplication / error]에 대한 POST 요청을 처리 중입니다. 2015-08-12 09 : 33 : 10.927 TRACE 16988 --- [nio-8080-exec-4] osweb.servlet.DispatcherServlet : 핸들러 맵 테스트 [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping@331bb032] 이름이 'dispatcherServlet'인 DispatcherServlet 2015-08-12 09 : 33 : 10.927 TRACE 16988 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : [/ error]에 대한 핸들러 매핑이 없습니다. 2015-08-12 09 : 33 : 10.927 TRACE 16988 --- [nio-8080-exec-4] osweb.servlet.DispatcherServlet : 테스트 핸들러 맵 [org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping@69e79b9b ]를 DispatcherServlet에 저장하고 'dispatcherServlet' 2015-08-12 09 : 33 : 10.927 TRACE 16988 --- [nio-8080-exec-4] osweb.servlet.DispatcherServlet : 테스팅 핸들러 맵 [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping @ 27cc0354]를 DispatcherServlet에 저장하고 'dispatcherServlet' 2015-08-12 09 : 33 : 10.927 DEBUG 16988 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : 경로 / 오류에 대한 핸들러 메소드 찾기 2015-08-12 09 : 33 : 10.928 DEBUG 16988 --- [nio-8080-exec-4] .mmaExceptionHandlerExceptionResolver : 핸들러 [null]에서 예외를 해결하는 중 : org.springframework.web.HttpRequestMethodNotSupportedException : 요청 메소드 'POST'가 아닙니다. 지원되는

위의 로그 및 스프링 소스 디버깅 후, 나는 자격 증명이 잘못되었음을 확인하면 Spring에서 BadCredentials 예외를 생성 한 다음 "/ error"로 리디렉션을 시도하지만이 리디렉션은 HttpMethodNotAllowed 예외의 원인입니다. (my 응용 프로그램에 / 오류 엔드 포인트가 없음).

나는 다음과 같이 설정함으로써 / 에러를 사용하지 않도록 스프링에게 알려 주려고 노력했다.

`public class ServerCustomization extends ServerProperties {

@Override
public void customize(ConfigurableEmbeddedServletContainer container) {

    super.customize(container);
    container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, null));

}`

이렇게하면 HttpMethodnotallowed 예외가 튀어 나오고 401 (Unauthorized)이 생기게되지만,이 예외는 예외 처리기 (@ControllerAdvice를 사용하여 구성됨)에서 발견하지 못합니다.

행운을 빌지 않고 아래와 같이 사용자 정의 인증 엔트리 포인트를 구성 해 보았습니다.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

AlwaysSendUnauthorized401AuthenticationEntryPoint alwaysSendUnauthorized401AuthenticationEntryPoint = 
        new AlwaysSendUnauthorized401AuthenticationEntryPoint();


@Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers().httpStrictTransportSecurity().xssProtection().and().authorizeRequests().anyRequest().fullyAuthenticated()
            .and().csrf().disable();

    http.exceptionHandling().authenticationEntryPoint(alwaysSendUnauthorized401AuthenticationEntryPoint);
}

public class AlwaysSendUnauthorized401AuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public final void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

}

/ error로 리다이렉트하지 않고 나쁜 신용 증명 예외를 반환하도록 지정할 수있는 방법이 있습니까?

해결법

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

    1.나는 다음의 보안 설정을 가진 Spring Boot app 예제를 만들었다 :

    나는 다음의 보안 설정을 가진 Spring Boot app 예제를 만들었다 :

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("test").password("password").roles("USER");
        }
    
        @Bean
        public AuthenticationEntryPoint authenticationEntryPoint() {
            return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.headers().httpStrictTransportSecurity().xssProtection()
                    .and().authorizeRequests().anyRequest().fullyAuthenticated()
                    .and().csrf().disable();
    
            http.httpBasic().authenticationEntryPoint(authenticationEntryPoint());
            http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint());
    
        }
    }
    

    유효하지 않은 사용자 이름 / 암호 (test / password 이외)를 입력하면 다음과 같은 응답이 표시됩니다.

    {"timestamp":1439381390204,"status":401,"error":"Unauthorized","message":"Bad credentials","path":"/"}
    

    이 오류는 org.springframework.boot.autoconfigure.web.BasicErrorController 클래스에 의해 반환됩니다.이 클래스는 @RequestMapping ( "/ error") - errorHtml 및 error가있는 두 개의 메소드를 정의합니다. API를 작성하기 때문에 두 번째로 호출해야하며 올바른 동작이라고 할 수 있습니다.

    먼저, 인증 실패시 BasicErrorController에 도착했는지 확인하십시오. 그렇다면 errorHTML이 아닌 오류 메 시지를 치고 있는지 확인하십시오.

    위의 내용 중 아무 것도 도움이되지 않는다면 누군가가 오류 컨트롤러의 기본 동작을 재정의했는지 확인하십시오. 일반적인 (그리고 유효한) 확장은 org.springframework.boot.autoconfigure.web.ErrorAttributes를 구현하여 기본 오류 페이로드를 변경하는 것입니다. 그러나 전체 BasicErrorController를 비표준 구현으로 쉽게 교체 할 수 있으므로 응용 프로그램에서이를 확인하십시오.

    다른 모든 방법이 실패하고 Spring 기본 오류 처리를 비활성화하려는 경우 (권장하지 않음) 구성에 다음을 추가하십시오.

    @EnableAutoConfiguration (제외 = {ErrorMvcAutoConfiguration.class})

    이 작업을 수행하려면 오류 컨 트롤러가 응용 프로그램 컨텍스트에로드되지 않도록해야합니다.

  2. ==============================

    2.http.exceptionHandling (). authenticationEntryPoint 대신 http.httpBasic (). authenticationEntryPoint를 사용해야한다고 생각합니다. 폼 기반 인증의 경우, 이것이 저에게 효과적입니다.

    http.exceptionHandling (). authenticationEntryPoint 대신 http.httpBasic (). authenticationEntryPoint를 사용해야한다고 생각합니다. 폼 기반 인증의 경우, 이것이 저에게 효과적입니다.

    http
        .formLogin()
            .failureHandler(authenticationFailureHandler())
            ...
        ...
    

    인증 실패 처리기의 경우 Spring의 SimpleUrlAuthenticationFailureHandler를 사용할 수 있습니다. 매개 변수없이 인스턴스화하면 원하는대로 할 수 있습니다.

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new SimpleUrlAuthenticationFailureHandler();
    }   
    

    도움이 될 경우를 대비하여이 파일은 완전한 보안 설정 파일입니다.

  3. from https://stackoverflow.com/questions/31954292/spring-security-with-basic-auth-redirecting-to-error-for-invalid-credentials by cc-by-sa and MIT license