Spring Security重定向url和单页散列片段

时间:2016-07-20 14:31:24

标签: spring spring-security vaadin single-page-application vaadin7

有没有办法配置Spring Security以正确理解单页面应用程序中的哈希片段(使用Vaadin 7框架构建)?

成功登录后,我需要将用户重定向到带有哈希片段的正确页面,但Spring Security会破坏原始路径。

2 个答案:

答案 0 :(得分:1)

您可以将哈希部分放入登录表单中,并在成功登录后发回哈希值。

使用登录表单提交带来哈希部分:

<form name='login_form' action="/perform_login" method='POST' onsubmit="getHashPart()">
    <table>
        <tr>
            <td>User:</td>
            <td><input type='text' name='username' value=''></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type='password' name='password'/></td>
        </tr>
        <input type="hidden" name="hashPart" value=""/>
        <tr>
            <td><input name="submit" type="submit" value="submit"/></td>
        </tr>
    </table>
</form>

<script type="text/javascript">
    var getHashPart = function () {
        login_form.hashPart.value = location.hash;
    }
</script>

创建一个MyAuthenticationSuccessHandler:

public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
        throws ServletException, IOException {
        String hashPart = request.getParameter("hashPart");
        if (hashPart == null || hashPart.trim().equals("")) {
            super.onAuthenticationSuccess(request, response, authentication);
        } else {
            this.getRedirectStrategy().sendRedirect(request, response, "/" + hashPart);
        }
    }
}

将您的处理程序放入SecurityConfig:

        http
            ......
            .and()
            .formLogin()
            .loginPage("/login")
            .loginProcessingUrl("/perform_login")
            .successHandler(myAuthenticationSuccessHandler)

答案 1 :(得分:0)

通过以下技巧修复(我使用ThymeLeaf作为模板引擎):

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <title>Login</title>

        <script th:inline="javascript">
            function getLoginAction(form){
                var hash = unescape(self.document.location.hash.substring(1));
                form.action = [[@{/login}]] + '#' + hash;
                return true;
            }
        </script>

    </head>
    <body>
        <h3>Please login</h3> 
        <p th:if="${param.error}">
            Bad Credentials:
        </p>
        <form th:action="@{/login}" method="POST" onsubmit="getLoginAction(this);">
            User Name : <input type="text" name="username"/> <br/><br/>
            Password: <input type="password" name="password"/> <br/><br/>
            <input type='checkbox' name="remember-me"/>Remember Me? <br/><br/>
            <input type="submit" value="Login"/>
        </form>
    </body>
</html>