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

标签 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>

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

MvcConfig 方法如下:
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/login").setViewName("login");
    registry.addViewController("/").setViewName("login");
}

最佳答案

成功登录后定义重定向需要应用于 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 提供内容。网址。 src/main/resources/public/ 中默认可用的静态资源会做测试目的的伎俩。我个人宁愿定义一个由 Spring MVC Controller 提供的安全 URL,该 Controller 为 Thymeleaf 提供内容。您不希望任何匿名用户能够访问成功页面。 Thymeleaf 作为在呈现 HTML 内容时与 Spring Security 交互的一些有用功能。

问候,
丹尼尔

关于spring-security - 登录成功后如何设置重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36243352/

相关文章:

java - Spring Boot 2 安全基础认证

azure - Azure 应用服务 API 的 Google Cloud Logging 相当于什么?

java - 如何根据应用程序属性制作 Spring Boot 2 执行器路径?

spring - Spring Security:REST API需要哪个过滤器

数据库中没有用户/角色的 Grails spring-security-ldap

java - 从 http 链接映射 http 参数

java - Spring Data JPA 过滤

java - 何时在 Spring Boot 中使用自定义上下文路径而不是根上下文

java - 如何在 Spring 中将 jpa 属性加载到数据源?

java - 为什么 JDBC 身份验证在 Spring Boot 和 React 中因 CORS 失败?