Get original request url in Spring Security form-login page

亡梦爱人 提交于 2020-01-01 09:22:23

问题


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?


回答1:


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




回答2:


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



回答3:


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

}


来源:https://stackoverflow.com/questions/4684323/get-original-request-url-in-spring-security-form-login-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!