标签:rest spring-security spring java spring-mvc
我不确定我是否对主题足够了解,可以正确地提出问题.
无论如何,登录后,我想使用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"
/>
现在,您将在登录后被重定向.
注意:如果您想重定向到控制器方法,只需重定向到映射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());
}
标签:rest,spring-security,spring,java,spring-mvc 来源: https://codeday.me/bug/20191027/1943022.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。