Reputation: 2847
At pages I am using tag: security:authorize ifAnyGranted="ROLE_USER,ROLE_ADMIN" ... It works. But at server side: I use SecurityContextHolder.getContext().getAuthentication().isAuthenticated(),it is always true. When I didn't log in, the system take anonymousUser as the log in user.
How can I avoid this?
Upvotes: 3
Views: 5526
Reputation: 3030
SecurityContextHolder.getContext().getAuthentication().isAuthenticated() will return true almost always. use this
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
Upvotes: 5
Reputation: 52635
If it is spring security 2.x, there is AuthorityUtils.userHasAuthority(String authority)
which you can use to make explicit check for the role.
You could iterate over SecurityContextHolder.getContext().getAuthentication().getAuthorities()
and ensure you permit operation only for the roles that you want.
Upvotes: 4