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

Alb*_*ert 9 spring-security spring-boot

我使用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>
Run Code Online (Sandbox Code Playgroud)

我试过更改上面的th:action标签,但我无法随身携带它.

MvcConfig方法如下:

public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("login");
    registry.addViewController("/").setViewName("login");
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*oie 34

成功登录后定义重定向需要应用于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);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您需要定义一个proprer端点来为/success.htmlURL 提供内容.默认情况下可用的静态资源可src/main/resources/public/用于测试目的.我个人宁愿定义一个由Spring MVC Controller提供服务的安全URL,该服务器提供Thymeleaf的内容.您不希望任何匿名用户能够访问成功页面.Thymeleaf是一些在呈现HTML内容时与Spring Security交互的有用功能.

问候,丹尼尔