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 realize micro-service data access control by SpringCloud

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

Share

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

This article will explain in detail how SpringCloud implements micro-service data access control. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

For example:

A group of salesmen followed up on sales orders across the country. They are divided by city, and a salesman follows up orders from three cities. In order to protect that the company's business data cannot be grasped by everyone, each salesman can only see the order data of the city he is responsible for. So from the system, each salesman has the function to access the sales order, and then need to configure the city that each salesman is responsible for, so as to filter the order data.

There are many ways to achieve this function, and if similar requirements are needed in many places in the system, then we can propose it into a general function. Here I introduce a relatively simple solution for reference.

I. overall structure

Data permissions are hung on every Controller that needs data access control in the form of an annotation, which is intrusive because it is related to the specific program logic, and needs to be used with the database.

Second, the implementation process

1. Browsers access Controller with query permission range parameters, such as cities

POST http://127.0.0.1:8000/order/queryaccept: * / * Content-Type: application/jsontoken: 1e2b2298-8274-4599-a26f-a799167cc82f {"cities": ["cq", "cd", "bj"], "userName": "string"}

two。 By annotating the parameters of the scope of authority, and comparing the scope of pre-authorization, write back the parameters of the scope of authority within the scope of authorization.

Cities = ["cq", "cd"]

3. Pass the parameters to the DAO layer, assemble the query conditions in the SQL statement, and realize the data filtering.

Select * from order where city in ('cq','cd') 3. Implement step 1. Annotation implementation

For the complete code of the comments, please refer to the source code for details.

1) create comments

@ Retention (value = RetentionPolicy.RUNTIME) @ Target (value = {ElementType.METHOD}) @ Documentedpublic @ interface ScopeAuth {String token () default "AUTH_TOKEN"; String scope () default ""; String [] scopes () default {};}

This note is that the runtime RetentionPolicy.RUNTIME acts on the method ElementType.METHOD

Token: obtain the identity that identifies the unique user, related to the storage of user data permissions

Scope,scopes: scope of permissions for pre-requested data

2) AOP implementation annotations

Public class ScopeAuthAdvice {@ Around ("@ annotation (scopeAuth)") public Object before (ProceedingJoinPoint thisJoinPoint, ScopeAuth scopeAuth) throws Throwable {/ /... Omit the procedure / / get token String authToken = getToken (args, scopeAuth.token (), methodSignature.getMethod ()); / / write back the range parameters setScope (scopeAuth.scope (), methodSignature, args, authToken); return thisJoinPoint.proceed () } / * set range * / private void setScope (String scope, MethodSignature methodSignature, Object [] args, String authToken) {/ / get request range Set requestScope = getRequestScope (args, scope, methodSignature.getMethod ()); ScopeAuthAdapter adapter = new ScopeAuthAdapter (supplier); / / authorized range Set authorizedScope = adapter.identifyPermissionScope (authToken, requestScope) / / write back the new range setRequestScope (args, scope, authorizedScope, methodSignature.getMethod ());} / * * write back the request range * / private void setRequestScope (Object [] args, String scopeName, Collection scopeValues, Method method) {/ / parse the SPEL expression if (scopeName.indexOf (SPEL_FLAG) = = 0) {ParseSPEL.setMethodValue (scopeName, scopeValues, method, args) }}}

This demo code omits the process. The main function is to get the pre-authorized data range through token, then intersect with the scope of this request, and finally write back the original parameters.

More SPEL expressions are used in the process to calculate the expression results. For more information, please refer to the ParseSPEL file.

3) calculation of the intersection of authority ranges

Public class ScopeAuthAdapter {private final AuthQuerySupplier supplier; public ScopeAuthAdapter (AuthQuerySupplier supplier) {this.supplier = supplier;} / * verify the scope of permission * @ param token * @ param requestScope * @ return * / public Set identifyPermissionScope (String token, Set requestScope) {Set authorizeScope = supplier.queryScope (token); String ALL_SCOPE = "AUTH_ALL" String USER_ALL = "USER_ALL"; if (authorizeScope = = null) {return null;} if (authorizeScope.contains (ALL_SCOPE)) {/ / if it is fully open, return the request range return requestScope;} if (requestScope = = null) {return null } if (requestScope.contains (USER_ALL)) {/ / all authorized scope return authorizeScope;} / / remove different elements requestScope.retainAll (authorizeScope); return requestScope;}}

Here for ease of setting, there are two keyword ranges

AUTH_ALL: preset all ranges, meaning fully open, set values in advance for the database, and pass whatever values are requested.

USER_ALL: request the scope of all authorizations. If this value is passed on the request, the default value of the database will prevail.

4) spring.factories automatically imports class configuration

Org.springframework.boot.autoconfigure.AutoConfigurationImportSelector=\ fun.barryhome.cloud.annotation.ScopeAuthAdvice

If the annotation function exists in a separate project, there may be a problem that the import file cannot be found when using it. The classes that need to be initialized can be loaded automatically through this configuration file.

two。 The annotation uses @ ScopeAuth (scopes = {"# orderDTO.cities"}, token = "# request.getHeader (\" X-User-Name\ ")) @ PostMapping (value =" / query ") public String query (@ RequestBody OrderDTO orderDTO, HttpServletRequest request) {return Arrays.toString (orderDTO.getCities ());}

Add @ ScopeAuth annotations to controller methods that require data permissions

Scopes = {"# orderDTO.cities"}: indicates that the values of the input parameter orderDTO are taken, where the expression must be appended with #

In the actual development process, orderDTO.getCities () needs to be brought into the subsequent logic and assembled in SQL in the DAO layer to achieve the data filtering function.

3. Implement AuthStoreSupplier

The AuthStoreSupplier interface is the storage interface for data permissions. When used with AuthQuerySupplier, it can be implemented according to the actual situation.

This interface is unnecessary and can be stored by database or Redis (recommended). It is generally saved in Redis when logging in.

4. Implement AuthQuerySupplier

AuthQuerySupplier is an API for querying data permissions, which can be queried by storage method. It is recommended to use Redis.

@ Componentpublic class RedisAuthQuerySupplier implements AuthQuerySupplier {@ Autowired private RedisTemplate redisTemplate; / * query scope * / @ Override public Set queryScope (String key) {String AUTH_USER_KEY = "auth:logic:user:%s"; String redisKey = String.format (AUTH_USER_KEY, key); List range = redisTemplate.opsForList () .range (redisKey, 0,-1) If (range! = null) {return new HashSet (range);} else {return null;}}

In the distributed architecture, this implementation can also be proposed to the permission module, using remote invocation to further decouple.

5. Turn on data permissions @ EnableScopeAuth@EnableDiscoveryClient@SpringBootApplicationpublic class OrderApplication {public static void main (String [] args) {SpringApplication.run (OrderApplication.class, args);}} this is the end of the article on "how SpringCloud implements data permission control in microservices". I hope the above content will be helpful to you so that you can learn more knowledge. if you think the article is good, please share it 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