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

时间:2016-03-27 02:54:44

标签: 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");
}

3 个答案:

答案 0 :(得分:25)

成功登录后定义重定向需要在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);
    }
}

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

此致 丹尼尔

答案 1 :(得分:0)

您还可以动态定义登录后重定向。事实证明这很简单。

假定您的控制器的条件复杂,需要确保用户正确登录。

通过将“请求”缓存中的值设置为当前请求/响应,然后进行重定向,登录成功后,Spring安全性将转发到缓存的请求。

    RequestCache requestCache = new HttpSessionRequestCache();
    requestCache.saveRequest(request,response);
    return "redirect:/login";

不,这似乎没有任何地方记录在案。我发现它的唯一参考如下:

  

SavedRequests和RequestCache接口   ExceptionTranslationFilter职责的另一个职责是在调用AuthenticationEntryPoint之前保存当前请求。这允许在用户认证之后恢复请求(请参阅Web认证的先前概述)。一个典型的示例是用户使用表单登录,然后通过默认的SavedRequestAwareAuthenticationSuccessHandler重定向到原始URL(请参见下文)。

     

RequestCache封装了存储和检索HttpServletRequest实例所需的功能。默认情况下,使用HttpSessionRequestCache,它将请求存储在HttpSession中。当用户被重定向到原始URL时,RequestCacheFilter的工作实际上是从缓存中还原保存的请求。

答案 2 :(得分:0)

对我有用。登录成功后,Spring安全性将重定向到“ /”,然后,我检查用户是否已通过身份验证,在这种情况下,将其重定向到我的仪表板页面。

@RequestMapping("/")
    public String index(Model model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken))
            return "dashboard";

        // if it is not authenticated, then go to the index...
        // other things ...
        return "index";
    }