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 privilege Control through AOP and Custom Annotation in SpringBoot

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

Share

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

This article is about how SpringBoot implements access control through AOP and custom annotations. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Train of thought

Custom permission annotations add annotations to the interfaces that need to be verified, and set specific permission values. When a user logs in with the permissions required by the corresponding interface in the database permission table, the user logs in to get all the permissions of the current user in the Redis cache to define AOP, set the pointcut point to the custom permission AOP to get the permission value of the interface annotation, and verify whether the user exists this permission, if there is no such permission in the Redis. Gets the list of user permissions from the database, and then verifies

Introducing AOP into pom file

Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-aop

Custom Annotation VisitPermission

@ Target (ElementType.METHOD) @ Retention (RetentionPolicy.RUNTIME) public @ interface VisitPermission {/ * used to configure the permission value of a specific interface * add the corresponding record in the database * when the user logs in, put all the permission list of the user in the redis * when the user accesses the interface, match the value of the corresponding interface with that in the redis to see if there is access * when the user logs out Clear the corresponding permission cache * / String value () default "" in redis }

Add the annotation @ VisitPermission (value) to the interface where permissions need to be set

@ RestController@RequestMapping ("/ permission") public class PermissionController {/ * configure permission notes @ VisitPermission ("permission-test") * only users with this permission can access it, otherwise it prompts illegal operation * / @ VisitPermission ("permission-test") @ GetMapping ("/ test") public String test () {System.out.println ("= step 3: doing ="); return "success";}}

Define permission AOP

Set the pointcut to @ annotation (VisitPermission) to get the token in the request, verify whether the token expires or legally obtain the permission values in the comments, and verify whether the current user has access rights MongoDB records access logs (IP, parameters, interfaces, time-consuming, etc.)

@ Aspect@Componentpublic class PermissionAspect {/ * pointcut * pointcut is the execution (public * org.ylc.note.aop.controller..* (..)) under the package path: * the method of public returned by any class under the org.ylc.note.aop.Controller package *

* the entry point is annotated: @ annotation (VisitPermission) * method with VisitPermission annotations * / @ Pointcut ("@ annotation (org.ylc.note.aop.annotation.VisitPermission)") private void permission () {} / * execute * / @ Before ("permission ()") public void doBefore () {System.out.println ("= step 2: before =") before the target method call } / * execute * / @ After ("permission ()") public void doAfter () {System.out.println ("= step 4: after =") after the target method call;} / * * surround * encapsulates the target method * specific verification business data * / @ Around ("permission ()") public Object doAround (ProceedingJoinPoint proceedingJoinPoint) throws Throwable {System.out.println ("= step 1: around =") Long startTime = System.currentTimeMillis (); / * * get the token * parsing token in the current http request: * 1, whether token exists * 2, whether token format is correct * 3, whether token has expired (parsing information or whether it exists in redis) * * / ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes (); HttpServletRequest request = attributes.getRequest (); String token = request.getHeader ("token") If (StringUtils.isEmpty (token)) {throw new RuntimeException (illegal request, invalid token) } / / verify the business logic of token / /... / * get the annotated value and verify the permissions: * whether there is a corresponding permission in redis * if there is no permission in redis, get the permission from the database * No data in the air, throw an exception, illegal request, no permission * * / Method method = ((MethodSignature) proceedingJoinPoint.getSignature ()) .getMethod (); VisitPermission visitPermission = method.getAnnotation (VisitPermission.class) String value = visitPermission.value (); / / Business logic for verifying permissions / / List permissions = redis.get (permission) / / db.getPermission / / permissions.contains (value) / /. System.out.println (value); / / execute specific method Object result = proceedingJoinPoint.proceed (); long endTime = System.currentTimeMillis (); / * * record relevant execution results * can be stored in MongoDB later for data analysis * * / / print request url System.out.println ("URL:" + request.getRequestURL (). ToString ()); / / print Http method System.out.println ("HTTP Method:" + request.getMethod ()) / / print the full path of calling controller and execute method System.out.println ("controller:" + proceedingJoinPoint.getSignature (). GetDeclaringTypeName ()); / / call method System.out.println ("Method:" + proceedingJoinPoint.getSignature (). GetName ()); / / execute time-consuming System.out.println ("cost-time:" + (endTime-startTime) + "ms"); return result;}}

Unit testing

Package org.ylc.note.aop;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.http.MediaType;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.MvcResult;import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import org.springframework.test.web.servlet.setup.MockMvcBuilders Import org.ylc.note.aop.controller.PermissionController;@SpringBootTestclass AopApplicationTests {@ Autowired private PermissionController permissionController; private MockMvc mvc; @ BeforeEach void setupMockMvc () {mvc = MockMvcBuilders.standaloneSetup (permissionController). Build ();} @ Test void apiTest () throws Exception {MvcResult result = mvc.perform (MockMvcRequestBuilders.get ("/ permission/test") .accept (MediaType.APPLICATION_JSON) .header ("token", "9527")) .andReturn () System.out.println ("api test result:" + result.getResponse (). GetContentAsString ();}}

Thank you for reading! This is the end of this article on "how SpringBoot achieves access control through AOP and custom annotations". 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