Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get original request url in Spring Security form-login page

I have the following declared in my spring security configuration 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?

like image 982
Abdullah Jibaly Avatar asked Jan 13 '11 19:01

Abdullah Jibaly


2 Answers

Original request is represented by the SavedRequest object, which can be accessed as a session attribute named SPRING_SECURITY_SAVED_REQUEST_KEY.

like image 185
axtavt Avatar answered Oct 20 '22 05:10

axtavt


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());
    }
  }

}
like image 42
sango Avatar answered Oct 20 '22 04:10

sango



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!