복붙노트

[SPRING] 스프링 보안에서 커스텀 인증 구현하기

SPRING

스프링 보안에서 커스텀 인증 구현하기

Spring Security에서 내 문제에 관해서 당신의 도움을 요청하고 싶습니다. 사용자가 선택한 옵션에 따라 로그인 자격 증명의 유효성을 검사해야한다는 요구 사항이 있습니다. 옵션 1은 타사 서비스를 통해 로그인 한 사용자의 유효성을 검사합니다. 옵션 2는 데이터베이스 인증 레벨을 사용하는 일반 유효성 검사입니다. 어떻게 구현할 수 있습니까?

해결법

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

    1.AuthenticationProvider는 단일 메서드를 사용하는 인터페이스입니다. 따라서 사용자 정의 구현은 다음과 같을 수 있습니다.

    AuthenticationProvider는 단일 메서드를 사용하는 인터페이스입니다. 따라서 사용자 정의 구현은 다음과 같을 수 있습니다.

    class DelegatingAuthenticationProvider implements AuthenticationProvider {
      @Autowired
      private ThirdPartyAuthenticationService service;
    
      @Autowired
      @Qualifier("anotherAuthenticationProvider")
      private AuthenticationProvider provider;
    
      @Override
      public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        // Get the user selection.
        String selection = (String) authentication.getDetails();
    
        // Take action depending on the selection.
        Authentication result;
        if("ThirdParty".equals(selection)) {
          // Authenticate using "service" and generate a new
          // Authentication "result" appropriately.
        }
        else {
          // Authenticate using "provider" and generate a new
          // Authentication "result" appropriately.
        }
    
        return result;
      }
    }
    

    위의 AuthenticationProvider 구현은 Authentication 객체의 details 속성에서 사용자 선택을 선택합니다. 아마도 사용자 선택은 HttpServletRequest에서 선택되어야하고 AuthenticationProvider가 호출되기 전에 Authentication 객체에 추가되어야합니다. 즉, AuthenticationProvider가 호출되기 전에 Authentication 및 HttpServletRequest 객체에 액세스 할 수있는 다른 구성 요소를 호출해야합니다.

    Authentication 객체는 AbstractAuthenticationProcessingFilter의 구현에 의해 생성됩니다. 이 클래스에는 HttpServletRequest 객체를 받아들이고 Authentication 객체를 반환하는 tryAuthentication이라는 메서드가 있습니다. 따라서 이것이 필요한 것을 구현하기위한 좋은 후보자가 될 것 같습니다. 사용자 이름 - 암호 기반 인증의 경우 구현 클래스는 UsernamePasswordAuthenticationFilter입니다. 이 클래스는 인증 구현 인 UsernamePasswordAuthenticationToken의 새 인스턴스를 반환합니다. 따라서 UsernamePasswordAuthenticationFilter를 확장하는 클래스로 충분해야합니다.

    class ExtendedUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
      @Override
      public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        ...
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, password);
        authentication.setDetails(obtainUserSelection(request));
    
        ...
    
        return authentication;
      }
    }
    

    obtainUserSelection은 요청에서 사용자 선택을 가져 오는 개인 메서드입니다.

    Spring 보안 설정에서 AuthenticationProvider와 필터 구현을 설정하십시오. 정확한 단계는 XML 또는 Java 구성 사용 여부에 따라 달라집니다.

  2. from https://stackoverflow.com/questions/36416324/implementing-custom-authentication-in-spring-security by cc-by-sa and MIT license