How to get authentication information when using spring security?

In the pages I use the tag: security: allow ifAnyGranted = "ROLE_USER, ROLE_ADMIN" ... It works. But server side: I use SecurityContextHolder.getContext (). GetAuthentication (). IsAuthenticated (), this is always true. When I did not log in, the system accepts anonymousUser as the login user.

How can i avoid this?

+3
source share
2 answers

If it is spring security 2.x, there is AuthorityUtils.userHasAuthority(String authority)one that can be used to explicitly verify the role.

You can iterate through SecurityContextHolder.getContext().getAuthentication().getAuthorities()and make sure that you only allow the operation for the roles you want.

+4

SecurityContextHolder.getContext(). getAuthentication(). isAuthenticated() true .

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
+3

Source: https://habr.com/ru/post/1767726/


All Articles