복붙노트

[SPRING] 스프링 보안 로그인 페이지에서 추가 매개 변수를 전달하는 방법

SPRING

스프링 보안 로그인 페이지에서 추가 매개 변수를 전달하는 방법

봄 보안 로그인 페이지에서 요청 입력 매개 변수로 데이터베이스 이름을 설정하려고합니다. 현재 스프링 보안 SecurityContextHolder.getContext (). getAuthentication ()을 사용하여 검색된 사용자 이름 만 얻고 있습니다.

로그인 페이지에서 설정 한 추가 입력란에 액세스하는 방법은 무엇입니까?

해결법

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

    1.여기에 간단한 방법이있다. (테스트를하지 않았지만 이것이 효과가있을 것이라고 나는 믿는다.)

    여기에 간단한 방법이있다. (테스트를하지 않았지만 이것이 효과가있을 것이라고 나는 믿는다.)

    1) 기본 필터를 확장하고 추가 매개 변수를 가져 와서 세션에 저장하는 새 클래스 ExUsernamePasswordAuthenticationFilter를 만듭니다. 다음과 같이 보일 것입니다 :

        public class ExUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    
        @Override
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
            final String dbValue = request.getParameter("dbParam");
            request.getSession().setAttribute("dbValue", dbValue);
    
            return super.attemptAuthentication(request, response); 
        } 
    }
    

    2) UserDetailsService 구현에서 구현을 다음과 같이 수정하십시오.

    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException;
    

    1 단계의 필터에서 사용할 수있는 세션 변수를 가져옵니다.

    3) 보안 설정에서 사용자 정의 필터로 기본 필터를 덮어 씁니다

    <custom-filter ref="beanForYourCustomFilterFromStep1" position="FORM_LOGIN_FILTER"/>
    

    맞춤 필터에 대한 자세한 내용은 문서의이 부분을 참조하십시오. http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-custom-filters

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

    2.이 작업을 수행하는 방법은 여러 가지가 있지만 공식적인 방법은 Spring의 WebAuthenticationDetails 및 WebAuthenticationDetailsSource를 각각 서브 클래 싱하여 사용자 정의 AuthenticationDetails 및 AuthenticationDetailsSource를 사용하는 것입니다. 추가 필드를 사용자 정의 WebAuthenticationDetails에 추가하고 사용자 정의 WebAuthenticationDetailsSource가 요청에서 데이터를 가져 와서 필드를 채우도록하십시오.

    이 작업을 수행하는 방법은 여러 가지가 있지만 공식적인 방법은 Spring의 WebAuthenticationDetails 및 WebAuthenticationDetailsSource를 각각 서브 클래 싱하여 사용자 정의 AuthenticationDetails 및 AuthenticationDetailsSource를 사용하는 것입니다. 추가 필드를 사용자 정의 WebAuthenticationDetails에 추가하고 사용자 정의 WebAuthenticationDetailsSource가 요청에서 데이터를 가져 와서 필드를 채우도록하십시오.

    Spring Security 3.1에서는 요소의 authentication-details-source-ref 속성을 사용하여 쉽게 구성 할 수 있습니다.

    3.0에서는 BeanPostProcessor를 사용해야합니다. Spring 보안 FAQ에는 BeanPostProcessor를 사용하여 커스텀 WebAuthenticationDetailsSource를 설정하는 예제가있다.

    이 작업이 완료되면 SecurityContextHolder.getContext (). getAuthentication (). getDetails ()를 호출하여 추가 필드에 액세스 할 수 있습니다.

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

    3.sourcedelica는 AuthenticationDetailsSource 및 사용자 정의 AuthenticationDetails를 사용하여 언급했습니다. 다음은 그 예입니다.

    sourcedelica는 AuthenticationDetailsSource 및 사용자 정의 AuthenticationDetails를 사용하여 언급했습니다. 다음은 그 예입니다.

    form-login에 bean id customWebAuthenticationDetailsSource와 함께 authentication-details-source-ref 속성을 추가하십시오.

    <security:http>
        <security:intercept-url pattern="/**" access="..." />
        <security:form-login authentication-details-source-ref="customWebAuthenticationDetailsSource" login-page="..." />
        <security:logout logout-success-url="..." />
    </security:http>
    

    새 클래스 CustomWebAuthenticationDetailsSource를 만듭니다.

    package security;
    
    import org.springframework.security.authentication.AuthenticationDetailsSource;
    import org.springframework.security.web.authentication.WebAuthenticationDetails;
    
    import javax.servlet.http.HttpServletRequest;
    
    public class CustomWebAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> {
        @Override
        public WebAuthenticationDetails buildDetails(HttpServletRequest context) {
            return new CustomWebAuthenticationDetails(context);
        }
    }
    

    및 관련 CustomWebAuthenticationDetails :

    package security;
    
    import org.springframework.security.web.authentication.WebAuthenticationDetails;
    import javax.servlet.http.HttpServletRequest;
    
    public class CustomWebAuthenticationDetails extends WebAuthenticationDetails {
    
        private final String yourParameter;
    
        public CustomWebAuthenticationDetails(HttpServletRequest request) {
            super(request);
            yourParameter = request.getParameter("yourParameter");
        }
    
        public String getyourParameter() {
            return yourParameter;
        }
    
        //TODO override hashCode, equals and toString to include yourParameter
        @Override
        public int hashCode() { /* collapsed */ }
        @Override
        public boolean equals(Object obj) { /* collapsed */ }
        @Override
        public String toString() { /* collapsed */ }
    }
    
  4. ==============================

    4.@ user1322340은 loadUserByUsername 함수에서 세션 속성을 가져 오기위한 상세 정보를 제공하지 않습니다.

    @ user1322340은 loadUserByUsername 함수에서 세션 속성을 가져 오기위한 상세 정보를 제공하지 않습니다.

    1 단계 : @ user1322340에서 제공하는 모든 단계를 따르십시오.

    2 단계: 다음과 같이 web.xml에 하나의 구성을 추가해야합니다.

    <listener>
        <listener-class>
           org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>
    

    3 단계 : 이러한 코드를 사용하여 속성을 가져옵니다.

    RequestContextHolder.getRequestAttributes().getAttribute("yourAttributeName", RequestAttributes.SCOPE_SESSION);
    

    4 단계 : 봄 보안 설정에 필터를 등록하십시오. "authenticationManager를 지정해야합니다."라는 오류가 발생하면 구성에 필터를 등록한 후 확장 필터에 대해 authenticationManagerBean을 설정하고 그런 식으로 설정해야합니다.

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Bean
        public ExUsernamePasswordAuthenticationFilter exUsernamePasswordAuthenticationFilter()
                throws Exception {
            ExUsernamePasswordAuthenticationFilter exUsernamePasswordAuthenticationFilter = new ExUsernamePasswordAuthenticationFilter();
            exUsernamePasswordAuthenticationFilter
                    .setAuthenticationManager(authenticationManagerBean());
            return exUsernamePasswordAuthenticationFilter;
        }
    
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    
            RequestMatcher requestMatcher = new RequestMatcher() {
                @Override
                public boolean matches(HttpServletRequest httpServletRequest) {
                    if (httpServletRequest.getRequestURI().indexOf("/api", 0) >= 0) {
                        return true;
                    }
                    return false;
                }
            };
    
            http
                    .addFilterBefore(exUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                    ...
        }
    }
    
  5. ==============================

    5.자바 설정을 사용하는 스프링 보안 3.0 이상에서는 다음과 같은 간단한 단계가 잘 작동합니다.

    자바 설정을 사용하는 스프링 보안 3.0 이상에서는 다음과 같은 간단한 단계가 잘 작동합니다.

  6. ==============================

    6.사용자 정의 AuthenticationProvider를 사용하는 경우 더 쉬운 방법이 있습니다. 방금 HttpServletRequest를 삽입하고 추가 매개 변수를 검색 할 수 있습니다.

    사용자 정의 AuthenticationProvider를 사용하는 경우 더 쉬운 방법이 있습니다. 방금 HttpServletRequest를 삽입하고 추가 매개 변수를 검색 할 수 있습니다.

    @Component
    public class CustomAuthenticationProvider implements AuthenticationProvider {
    
        @Autowired(required = false)
        private HttpServletRequest request;
    
        @Autowired
        private MyAccountService myAccountService;
    
        @Override
        public Authentication authenticate(Authentication authentication) {
    
            System.out.println("request testing= " + request.getParameter("testing"));
    
            .....
        }
    
        @Override
        public boolean supports(Class<?> authentication) {
            return authentication.equals(UsernamePasswordAuthenticationToken.class);
        }
    }
    
  7. ==============================

    7.간단한 방법 :

    간단한 방법 :

    1) RequestContextListener를 등록한다.

    @Bean
    public RequestContextListener requestContextListener(){
        return new RequestContextListener();
    }
    

    2) 그리고 주 수업 :

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.
    currentRequestAttributes()).
    getRequest();
    

    3) 그런 다음 사용자 지정 헤더에서 매개 변수를 사용할 수 있습니다.

    request.getHeader("OrganizationId")
    
  8. ==============================

    8.2 단계만으로 가장 간단한 방법 :

    2 단계만으로 가장 간단한 방법 :

    1 단계.

    web.xml에 다음 리스너를 추가하십시오.

    <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>
    
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value></param-value>
    </context-param>
    

    2 단계.

    추가 매개 변수를 가져올 클래스 메서드에 다음을 추가합니다.

    RequestAttributes attribs = RequestContextHolder.getRequestAttributes();
    
    if (RequestContextHolder.getRequestAttributes() != null) {
        HttpServletRequest request = ((ServletRequestAttributes) attribs).getRequest();
    }
    

    이제 추가 매개 변수의 이름이 "loginType"이라고 가정하고 다음과 같이 추가 매개 변수를 가져올 수 있습니다.

    request.getParameter("loginType") 
    
  9. from https://stackoverflow.com/questions/10074308/how-to-pass-an-additional-parameter-with-spring-security-login-page by cc-by-sa and MIT license