登录成功后如何设置重定向?

新手上路,请多包涵

我正在使用带有 spring-boot-starter-security 依赖项的 spring boot。

我有一个应用程序,如果有正确的凭据,它将成功登录。但是,每当我登录时,我都不会被重定向到任何地方。我该如何配置?

下面是表格:

  <form th:action="@{/login}" method="post">
        <div><label> User Name : <input type="text" name="username"/> </label></div>
        <div><label> Password: <input type="password" name="password"/> </label></div>
        <div><input type="submit" value="Sign In"/></div>
 </form>

我已经尝试更改上面的 th:action 标签,但我无法使用它。

MvcConfig 方法如下:

 public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("login");
    registry.addViewController("/").setViewName("login");
}

原文由 Albert 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 720
1 个回答

成功登录后定义重定向需要在 Spring Security 上应用,而不是在 Spring MVC 上。

th:action 定义了将处理身份验证请求的 Spring Security 端点。它没有定义重定向 URL。开箱即用,Spring Boot Security 将为您提供 /login 端点。默认情况下,Spring Security 将在登录后重定向到您尝试访问的安全资源。如果您希望始终重定向到特定 URL,您可以通过 HttpSecurity 配置对象强制执行该操作。

假设您使用的是最新版本的 Spring Boot,您应该能够使用 JavaConfig。

这是一个简单的例子:

 @Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // the boolean flags force the redirection even though
        // the user requested a specific secured resource.
        http.formLogin().defaultSuccessUrl("/success.html", true);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }
}

请注意,您需要定义一个适当的端点来为 /success.html URL 提供内容。 src/main/resources/public/ 中默认可用的静态资源可以达到测试目的。我个人宁愿定义一个由 Spring MVC 控制器提供的安全 URL,该控制器使用 Thymeleaf 提供内容。您不希望任何匿名用户能够访问成功页面。 Thymeleaf 作为渲染 HTML 内容时与 Spring Security 交互的一些有用功能。

问候,丹尼尔

原文由 Daniel Lavoie 发布,翻译遵循 CC BY-SA 3.0 许可协议