Spring登录后如何重定向到请求的页面?
Posted
技术标签:
【中文标题】Spring登录后如何重定向到请求的页面?【英文标题】:How to redirect to requested page after login in Spring? 【发布时间】:2017-07-20 03:21:21 【问题描述】:我试图在登录后使用我的选择选项重定向到特定页面,但我似乎无法正确进入。 我在一个表单上有一个选择选项和一个登录框。选择框应该重定向到指定的页面,但登录后它不会被重定向,即使我请求它。
登录页面
<form class="myform" th:action="@/login" th:object="$user" method="post">
<div th:replace="common/layout :: flash"></div>
<div class="form-group">
<select th:field="*cert" class="form-control input-lg" id="selectEl" >
<option value="" >[Select Program Type]</option>
<option th:each="program : $programs" th:value="$program.values" th:text="$program.name" >Certificate programs</option>
</select>
</div>
<div>
<div class="input-group input-group-lg">
<span class="input-group-addon" id="sizing-addon1">@</span>
<input type="text" class="form-control" placeholder="LoginID" th:field="*username" aria-describedby="sizing-addon1" />
</div>
</div>
<div class="form-group">
<div class="input-group input-group-lg">
<span class="input-group-addon form-wrapper" id="sizing-addon2">@</span>
<input type="password" class="form-control showpassword" placeholder="Pin" th:field="*password" aria-describedby="sizing-addon1" />
<span class="input-group-btn">
<button class="btn btn-default toggle" type="button">Show Pin</button>
</span>
</div>
</div>
<div>
<label>
<input type="checkbox" value="1" id="checkbox" /> <p class="login-caution">I have carefully read all instructions as well as programme requirements in the Admission Brochure and i here my accept any responsibility for any omission(s) or error(s) on my submitted form.</p>
</label>
</div>
<button type="submit" id="btnCheck" class="btn btn-primary btn-lg btn-block">Login</button>
</form>
登录控制器
@RequestMapping(path = "/login", method = RequestMethod.GET)
public String loginForm(Model model, HttpServletRequest request)
model.addAttribute("user", new User());
if (request != null)
DefaultSavedRequest savedRequest=(DefaultSavedRequest) request.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST_KEY");
if (savedRequest != null)
model.addAttribute("redirectUrl", savedRequest.getRedirectUrl());
return savedRequest.getRedirectUrl();
model.addAttribute("programs", Program.values());
try
Object flash = request.getSession().getAttribute("flash");
model.addAttribute("flash", flash);
request.getSession().removeAttribute("flash");
catch (Exception ex)
// "flash" session attribute must not exist...do nothing and proceed normally
return "login";
安全配置
@Override
protected void configure(HttpSecurity http) throws Exception
http
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.successHandler(loginSuccessHandler())
.failureHandler(loginFailureHandler())
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/login").deleteCookies("JSESSIONID").logoutSuccessUrl("/");
public AuthenticationSuccessHandler loginSuccessHandler()
//return (request, response, authentication) -> response.sendRedirect("/");
return (request, response, authentication)->
response.sendRedirect("/");
;
public AuthenticationFailureHandler loginFailureHandler()
return (request, response, exception) ->
request.getSession().setAttribute("flash", new FlashMessage("Incorrect username and/or password. Please try again.", FlashMessage.Status.FAILURE));
//request.removeAttribute("username");
response.sendRedirect("/login");
;
@Bean
public EvaluationContextExtension securityExtension()
return new EvaluationContextExtensionSupport()
@Override
public String getExtensionId()
return "security";
@Override
public Object getRootObject()
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return new SecurityExpressionRoot(authentication) ;
;
【问题讨论】:
【参考方案1】:您似乎总是将用户重定向到根页面,正如您在 AuthenticationSuccessHandler 中定义的那样。
如果您想将用户重定向到特定页面,我建议您在 url 中附加一个“redirectUrl=http://xxxx.com”作为查询字符串参数。在你的 AuthenticationSuccessHandler 中,你可以有类似的东西,
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException
String queryString = request.getQueryString();
if(queryString == null)
response.setStatus(200);
else if(!queryString.contains("redirectUrl="))
response.sendRedirect("/");
else
queryString = URLDecoder.decode(queryString.replace("url=", ""), "utf-8");
response.sendRedirect(queryString);
【讨论】:
嗨@simon 使用 request.getQueryString 还是 request.getParameter() 更好?使用 request.getRequestDispathcer 而不是 request.sendRequest ***.com/questions/20371220/… 是否更好 嗨 @simon 脚本 if(!queryString.contains("redirectUrl=")) response.sendRedirect("/"); 一直在下载登录文件。 @ARTHURDECKER 这里的代码是从我的 CAS 服务器应用程序中复制的,它将用户重定向到不同的域,所以我在这里使用了重定向。就您而言,我认为 request.getRequestDispathcer 会更好。同样对于查询字符串,最初查询字符串会被处理并附加到某个 url,这就是我使用 request.getQueryString() 的原因。如果你只想获取重定向url,你是对的,getParameter应该更好。 这里是否发生了循环重定向?所以它请求登录页面,如果没有,也许尝试直接打开 url 看看是否有效。由于 cookie 与选项卡共享,因此登录也应该在不同的选项卡中工作。【参考方案2】:我设法解决了,这是最终配置
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
// roles admin allow to access /admin/**
// roles user allow to access /user/**
// custom 403 access denied handler
// @formatter:off
@Override
protected void configure(HttpSecurity http) throws Exception
// @formatter:off
// http.formLogin().defaultSuccessUrl("/usersList", true);
// @formatter:off
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login*").permitAll()
.antMatchers("/","/userList")
.permitAll().anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.defaultSuccessUrl("/usersList", true)
.successHandler(new AuthenticationSuccessHandler()
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException
System.out.println("enter here: ");
System.out.println("session: " + request.getSession());
response.sendRedirect("/userList");
request.getSession().setMaxInactiveInterval(60);
System.out.print("session expired");
)
.and()
.logout().permitAll();
http.headers().frameOptions().disable();
这是正确引导我的路线
response.sendRedirect("/userList")
但是有人可以解释为什么这个工作而不是不工作
.defaultSuccessUrl("/usersList", true);
【讨论】:
以上是关于Spring登录后如何重定向到请求的页面?的主要内容,如果未能解决你的问题,请参考以下文章
执行登录保存请求后,Spring Boot Security POST 重定向到登录页面
CAS服务器认证成功后,如何使Spring安全将用户重定向到原始请求的页面
使用 Spring Security 登录后重定向到不同的页面