반응형
http://chomman.github.io/blog/java/spring%20security/programming/spring-security-redirect-previous-after-login/
Spring security
를 사용할 때 특정 페이지에서 인증이 필요하면 로그인 페이지로 리다이렉트를 시키면 된다. 그런데 로그인 후 첫 페이지로 가는 것이 아니라 원래 이용하려던 서비스 페이지로 가야하는 기능이 필요하다면 AuthenticationSuccessHandler
인터페이스를 구현하면 된다. 물론 로그인 페이지로 이동하는 시점에 원래 페이지를 기억하도록 해야 한다. 실제 소스로 해보자.
1. Success Handler 구현
public class CustomLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
public CustomLoginSuccessHandler(String defaultTargetUrl) {
setDefaultTargetUrl(defaultTargetUrl);
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session != null) {
String redirectUrl = (String) session.getAttribute("prevPage");
if (redirectUrl != null) {
session.removeAttribute("prevPage");
getRedirectStrategy().sendRedirect(request, response, redirectUrl);
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
2. 인증 페이지로 이동하기 전 URL 기억
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(HttpServletRequest request) {
String referrer = request.getHeader("Referer");
request.getSession().setAttribute("prevPage", referrer);
return "login";
}
3. Security Config 설정
Java Config의 경우
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login")
.successHandler(successHandler())
.permitAll()
...
;
}
.
.
.
@Bean
public AuthenticationSuccessHandler successHandler() {
return new CustomLoginSuccessHandler("/defaultUrl");
}
반응형
'Web > 스프링' 카테고리의 다른 글
Java: Spring프로젝트에 이메일 인증 기능 추가 (0) | 2017.06.15 |
---|---|
[Mybatis] 동적 쿼리 작성 (가변 컬럼) (0) | 2017.06.14 |
스프링 시큐리티 utf-8 충돌나서 한번더 인코딩함. (스프링 시큐리티 적용시 인코딩 필터 동작안할경우) (0) | 2017.05.25 |
Root Application Context와 Servlet Context (0) | 2017.05.11 |
스프링시큐리티 csrf ajax 헤더 첨부 (0) | 2017.04.21 |
댓글