How to realize data privilege isolation with Springboot+mybatis-plus+ annotations
Today, the editor will share with you the relevant knowledge points about how to use Springboot+mybatis-plus+ annotations to achieve data permission isolation. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.
1. Create comment
When this comment is typed on the class, there is no need to pass parameters, and all query APIs under this class enable data isolation; enable data isolation by default on the method, and disable verification if the parameter is false.
/ * data permission verification notes * @ author xiaohua * @ date 2021-6-23 * / @ Documented@Target ({METHOD, ANNOTATION_TYPE, TYPE}) @ Retention (RUNTIME) public @ interface DataPermission {/ * whether to isolate data permissions * / boolean isPermi () default true;} 2. Concrete realization
@ Component@Intercepts ({@ Signature (type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})}) public class DataPermissionInterceptor implements Interceptor {private static final Logger logger = LoggerFactory.getLogger (DataPermissionInterceptor.class); @ Autowired private TokenService tokenService; / / scanned package path (based on your own project path). Here is the package path @ Value ("${permission.package-path}") private String packagePath in the configuration. Private final static String DEPT_ID = "dept_id"; private final static String USER_ID = "create_user"; private static List classNames; @ Override public Object intercept (Invocation invocation) throws Throwable {try {LoginInfo user = tokenService.getLoginInfo (); if (user = = null) {return invocation.proceed () } List deptIds = (List) Convert.toList (user.getDataScope ()); if (deptIds = = null) {deptIds = new ArrayList () } / / reflection scans the package slowly. Here we do a lazy load if (classNames = = null) {synchronized (LazyInit.class) {if (classNames = = null) {/ / scan all classes containing the specified annotations under the specified package path Set clazz = Class.forName (newId) / / traversal method for (Method method: clazz.getDeclaredMethods ()) {/ / whether the method contains DataPermission comments, and if so, filter the data results if (method.isAnnotationPresent (DataPermission.class) & & newName.equals (method.getName () {DataPermission dataPermission = method.getAnnotation (DataPermission.class) If (dataPermission! = null) {/ / do not verify if (! dataPermission.isPermi ()) {isPermi = false;} else {/ / enable authentication isPermi = true } if (isPermi) {/ / get the original sql statement String sql = statementHandler.getBoundSql () .getSql () Parses and returns the new SQL statement, processing only the query sql if (mappedStatement.getSqlCommandType (). ToString (). Equals ("SELECT")) {/ / String newSql = getNewSql (sql,deptIds,user.getUserId ()); sql = getSql (sql,deptIds,user.getUserId ()) } / / modify sql metaObject.setValue ("delegate.boundSql.sql", sql);} return invocation.proceed ();} catch (Exception e) {logger.error ("data permission isolation exception:", e); return invocation.proceed () }} / * parses the SQL statement and returns a new SQL statement * Note that this method uses JSqlParser to manipulate SQL, and the dependency package Mybatis-plus has been integrated. If you want to use it alone, please import the dependency * * @ param sql original SQL * @ return new SQL * / private String getSql (String sql,List deptIds,Long userId) {try {String condition = "; String permissionSql =" (" If (deptIds.size () > 0) {for (Long deptId: deptIds) {if ("(" .equals (permissionSql)) {permissionSql = permissionSql + deptId;} else {permissionSql = permissionSql + "," + deptId }} permissionSql = permissionSql + ")"; / / modify the original statement condition = DEPT_ID + "in" + permissionSql;} else {condition = USER_ID + "=" + userId } if (StringUtils.isBlank (condition)) {return sql;} Select select = (Select) CCJSqlParserUtil.parse (sql); PlainSelect plainSelect = (PlainSelect) select.getSelectBody (); / / get the where condition of the original SQL final Expression expression = plainSelect.getWhere () / / add new where condition final Expression envCondition = CCJSqlParserUtil.parseCond_Expression (condition); if (expression = = null) {plainSelect.setWhere (envCondition);} else {AndExpression andExpression = new And_Expression (expression, envCondition); plainSelect.setWhere (andExpression);} return plainSelect.toString () } catch (JSQLParserException e) {logger.error ("parsing the original SQL and building a new SQL error:" + e); return sql;}} above is all the content of the article "how to use Springboot+mybatis-plus+ annotations to achieve data permission isolation". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.