开发者

Retrieve Spring Security's Authentication, even on public pages with filter="none"

Let's say I have a simple page called faq.html. I want this page to be publicly accessible, so I apply the usual Spring Security configuration:

<sec:intercept-url pattern="/faq.html" filters="none" />

Let's also say that if the user reaches this page after authenticating, I want to print "Hi Firstname Lastname" on the page. For pages that require authentication, I simply put the result of the following into my ModelMap, and then the names are accessible in my view later:

SecurityContextHolder.getContext().getAuthentication().getPrincipal()

This doesn't work for faq.html, presumably because when you specify filters="none", then the call to getPrincipal() returns null. (This behavior makes sens开发者_运维问答e since the configuration causes no filters to be applied.) So, instead it seems that I have to do a bunch of the Spring Security stuff manually:

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;
}

Is there a better way to do this? For example, it seems like Spring should provide some facility for hooking their API calls in via the original <sec:intercept-url /> config.


That's the reason not to use filters = "none" for public pages.

Use access = "permitAll" instead (or access = "IS_AUTHENTICATED_ANONYMOUSLY, IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED" if you don't have use-expressions = "true").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜