bma*_*ham 3 java rest spring spring-mvc spring-security
我不确定我是否足够了解该主题以正确提出问题。
无论如何,登录后,我想重定向到在 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" />
Run Code Online (Sandbox Code Playgroud)
我已经尝试过搞砸了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;
}
Run Code Online (Sandbox Code Playgroud)
创建自定义实现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());
}
}
Run Code Online (Sandbox Code Playgroud)
创建此处理程序的 bean:
<bean id="successLoginHandler" class="com.myapp.security.RedirectLoginSuccessHandler" />
Run Code Online (Sandbox Code Playgroud)
在安全配置中注册这个 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"
/>
Run Code Online (Sandbox Code Playgroud)
现在,您将在登录后被重定向。
注意:如果您想重定向到控制器方法,只需重定向到映射 url。例如,对于重定向到"/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());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5696 次 |
| 最近记录: |