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?
SecurityContextHolder.getContext().getAuthentication().isAuthenticated() will return true almost always. use this
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With