복붙노트

[SPRING] Spring 보안 - 로그인으로 리다이렉션시 URL 매개 변수 유지하기

SPRING

Spring 보안 - 로그인으로 리다이렉션시 URL 매개 변수 유지하기

승인.

보안 URL 패턴이 있다고 가정 해 보겠습니다.

/secure/link-profile

선택적으로 url 매개 변수가 추가 될 수 있습니다.

/secure/link-profile?firstName=Bob&secondName=Smith&membershipNumber=1234

어떻게 url 매개 변수가 로그인 페이지로 옮겨 지도록 만들 수 있습니까?

/login?firstName=Bob&secondName=Smith&membershipNumber=1234

기본적인 전제는 제 3 자와 보상을 통합하여 사용자를 우리에게 보낼 것임을 말합니다. 그들은 자신의 / 우리의 웹 사이트 사용자와 제 3 자 계정 / 프로필을 연결하는 페이지로 이동합니다. 그러나 기존 계정이 없으면 로그인 페이지에서 가입 페이지로 이동하여 제 3자가 전달한 세부 정보 중 일부를 미리 채울 수 있습니다.

미리 감사드립니다.

봄 보안 2.0.7.RELEASE 스프링 프레임 워크 3.1.1.RELEASE

해결법

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

    1.LoginUrlAuthenticationEntryPoint의 메소드 buildRedirectUrlToLoginPage (HttpServletRequest request, ...)를 참조하십시오.

    LoginUrlAuthenticationEntryPoint의 메소드 buildRedirectUrlToLoginPage (HttpServletRequest request, ...)를 참조하십시오.

    달성하고자하는 것을 정확하게 이해했다면, 서브 클래스에서이 메소드를 대체하고, 원래 메소드를 복사하고, 추가로 호출해야합니다. urlBuilder.setQuery (request.getQueryString ()) URL을 작성할 때.

    그런 다음 사용자 정의 엔트리 포인트를 사용하여 ExceptionTranslationFilter를 구성하기 만하면됩니다.

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

    2.@ zagyi의 응답에 따라 기존의 AuthenticationProcessingFilterEntryPoint 확장에서 메소드를 오버로드했습니다.

    @ zagyi의 응답에 따라 기존의 AuthenticationProcessingFilterEntryPoint 확장에서 메소드를 오버로드했습니다.

    오버라이드 (override)하는 메소드가 보호되고있다. String determineUrlToUseForThisRequest (HttpServletRequest request, HttpServletResponse response,             AuthenticationException 예외). 이것은 buildRedirectUrlToLoginPage (..)에 의해 호출됩니다.

    @Override
    protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) {
        String url = super.determineUrlToUseForThisRequest(request, response, exception);
        return url + "?" + request.getQueryString();
    }
    

    분명히 그 또한 URL의 기존 쿼리 문자열에 대한 음식을 제공하는 일종의 빌더를 사용하여 향상시킬 수 있지만 지금은 내 로그인 URL을 항상 / 로그인 / 알고,이 내 목적을 위해 괜찮습니다

  3. ==============================

    3.다른 기사에서는 재정의가 작동하지 않는 방법을 설명합니다. 나는 시작을 무시할 필요가 있었다. 아마도 스프링 보안의 최신 버전에서 소개 된 새로운 기능 일 것입니다.

    다른 기사에서는 재정의가 작동하지 않는 방법을 설명합니다. 나는 시작을 무시할 필요가 있었다. 아마도 스프링 보안의 최신 버전에서 소개 된 새로운 기능 일 것입니다.

    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        protected void configure(final HttpSecurity httpSecurity) throws Exception {
        httpSecurity.
        formLogin().loginPage("/signIn").permitAll().
            and().
                authorizeRequests().
                antMatchers(managementContextPath + "/**").permitAll().
                anyRequest().authenticated().withObjectPostProcessor(objectPostProcessor).
            and().
                csrf().disable().
                contentTypeOptions().
                xssProtection().
                cacheControl().
                httpStrictTransportSecurity().
            and().
                requestCache().requestCache(new RedisRequestCache(savedRequestRedisTemplate())).
            and().
                sessionManagement().sessionAuthenticationStrategy(sessionAuthenticationStrategy).
            and().
                exceptionHandling().authenticationEntryPoint(new AuthenticationProcessingFilterEntryPoint("/signIn"));
        }
    }
    
    public class AuthenticationProcessingFilterEntryPoint extends LoginUrlAuthenticationEntryPoint {
        public AuthenticationProcessingFilterEntryPoint(String loginFormUrl) {
            super(loginFormUrl);
        }
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
            RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
            redirectStrategy.sendRedirect(request, response, getLoginFormUrl() + "?" + request.getQueryString());
        }
    }
    

    Rizier123, 당신의 조언에 다시 한번 감사드립니다.

  4. ==============================

    4.안녕 카발 -

    안녕 카발 -

    나는 매우 비슷한 요구 사항을 가지고 있으며, 당신과 zagyi와 사자의 게시물을 따랐지만 여전히 / login 페이지의 원래 요청 매개 변수를 잃어버린 것 같습니다.

    여기에 내가 가지고있는 것이있다.

    public class AuthenticationProcessingFilterEntryPoint extends LoginUrlAuthenticationEntryPoint {
        @Override
        protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
            String url = super.determineUrlToUseForThisRequest(request, response, exception);
            return url + "?" + request.getQueryString();
        }
    }
    
    
    
    protected void configure(final HttpSecurity httpSecurity) throws Exception {
        httpSecurity.
        formLogin().loginPage("/signIn").permitAll().
            and().
                authorizeRequests().
                antMatchers(managementContextPath + "/**").permitAll().
                anyRequest().authenticated().withObjectPostProcessor(objectPostProcessor).
            and().
                csrf().disable().
                contentTypeOptions().
                xssProtection().
                cacheControl().
                httpStrictTransportSecurity().
            and().
                requestCache().requestCache(new RedisRequestCache(savedRequestRedisTemplate())).
            and().
                sessionManagement().sessionAuthenticationStrategy(sessionAuthenticationStrategy).
            and().
                addFilter(new ExceptionTranslationFilter(new AuthenticationProcessingFilterEntryPoint()));
    }
    

    AuthenticationProcessingFilterEntryPoint가 배포되었지만 거기에 중단 점이 있지는 않습니다.

    문서를 기반으로, AuthenticationException 또는 AccessDeniedException이있는 경우에만 시작됩니다. 위의 구성에서 스프링이 내부적으로 이러한 예외가 발생하면 확실하지 않습니다.

    또한 인증 성공 여부와 관계없이 방문 페이지에서 검색어 매개 변수를 보존하고 싶습니다.

    성공과 실패 처리기를 추가했지만 아무도 작동하지 않습니다.

    protected void configure(final HttpSecurity httpSecurity) throws Exception {
        httpSecurity.
        formLogin().
            successHandler(new PropogateQueryStringAuthenticationSuccessHandlerImpl()).
            failureHandler(new SimpleUrlAuthenticationFailureHandlerImpl(new QueryStringPropagateRedirectStrategy())).
        and().
            authorizeRequests().
            antMatchers(managementContextPath + "/**").permitAll().
            anyRequest().authenticated().withObjectPostProcessor(objectPostProcessor).
        and().
            csrf().disable().
            contentTypeOptions().
            xssProtection().
            cacheControl().
            httpStrictTransportSecurity().
        and().
            requestCache().requestCache(new RedisRequestCache(savedRequestRedisTemplate())).
         and().
            sessionManagement().sessionAuthenticationStrategy(sessionAuthenticationStrategy);
    }
    

    나는 봄 보안 3.2.4.RELEASE를 봄 부팅 1.1.6.RELEASE (이는 봄 프레임 워크 4.0.7을 사용한다.) 릴리스를 사용하고있다.

    감사, 산

  5. from https://stackoverflow.com/questions/14282569/spring-security-retaining-url-parameters-on-redirect-to-login by cc-by-sa and MIT license