Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get authentication infomation when using spring security?

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?

like image 364
Tom Avatar asked Apr 13 '26 06:04

Tom


2 Answers

SecurityContextHolder.getContext().getAuthentication().isAuthenticated() will return true almost always. use this

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) && authentication.isAuthenticated();
like image 154
Noushad Avatar answered Apr 16 '26 00:04

Noushad


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.

like image 34
Raghuram Avatar answered Apr 15 '26 23:04

Raghuram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!