티스토리 뷰

프링 시큐리티를 이용해서 로그인을 할때, 로그인 성공했을 때와 실패했을 때 로그를 남기는 필요가 생겼다.


시큐리티를 직접 수정한건 처음이어서 흐름을 파악하는데에 시간이 좀 필요했다.


현재 프레임워크는 스프링부트에 자바기반으로 환경설정이 되어있고

이미 구현된 로그인에 성공했을 때, 실패했을 때만 잡으면 되는거였다.



스프링 시큐리티에서 로그인 성공했을 때와 실패했을 때를 잡아주는

public interface AuthenticationSuccessHandler
public interface AuthenticationFailureHandler 

각각의 인터페이스가 존재하며, 인터페이스 내에 아래 메서드를 오버라이딩해서 사용하면 된다.

void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException;
void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException;





@Configuration
public class AuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

//로그인 성공시 필요한 작업 추가


super.onAuthenticationSuccess(request, response, authentication);
}
}

@Configuration 어노테이션으로 설정해주고,

로그인 성공시에는 구현되어있던 클래스를 상속받아서, db에 넣는 작업만 추가해서 결국 request내의 url로 리다이렉트 시킨다.

기본적으로 request, response, 계정관련 정보인 authentication객체를 받아오기 때문에, 필요한 정보를 사용할 수 있다.


@Configuration
public class AuthenticationFailureHandler implements AuthenticationFailureHandler{

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
String username = request.getParameter("username");
        

//로그인 실패시 필요한 작업 추가

response.sendRedirect("/secure/login.do?error=500");
}
}


위의 username은 로그인했던 사용자의 아이디가 필요해서 받아두었다.

로그인실패시에 다른 정보를 가지고있을 필요는 없을 것 같아 바로 리다이렉트 시켰다.




- 시큐리티 설정 추가

@Autowired
public AuthenticationSuccessHandler authenticationSuccessHandler;

@Autowired
public AuthenticationFailureHandler authenticationFailureHandler;

/**
* Login Logout 설정
*/
http.formLogin()
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler)





이번엔 시큐리티에 발만 담궈봤는데

좀 더 자세히 뜯어봐야겠다!

«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30