Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Spring security expressions to control access to system functions

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to use Spring security expressions to control access to system functions. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. SPEL expression permission control

Since spring security 3.0, it has been possible to use spring Expression expressions to control authorization, allowing complex Boolean logic to be used in expressions to control access permissions. The base class of the Spring Security available expression object is SecurityExpressionRoot.

The expression function describes hasRole ([role]) when a user has a specified role, returns true (Spring security is prefixed with ROLE_ by default), removes the prefix reference Remove the ROLE_hasAnyRole ([role1,role2]), returns truehasAuthority ([authority]) when a user has any of the specified roles, and returns truehasAnyAuthority ([auth1]) if he has access to a resource. Auth2]) if you have access to some of the resources, truepermitAll will always return truedenyAll. Falseanonymous will always return truerememberMe when the current user is anonymous. The current user will return the authentication object of trueauthentication's current logged-in user. FullAuthenticated, if the current user is neither anonymous nor rememberMe, will return truehasIpAddress ('192.168.1.0 rememberMe 24') when the IP sent by the request matches true.

Some friends may be a little confused about Authority and Role. Authority can be used as a resource access right, which can be the access right of a button (such as resource ID:biz1) or a certain type of user role (such as resource ID:ADMIN). When Authority is a role resource permission, hasAuthority ('ROLE_ADMIN') has the same effect as hasRole (' ADMIN').

2. The use of SPEL in global configuration

We can implement the relevant configuration methods and global security configuration by inheriting WebSecurityConfigurerAdapter (as mentioned in the previous chapter). Here's how to use SPEL expressions in a global configuration.

2.1.URL security expression

Config.antMatchers ("/ system/*") .access ("hasAuthority ('ADMIN') or hasAuthority (' USER')") .anyRequest () .authenticated ()

Here we define the scope of the application / person/*URL, and only users with ADMIN or USER permissions can access these person resources.

2.2. Reference bean in a security expression

This approach is more suitable for situations with complex permission verification logic, when the default expression method provided by Spring Security does not meet our needs. First, let's define a RbacService for permission verification.

@ Component ("rbacService") @ Slf4jpublic class RbacService {/ / return true indicates that the verification passed public boolean hasPermission (HttpServletRequest request, Authentication authentication) {/ / verification logic code return true;} public boolean checkUserId (Authentication authentication, int id) {/ / verification logic code return true;}}

For the access to the resource corresponding to "/ person/ {id}", call the method checkUserId of rbacService's bean for permission verification, passing the parameters authentication object and id of person. The id is PathVariable and starts with #.

Config.antMatchers ("/ person/ {id}") .access ("@ rbacService.checkUserId (authentication,#id)") .anyRequest () .access ("@ rbacService.hasPermission (request,authentication)")

Third, Method expression security control

If we want to implement method-level security configuration, Spring Security provides four annotations: @ PreAuthorize, @ PreFilter, @ PostAuthorize, and @ PostFilter

3.1. Turn on the configuration of method-level annotations

In the Spring security configuration code, add the EnableGlobalMethodSecurity annotation to enable the method-level security configuration feature.

@ Configuration@EnableGlobalMethodSecurity (prePostEnabled = true) public class MySecurityConfig extends WebSecurityConfigurerAdapter {

3.2 use PreAuthorize annotations

The @ PreAuthorize annotation is suitable for permission verification before entering the method. Only the ADMIN role can access the findAll method.

@ PreAuthorize ("hasRole ('ADMIN')") List findAll ()

3.3Use PostAuthorize annotations

@ PostAuthorize performs permission verification after the method is executed, which is suitable for permission verification based on the returned value. Spring EL provides that the returned object can get the returned object returnObject in the expression language. The following code returns correctly only if the name of the return value is equal to the name of the authentication object, otherwise an exception is thrown.

@ PostAuthorize ("returnObject.name = = authentication.name") Person findOne (Integer id)

3.4 use PreFilter annotations

PreFilter filters on parameters. The following code indicates that filtering is performed on ids parameters. Only an even number of id can access the delete method.

/ / when multiple objects are marked with filterTarget @ PreFilter (filterTarget= "ids", value= "filterObject%2==0") public void delete (List ids, List usernames) {

3.5 use PostFilter annotations

PostFilter filters the returned results, especially for collection classes that return values, filtering objects in the collection that do not conform to the expression.

PostFilter ("filterObject.name = = authentication.name") List findAll ()

Thank you for reading! This is the end of this article on "how to use Spring secure expressions to control access to system functions". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report