복붙노트

[SPRING] 스프링 보안 사용자 정의 필터 (비밀번호 변경)

SPRING

스프링 보안 사용자 정의 필터 (비밀번호 변경)

웹 사이트에 HTTP 요청을 보안하기 위해 스프링 보안을 사용하고 있습니다. 기본 사용법은 페이지에 액세스하려고 할 때 사용자가 로그인 페이지로 리디렉션되도록 페이지를 보호하는 것입니다.

그러나 추가 요구 사항이 있습니다. 필자의 모델에서는 사용자의 암호를 임시로 표시하여 로그인에 성공하면 자동으로 암호를 변경해야합니다. 암호가 변경되면 암호를 원래 액세스하려고 시도했던 페이지로 전달됩니다.

누구나 스프링 보안을이 목적으로 사용 했습니까? 나만의 맞춤 필터를 만들어야합니까?

감사,

앤드류

해결법

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

    1.Spring Security 3.0에서는 커스텀 AuthenticationSuccessHandler를 구현할 수있다.

    Spring Security 3.0에서는 커스텀 AuthenticationSuccessHandler를 구현할 수있다.

    이 핸들러에서는 임시 비밀번호가있는 사용자를 원래 요청한 페이지 대신 비밀번호 변경 페이지로 리디렉션 할 수 있습니다. 비밀번호가 변경되면 기본 핸들러 구현 인 SavedRequestAwareAuthenticationSuccessHandler를 사용하여 원래 요청한 페이지로 사용자를 리디렉션 할 수 있습니다.

    public class MyHandler implements AuthenticationSuccessHandler {
        private AuthenticationSuccessHandler target = new SavedRequestAwareAuthenticationSuccessHandler();
    
        public void onAuthenticationSuccess(HttpServletRequest request,
            HttpServletResponse response, Authentication auth) {
            if (hasTemporaryPassword(auth)) {
                response.sendRedirect("/changePassword");
            } else {
                target.onAuthenticationSuccess(request, response, auth);
            }
        }
    
        public void proceed(HttpServletRequest request, 
            HttpServletResponse response, Authentication auth) {
            target.onAuthenticationSuccess(request, response, auth);
        }
    }
    
    @Controller("/changePassword")
    public class ChangePasswordController {
    
        @Autowired
        private MyHandler handler;
    
        @RequestMapping(method = POST)
        public void changePassword(HttpServletRequest request, 
            HttpServletResponse response,
            @RequestParam(name = "newPassword") String newPassword) {
    
            // handle password change
            ...
    
            // proceed to the secured page
            handler.proceed(request, response, auth);        
        }
    
        // form display method, etc
        ...
    }
    
  2. ==============================

    2.조금 늦었으나 다른 사람들이이 링크를 찾도록 도울 수 있기를 바랍니다. 사용자 정의 UserDetailsService를 사용하는 경우 User 객체의 credentialsNonExpired를 false로 설정할 수 있습니다. 예를 들어 해당 필드가 true로 다시 설정 될 때까지 보안 내용에 대한 액세스를 허용하지 않을 수 있습니다.

    조금 늦었으나 다른 사람들이이 링크를 찾도록 도울 수 있기를 바랍니다. 사용자 정의 UserDetailsService를 사용하는 경우 User 객체의 credentialsNonExpired를 false로 설정할 수 있습니다. 예를 들어 해당 필드가 true로 다시 설정 될 때까지 보안 내용에 대한 액세스를 허용하지 않을 수 있습니다.

    기본적으로 암호 만료일을 설정하면 사용자 모델 (passwordExpired 어쩌면)에 필드를 설정하고 UserDetailsService가 사용자를 가져올 때 UserDetailsService는 해당 값을 사용하여 credentialsNonExpired를 설정합니다.

    그런 다음, 인증 예외 맵핑을 설정하기 위해 applicationContext-security.xml에 일부 구성을 추가하면됩니다. 이렇게하면 만료 된 자격 증명으로 throw 된 예외를 catch하고 사용자에게 암호 페이지를 다시 설정하도록 할 수 있습니다. 유사한 방법을 사용하여 잠긴 계정과 비활성화 된 계정을 추가로 캐치 할 수 있습니다. 설정 예는 다음과 같습니다.

    applicationContext-security.xml

    <beans:bean id="exceptionTranslationFilter" class="org.springframework.security.web.authentication.ExceptionMappingAuthenticationFailureHandler">
        <beans:property name="exceptionMappings">
            <beans:props>           
                <beans:prop key="org.springframework.security.authentication.BadCredentialsException">/login_error</beans:prop>
                <beans:prop key="org.springframework.security.authentication.CredentialsExpiredException">/password_expired</beans:prop>
                <beans:prop key="org.springframework.security.authentication.LockedException">/locked</beans:prop>
                <beans:prop key="org.springframework.secuirty.authentication.DisabledException">/disabled</beans:prop>
            </beans:props>
            </beans:property>
    </beans:bean>
    
    <http use-expressions="true">
        <!-- ADD BLACKLIST/WHITELIST URL MAPPING -->
        <form-login login-page="/login" default-target-url="/" authentication-failure-handler-ref="exceptionTranslationFilter" />
    </http>
    

    그런 다음 해당 콘텐트로 링크를 제공하도록 컨트롤러를 설정했는지 확인하십시오.

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

    3.예, 필터 ForceChangePasswordFilter를 사용하여이 작업을 수행했습니다. 사용자가 직접 URL을 입력하면 비밀번호 변경 양식을 무시할 수 있습니다. 필터를 사용하면 요청이 항상 차단됩니다.

    예, 필터 ForceChangePasswordFilter를 사용하여이 작업을 수행했습니다. 사용자가 직접 URL을 입력하면 비밀번호 변경 양식을 무시할 수 있습니다. 필터를 사용하면 요청이 항상 차단됩니다.

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

    4.매우 유용한 답변 양식 jyore, 정확히 내가 무엇을 찾고 있었는지. UserDetailsService를 구현하는 커스텀 클래스를 사용하고 있다면, applicationContext.xml의 위 빈 정의와 함께 다음과 같이 할 수있다. 하나는 CML 헤더를 기반으로하는 것이므로

    매우 유용한 답변 양식 jyore, 정확히 내가 무엇을 찾고 있었는지. UserDetailsService를 구현하는 커스텀 클래스를 사용하고 있다면, applicationContext.xml의 위 빈 정의와 함께 다음과 같이 할 수있다. 하나는 CML 헤더를 기반으로하는 것이므로

    import ......
    
    @Service("userService")
    public class UserDetailsServiceImpl implements UserDetailsService {
    
    private static Logger logger = LoggerFactory
            .getLogger(UserDetailsServiceImpl.class);
    
    @Autowired
    private UserDao userDao;
    
    @Override
    public UserDetails loadUserByUsername( String username )
        throws UsernameNotFoundException, DataAccessException , CredentialsExpiredException ,BadCredentialsException ,
        LockedException , DisabledException , UsernameNotFoundException
    {
        User user = userDao.getUserByUsername( username );
        System.out.println("User Found");
    
        if( user == null ){
            // System.out.println("User Not Found");
            logger.error( "User Not Found");
            throw new UsernameNotFoundException( username + " is not found." );
        }
    
        if( user.isEnabled() == false ){
        // System.out.println("User not enabled");
        logger.error( "User not enabled");
           throw new DisabledException( "User not enabled" );
       }
    
        if( user.isLocked() == true ){
             //System.out.println("User is Locked");
            logger.error( "User is Locked");
              throw new LockedException( "User is Locked" );
          }
        if( user.isPasswordExpired() == true ){
            // System.out.println("Password Expired");
            logger.error( "Password Expired");
             throw new CredentialsExpiredException( "Password Expired" );
         }  
    
        return user;
      }
    }
    

  5. from https://stackoverflow.com/questions/3335559/spring-security-custom-filter-change-password by cc-by-sa and MIT license