问题场景
我目前正在开发基于 Spring boot 和相关 Spring 项目(如安全和云)的应用程序的登录页面。我希望我的应用程序的用户为登录页面添加书签,因此需要采取这种行为。当我开始考虑潜在的问题时,我认为应用程序将无法知道在您为页面添加书签后重定向到哪里(因为这可以是多个 url)(因为只有/login 而没有重定向)。通常用户不会,例如,/dashboard 并被重定向到登录,因为不存在身份验证。在用户出示他或她的凭据后,应用程序会重定向用户。但这是唯一可能的原因,因为应用程序在其当前 session 中持有一个 SavedRequest 告诉重定向位置。
我想要实现的目标
基本上我想要实现的是让应用程序在用户在/login url 上设置书签后知道去哪里。这里的理想情况是/login url 包含一个重定向参数。例如。
- 用户访问/dashboard?param=value
- 没有身份验证,应用程序重定向到/login?redirect=/dashboard?param=value
- 用户登录
- 应用程序将用户发送到/dashboard?param=value。
现在,如果用户将在步骤 2 中提供的 url 加入书签,那么在一段时间后单击书签后,将为应用程序提供足够的信息以进行合理的重定向。
如果有人知道更好的方法,我想听听。
到目前为止采取的步骤
到目前为止,我一直在寻找解决方案 another answer on StackOverflow .这似乎是朝着正确方向迈出的一步,但仍然缺少一些所需的功能。
我首先创建了 LoginUrlAuthenticationEntryPoint 类的自定义实现。它覆盖了开始方法,看起来像这样:
public class CustomLoginUrlAuthenticaitonEntryPoint extends LoginUrlAuthenticationEntryPoint
{
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException
{
if (!request.getRequestURI().equals(this.getLoginFormUrl()))
{
RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.sendRedirect(request, response, getLoginFormUrl() + "?redirect=" + request.getRequestURI() + "?" + request.getQueryString());
}
}
}
然后我将这个自定义类添加到 HttpSecurity 作为默认身份验证入口点。
@Configuration
@Order(-20)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.exceptionHandling()
.authenticationEntryPoint(new CustomLoginUrlAuthenticationEntryPoint("/login"));
}
}
最后我实现了一个自定义登录 Controller 来为登录页面提供服务。
@Controller
public class LoginController
{
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(@RequestParam(value = "redirect", required = false) String redirect)
{
ModelAndView model = new ModelAndView();
// Do something with the redirect url;
model.setViewName("login");
return model;
}
但是一旦我实现了这个,重定向似乎就可以正常工作了。 (/dashboard?param=value 已重定向到/login?redirect=/dashboard?param=value)但未显示登录页面。但是当直接访问/login url 时,登录页面确实会显示。
所以我认为我是在正确的位置将自定义查询参数添加到/login url,但我猜实现还不是很完整。有人可以帮我解决问题,或者为我的问题提供更好的解决方案吗?
提前致谢。
最佳答案
警告:使用参数来确定您要重定向到的位置最多可以打开您的应用程序 Open Redirect Vulnerabilities .根据用户输入执行重定向时要非常小心。
ContinueEntryPoint
您的第一步是创建一个 AuthenticationEntryPoint
,它负责在显示登录表单时包含一个带有 URL 的参数,以便在 URL 中继续。在此示例中,我们将使用参数名称 continue。
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.web.util.UriComponentsBuilder;
/**
* @author Rob Winch
*
*/
public class ContinueEntryPoint extends LoginUrlAuthenticationEntryPoint {
public ContinueEntryPoint(String loginFormUrl) {
super(loginFormUrl);
}
@Override
protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) {
String continueParamValue = UrlUtils.buildRequestUrl(request);
String redirect = super.determineUrlToUseForThisRequest(request, response, exception);
return UriComponentsBuilder.fromPath(redirect).queryParam("continue", continueParamValue).toUriString();
}
}
网络安全配置
下一步是包括一个使用 ContinueEntryPoint 的安全配置。例如:
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(new ContinueEntryPoint("/login"))
.and()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
}
}
登录 Controller
最后,如果用户已经通过身份验证,您应该创建一个重定向到参数的 LoginController。例如:
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.NotBlank;
public class RedirectModel {
@Pattern(regexp="^/([^/].*)?$")
@NotBlank
private String continueUrl;
public void setContinue(String continueUrl) {
this.continueUrl = continueUrl;
}
public String getContinue() {
return continueUrl;
}
}
@Controller
public class LoginController {
@RequestMapping("/login")
public String login(Principal principal, @Valid @ModelAttribute RedirectModel model, BindingResult result) {
if (!result.hasErrors() && principal != null) {
// do not redirect for absolute URLs (i.e. https://evil.com)
// do not redirect if we are not authenticated
return "redirect:" + model.getContinue();
}
return "login";
}
}
完整样本
您可以在 github 中的 rwinch/spring-security-sample 找到完整的示例在 so-34087954-continue-on-login 分支中。您可以轻松download如果您不想使用 git,请使用它。
关于java - Spring 安全 : How to add a redirect query parameter to the login url to allow bookmarking of the page?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34087954/