我正在使用Spring Security,并想知道如果该页面包含#
(哈希)符号,如何在成功登录源页面后实现重定向。
现在我使用always-use-default-target="false"
,它适用于以下网址:/path/to/page/
。
但当网址变为#/path/to/page
时,它不会进行任何重定向。
有没有办法解决它?
答案 0 :(得分:13)
这是我最后使用的解决方案:
$(document).ready(function(){
$('#auth-form').submit(function() {
var el = $(this);
var hash = window.location.hash;
if (hash) el.prop('action', el.prop('action') + '#' + unescape(hash.substring(1)));
return true;
});
});
此代码段将哈希值添加到授权表单的操作属性中,然后Spring会将您重定向到种类的网址:#/path/to/page
,没有任何问题。
答案 1 :(得分:3)
也许这是一个老问题,但在我最近对这个主题的研究中,我发现问题很常见并且仍然存在(特别是在具有后端安全性的现代AngularJS前端应用程序的情况下)。我想与您分享我的解决方案。
在登录页面上,例如/login.html,将以下代码放在</body>
标记之前:
<script type="text/javascript">
var hash = window.location.hash;
document.cookie="hashPart=" + window.btoa(hash);
</script>
注意(1):btoa()函数在IE&gt; = 10(http://www.w3schools.com/jsref/met_win_btoa.asp)下工作,对于旧浏览器使用jQuery等效。
注意(2):URL的#部分加密是必要的,因为它可能包含特殊字符,不允许存储在cookie值字符串中。
从服务器端,您必须修改实现onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
接口的类的AuthenticationSuccessHandler
方法。
就我而言,我只是扩展SavedRequestAwareAuthenticationSuccessHandler
类并使用其原始代码覆盖onAuthenticationSuccess
方法。然后,我从请求中获取 hashPart cookie值,对其进行解码并添加到已解析的重定向URL。我的代码片段如下:
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws ServletException, IOException {
// ... copy/paste original implementation here, until ...
// Use the DefaultSavedRequest URL
String targetUrl = savedRequest.getRedirectUrl();
for (Cookie cookie : req.getCookies()) {
if (cookie.getName().equals("hashPart")) {
targetUrl += new String(Base64Utils.decodeFromString(cookie.getValue()));
cookie.setMaxAge(0); // clear cookie as no longer needed
response.addCookie(cookie);
break;
}
}
getRedirectStrategy().sendRedirect(request, response, targetUrl);
}
最后,只需将成功处理程序类注入Spring Security配置,如:https://stackoverflow.com/a/21100458/3076403
中所述。我期待您对此问题的评论或其他解决方案。