Get original request url in Spring Security form-login page
I have the following declared in my spring security config开发者_开发问答uration file (http://www.springframework.org/schema/security/spring-security-2.0.1.xsd):
<form-login login-page="/login.html" />
What Spring Security does is redirect the user to that page if they don't have the correct authentication credentials. How can I get the url of the page the user was trying to get to?
Original request is represented by the SavedRequest
object, which can be accessed as a session attribute named SPRING_SECURITY_SAVED_REQUEST_KEY
.
in my case i did something like this and it worked for me.
@Autowired
private LoggedUserListener loggedUserListener;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/find/**","/","/Application/**")
.access("hasRole('ROLE_USER')")
.successHandler(loggedUserListener)
//some other stuff
}
@Component
public class LoggedUserListener implements AuthenticationSuccessHandler{
@Autowired
private UserRepo userRepo;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
HttpSession session = request.getSession();
SavedRequest savedRequest = (SavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
if(savedRequest != null) {
User u = userRepo.findByUsername(authentication.getName());
u.setLastLogin(new Date());
u.setAccountNonLocked(false);
userRepo.save(u);
response.sendRedirect(savedRequest.getRedirectUrl());
}
}
}
In Spring Security 4
The original request is represented by the DefaultSavedRequest object, which can be accessed as a session attribute named SPRING_SECURITY_SAVED_REQUEST.
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(HttpSession session) {
DefaultSavedRequest savedRequest = (DefaultSavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
}
精彩评论