programing

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

bestprogram 2023. 8. 15. 11:17

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

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

로그인 페이지에 설정된 추가 필드에 액세스하는 방법은 무엇입니까?

여러 가지 방법이 있지만 공식적인 방법은 사용자 정의를 사용하는 것입니다.AuthenticationDetails그리고.AuthenticationDetailsSource각각 Spring's 와 subclassing.사용자 정의에 추가 필드 추가WebAuthenticationDetails그리고 그 관습을 가지고 있습니다.WebAuthenticationDetailsSource요청에서 데이터를 가져와 필드를 채웁니다.

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

3.0에서는 다음을 사용해야 합니다.BeanPostProcessor봄 보안 FAQ에는 BeanPostProcessor를 사용하여 사용자 지정 웹 인증 세부 정보를 구성하는 방법에 대한 예가 나와 있습니다.출처.

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

@Vacuum의 코멘트를 자세히 설명합니다.

간단한 방법이 있습니다(테스트되지 않았지만 이 방법이 효과가 있을 것으로 생각합니다).

  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); 
    } 
}
  1. 당신의UserDetailsService구현, 구현 수정:
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException;

1) 단계의 필터가 사용할 수 있도록 하는 세션 변수를 가져옵니다.

  1. 당신의<http />보안 설정, 사용자 지정 필터로 기본 필터 재정의
<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

sourceelica는 다음을 사용하여 언급되었습니다.AuthenticationDetailsSource그리고 관습AuthenticationDetails여기 예가 있습니다.

더하다authentication-details-source-ref빈 ID의 속성customWebAuthenticationDetailsSource로.form-login:

<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 */ }
}

사용자 지정을 사용하는 경우 더 쉬운 방법이 있습니다.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);
    }
}

@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)
                ...
    }
}

Java 구성을 사용하는 스프링 보안 3.0 이상의 경우 다음과 같은 간단한 단계가 잘 작동합니다.

  • 사용자 이름 및 암호 앞에 의 필터 추가구성의 HttpSecurity 개체에 AuthenticationFilter가 있습니다.

    http.addFilterBefore(new YourFilter(), UsernamePasswordAuthenticationFilter.class);
    
  • 세션 요청에 필요한 필드를 가져오려면 필터에 이와 같은 줄이 있어야 합니다.

    if(requestPath != null &&requestPath.equals("/login") ) {
            session.setAttribute("yourParam",req.getParameter("yourParam"));
        }
    
  • 나중에 클래스의 세션에서 다음과 같이 매개 변수 값을 가져올 수 있습니다.

    String yourParam =(String)request.getSession().getAttribute("yourParam");
    

간단한 방법:

RequestContextListener 등록

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

그리고 메인 클래스로:

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

그런 다음 사용자 정의 헤더에서 매개 변수를 가져올 수 있습니다.

request.getHeader("OrganizationId")

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") 

언급URL : https://stackoverflow.com/questions/10074308/how-to-pass-an-additional-parameter-with-spring-security-login-page