![](/img/trans.png)
[英]In Spring security 2.0.2 How to redirect to a requested url after login
[英]Spring Security: How to redirect to a REST url after login
我不確定我是否能夠很好地了解主題,以正確地提出問題。
無論如何,登錄后,我想重定向到url路徑中的用戶名的url。 我怎么能這樣做?
例如,某人使用用戶名“bmarkham”登錄。 我想在登錄www.website.com/bmarkham后重定向
這是我的spring-security.xml
<form-login login-page="/login" default-target-url="/welcome/"
authentication-failure-url="/login?error" username-parameter="username"
password-parameter="password" login-processing-url="/auth/login_check" />
我已經嘗試過使用default-target-url
而沒有真正起作用。
這是我的控制器
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password");
}
model.addObject("msg", "This is a message and stuff");
return model;
}
@RequestMapping(value = { "/welcome/{userName}", "/welcome" }, method = RequestMethod.GET, produces = "application/json")
public User welcome(@PathVariable String userName) {
User user = new User();
user.setEmail(userName + "@something.com");
user.setUsername(userName);
return user;
}
創建AuthenticationSuccessHandler
自定義實現:
package com.myapp.security;
public class RedirectLoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Authentication authentication) throws IOException, ServletException {
RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse,
"www.website.com/"+authentication.getName());
}
}
創建此處理程序的bean:
<bean id="successLoginHandler" class="com.myapp.security.RedirectLoginSuccessHandler" />
在安全配置中注冊此bean:
<form-login login-page="/login" default-target-url="/welcome/"
authentication-failure-url="/login?error" username-parameter="username"
password-parameter="password" login-processing-url="/auth/login_check"
authentication-success-handler-ref="successLoginHandler"
/>
現在,您將在登錄后重定向。
注意:如果您想重定向到控制器方法,只需重定向到映射網址即可。 例如,對於重定向到"/welcome/{userName}"
,處理程序中的代碼將如下所示:
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Authentication authentication) throws IOException, ServletException {
RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse,
"/welcome/"+authentication.getName());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.