假设我有一个名为 faq.html 的简单页面。我希望这个页面可以公开访问,所以我应用了通常的 Spring Security 配置:
<sec:intercept-url pattern="/faq.html" filters="none" />
我们还假设如果用户在验证后到达此页面,我想在页面上打印“Hi Firstname Lastname”。对于需要身份验证的页面,我简单地输入 the result of the following进入我的ModelMap
,然后在我的 View 中可以访问这些名称:
SecurityContextHolder.getContext().getAuthentication().getPrincipal()
这不适用于 faq.html
,大概是因为当您指定 filters="none"
, 然后调用 getPrincipal()
返回空值。 (这种行为是有道理的,因为配置不会导致应用任何过滤器。)因此,我似乎必须手动执行大量 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 />
Hook 它们的 API 调用。配置。
最佳答案
这就是不对公共(public)页面使用 filters = "none"
的原因。
使用 access = "permitAll"
(或者 access = "IS_AUTHENTICATED_ANONYMOUSLY, IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED"
如果你没有 use-expressions = "true "
).
关于java - 检索 Spring Security 的身份验证,即使在具有过滤器 ="none"的公共(public)页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7573899/