服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - spring boot 利用注解实现权限验证的实现代码

spring boot 利用注解实现权限验证的实现代码

2021-06-17 11:03兰茗翔 Java教程

这篇文章主要介绍了spring boot 利用注解实现权限验证的实现代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

这里使用 aop 来实现权限验证

引入依赖

?
1
2
3
4
<dependency>
  <groupid>org.springframework.boot</groupid>
  <artifactid>spring-boot-starter-aop</artifactid>
</dependency>

定义注解

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package com.lmxdawn.api.admin.annotation;
 
import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;
 
/**
 * 后台登录授权/权限验证的注解
 */
//此注解只能修饰方法
@target(elementtype.method)
//当前注解如何去保持
@retention(retentionpolicy.runtime)
public @interface authruleannotation {
  string value();
}

拦截实现登录和权限验证

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.lmxdawn.api.admin.aspect;
 
import com.lmxdawn.api.admin.annotation.authruleannotation;
import com.lmxdawn.api.admin.enums.resultenum;
import com.lmxdawn.api.admin.exception.jsonexception;
import com.lmxdawn.api.admin.service.auth.authloginservice;
import com.lmxdawn.api.common.utils.jwtutils;
import io.jsonwebtoken.claims;
import lombok.extern.slf4j.slf4j;
import org.aspectj.lang.joinpoint;
import org.aspectj.lang.annotation.aspect;
import org.aspectj.lang.annotation.before;
import org.aspectj.lang.annotation.pointcut;
import org.aspectj.lang.reflect.methodsignature;
import org.springframework.stereotype.component;
import org.springframework.web.context.request.requestcontextholder;
import org.springframework.web.context.request.servletrequestattributes;
 
import javax.annotation.resource;
import javax.servlet.http.httpservletrequest;
import java.lang.reflect.method;
import java.util.list;
 
/**
 * 登录验证 aop
 */
@aspect
@component
@slf4j
public class authorizeaspect {
 
  @resource
  private authloginservice authloginservice;
 
  @pointcut("@annotation(com.lmxdawn.api.admin.annotation.authruleannotation)")
  public void adminloginverify() {
  }
 
  /**
   * 登录验证
   *
   * @param joinpoint
   */
  @before("adminloginverify()")
  public void doadminauthverify(joinpoint joinpoint) {
 
    servletrequestattributes attributes = (servletrequestattributes) requestcontextholder.getrequestattributes();
    if (attributes == null) {
      throw new jsonexception(resultenum.not_network);
    }
    httpservletrequest request = attributes.getrequest();
 
    string id = request.getheader("x-adminid");
 
    long adminid = long.valueof(id);
 
    string token = request.getheader("x-token");
    if (token == null) {
      throw new jsonexception(resultenum.login_verify_fall);
    }
 
    // 验证 token
    claims claims = jwtutils.parse(token);
    if (claims == null) {
      throw new jsonexception(resultenum.login_verify_fall);
    }
    long jwtadminid = long.valueof(claims.get("admin_id").tostring());
    if (adminid.compareto(jwtadminid) != 0) {
      throw new jsonexception(resultenum.login_verify_fall);
    }
 
    // 判断是否进行权限验证
    methodsignature signature = (methodsignature) joinpoint.getsignature();
    //从切面中获取当前方法
    method method = signature.getmethod();
    //得到了方,提取出他的注解
    authruleannotation action = method.getannotation(authruleannotation.class);
    // 进行权限验证
    authruleverify(action.value(), adminid);
  }
 
  /**
   * 权限验证
   *
   * @param authrule
   */
  private void authruleverify(string authrule, long adminid) {
 
    if (authrule != null && authrule.length() > 0) {
 
      list<string> authrules = authloginservice.listrulebyadminid(adminid);
      // admin 为最高权限
      for (string item : authrules) {
        if (item.equals("admin") || item.equals(authrule)) {
          return;
        }
      }
      throw new jsonexception(resultenum.auth_failed);
    }
 
  }
 
}

controller 中使用

使用 authruleannotation 注解, value 值就是在数据库里面定义的 权限规则名称

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * 获取管理员列表
 */
@authruleannotation("admin/auth/admin/index")
@getmapping("/admin/auth/admin/index")
public resultvo index(@valid authadminqueryform authadminqueryform,
           bindingresult bindingresult) {
 
  if (bindingresult.haserrors()) {
    return resultvoutils.error(resultenum.param_verify_fall, bindingresult.getfielderror().getdefaultmessage());
  }
 
  if (authadminqueryform.getroleid() != null) {
    list<authroleadmin> authroleadmins = authroleadminservice.listbyroleid(authadminqueryform.getroleid());
    list<long> ids = new arraylist<>();
    if (authroleadmins != null && !authroleadmins.isempty()) {
      ids = authroleadmins.stream().map(authroleadmin::getadminid).collect(collectors.tolist());
    }
    authadminqueryform.setids(ids);
  }
  list<authadmin> authadminlist = authadminservice.listadminpage(authadminqueryform);
 
  // 查询所有的权限
  list<long> adminids = authadminlist.stream().map(authadmin::getid).collect(collectors.tolist());
  list<authroleadmin> authroleadminlist = authroleadminservice.listbyadminidin(adminids);
 
  // 视图列表
  list<authadminvo> authadminvolist = authadminlist.stream().map(item -> {
    authadminvo authadminvo = new authadminvo();
    beanutils.copyproperties(item, authadminvo);
    list<long> roles = authroleadminlist.stream()
        .filter(authroleadmin -> authadminvo.getid().equals(authroleadmin.getadminid()))
        .map(authroleadmin::getroleid)
        .collect(collectors.tolist());
    authadminvo.setroles(roles);
    return authadminvo;
  }).collect(collectors.tolist());
 
  pageinfo<authadmin> authadminpageinfo = new pageinfo<>(authadminlist);
  pagesimplevo<authadminvo> authadminpagesimplevo = new pagesimplevo<>();
  authadminpagesimplevo.settotal(authadminpageinfo.gettotal());
  authadminpagesimplevo.setlist(authadminvolist);
 
  return resultvoutils.success(authadminpagesimplevo);
 
}

相关地址

github 地址: https://github.com/lmxdawn/vue-admin-java

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://segmentfault.com/a/1190000017131530

延伸 · 阅读

精彩推荐