在Spring Security表单登录页面中获取原始请求URL

时间:2011-01-13 19:28:09

标签: spring-security

我在spring安全配置文件(http://www.springframework.org/schema/security/spring-security-2.0.1.xsd)中声明了以下内容:

<form-login login-page="/login.html" />

如果用户没有正确的身份验证凭据,Spring Security会将用户重定向到该页面。如何获取用户试图访问的页面的网址?

3 个答案:

答案 0 :(得分:10)

原始请求由SavedRequest对象表示,可以作为名为SPRING_SECURITY_SAVED_REQUEST_KEY的会话属性进行访问。

答案 1 :(得分:1)

在Spring Security 4中

原始请求由 DefaultSavedRequest 对象表示,该对象可以作为名为 SPRING_SECURITY_SAVED_REQUEST 的会话属性进行访问。

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(HttpSession session) {
    DefaultSavedRequest savedRequest = (DefaultSavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
}

答案 2 :(得分:1)

在我的情况下,我做了类似的事情,它对我有用。

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

}