假设我有一个名为faq.html的简单页面。我希望此页面可公开访问,因此我应用通常的Spring Security配置:
<sec:intercept-url pattern="/faq.html" filters="none" />
我们还要说,如果用户在进行身份验证后到达此页面,我想在页面上打印“Hi Firstname Lastname”。对于需要身份验证的网页,我只需将the result of the following放入ModelMap
,然后在我的视图中可以访问这些名称:
SecurityContextHolder.getContext().getAuthentication().getPrincipal()
这对faq.html
不起作用,可能是因为当您指定filters="none"
时,对getPrincipal()
的调用将返回null。 (这种行为是有道理的,因为配置不会导致应用过滤器。)所以,似乎我必须手动执行一堆Spring Security:
public static Authentication authenticate(HttpServletRequest request,
HttpServletResponse response, SecurityContextRepository repo,
RememberMeServices rememberMeServices) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// try to load a previous Authentication from the repository
if (auth == null) {
SecurityContext context = repo.loadContext(
new HttpRequestResponseHolder(request, response));
auth = context.getAuthentication();
}
// check for remember-me token
if (auth == null) {
auth = rememberMeServices.autoLogin(request, response);
}
return auth;
}
有更好的方法吗?例如,看起来Spring应该提供一些工具来通过原始的<sec:intercept-url />
配置来挂接他们的API调用。
答案 0 :(得分:11)
这就是不对公共页面使用filters = "none"
的原因。
改为使用access = "permitAll"
(如果您没有access = "IS_AUTHENTICATED_ANONYMOUSLY, IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED"
,则使用use-expressions = "true"
。)