当前位置: 移动技术网 > IT编程>开发语言>Java > Shiro + JWT + SpringBoot应用示例代码详解

Shiro + JWT + SpringBoot应用示例代码详解

2020年06月23日  | 移动技术网IT编程  | 我要评论
1.shiro的简介apache shiro是一种功能强大且易于使用的java安全框架,它执行身份验证,授权,加密和会话管理,可用于保护 从命令行应用程序,移动应用程序到web和企业应用程序等应用的安

1.shiro的简介

apache shiro是一种功能强大且易于使用的java安全框架,它执行身份验证,授权,加密和会话管理,可用于保护 从命令行应用程序,移动应用程序到web和企业应用程序等应用的安全。

  • authentication 身份认证/登录,验证用户是不是拥有相应的身份;
  • authorization 授权,即权限验证,验证某个已认证的用户是否拥有某个权限;即判断用户是否能做事情,常见的如:验证某个用户是否拥有某个角色。或者细粒度的验证某个用户对某个资源是否具有某个权限;
  • cryptography 安全数据加密,保护数据的安全性,如密码加密存储到数据库,而不是明文存储;
  • session management 会话管理,即用户登录后就是一次会话,在没有退出之前,它的所有信息都在会话中;
  • web integration web系统集成
  • interations 集成其它应用,spring、缓存框架

从应用程序角度的来观察如何使用shiro完成工作:

subject:主体,代表了当前“用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是subject,如网络爬虫,机器人等;即一个抽象概念;所有subject都绑定到securitymanager,与subject的所有交互都会委托给securitymanager;可以把subject认为是一个门面;securitymanager才是实际的执行者;

securitymanager:安全管理器;即所有与安全有关的操作都会与securitymanager交互;且它管理着所有subject;可以看出它是shiro的核心,它负责与后边介绍的其他组件进行交互,如果学习过springmvc,你可以把它看成dispatcherservlet前端控制器;

realm:域,shiro从从realm获取安全数据(如用户、角色、权限),就是说securitymanager要验证用户身份,那么它需要从realm获取相应的用户进行比较以确定用户身份是否合法;也需要从realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把realm看成datasource,即安全数据源。

也就是说对于我们而言,最简单的一个shiro应用:

1、应用代码通过subject来进行认证和授权,而subject又委托给securitymanager;

2、我们需要给shiro的securitymanager注入realm,从而让securitymanager能得到合法的用户及其权限进行判断。

2.shiro + jwt + springboot

1.导入依赖

<dependency>
 <groupid>org.apache.shiro</groupid>
 <artifactid>shiro-spring</artifactid>
 <version>1.4.1</version>
</dependency>
<dependency>
 <groupid>com.auth0</groupid>
 <artifactid>java-jwt</artifactid>
 <version>3.8.2</version>
</dependency>

2.配置jwt

public class jwtutil {
 /**
 * 校验 token是否正确
 *
 * @param token 密钥
 * @param secret 用户的密码
 * @return 是否正确
 */
 public static boolean verify(string token, string username, string secret) {
 try {
  algorithm algorithm = algorithm.hmac256(secret);
  jwtverifier verifier = jwt.require(algorithm)
   .withclaim("username", username)
   .build();
  verifier.verify(token);
  return true;
 } catch (exception e) {
  log.info("token is invalid{}", e.getmessage());
  return false;
 }
 }

 public static string getusername(httpservletrequest request) {
 // 取token
 string token = request.getheader("authorization");
 return getusername(uofferutil.decrypttoken(token));
 }
 /**
 * 从 token中获取用户名
 * @return token中包含的用户名
 */
 public static string getusername(string token) {
 try {
  decodedjwt jwt = jwt.decode(token);
  return jwt.getclaim("username").asstring();
 } catch (jwtdecodeexception e) {
  log.error("error:{}", e.getmessage());
  return null;
 }
 }
 
 public static integer getuserid(httpservletrequest request) {
 // 取token
 string token = request.getheader("authorization");
 return getuserid(uofferutil.decrypttoken(token));
 }
 /**
 * 从 token中获取用户id
 * @return token中包含的id
 */
 public static integer getuserid(string token) {
 try {
  decodedjwt jwt = jwt.decode(token);
  return integer.valueof(jwt.getsubject());
 } catch (jwtdecodeexception e) {
  log.error("error:{}", e.getmessage());
  return null;
 }
 }


 /**
 * 生成 token
 * @param username 用户名
 * @param secret 用户的密码
 * @return token 加密的token
 */
 public static string sign(string username, string secret, integer userid) {
 try {
  map<string, object> map = new hashmap<>();
  map.put("alg", "hs256");
  map.put("typ", "jwt");
  username = stringutils.lowercase(username);
  algorithm algorithm = algorithm.hmac256(secret);
  return jwt.create()
   .withheader(map)
   .withclaim("username", username)
   .withsubject(string.valueof(userid))
   .withissuedat(new date())
//   .withexpiresat(date)
   .sign(algorithm);
 } catch (exception e) {
  log.error("error:{}", e);
  return null;
 }
 }
}

3.配置shiro

4.实现jwttoken

token自己已经包含了用户名等信息。

@data
public class jwttoken implements authenticationtoken {

 private static final long serialversionuid = 1282057025599826155l;

 private string token;

 private string exipreat;

 public jwttoken(string token) {
 this.token = token;
 }

 public jwttoken(string token, string exipreat) {
 this.token = token;
 this.exipreat = exipreat;
 }

 @override
 public object getprincipal() {
 return token;
 }

 @override
 public object getcredentials() {
 return token;
 }

}

5.实现realm

自定义实现 shirorealm,包含认证和授权两大模块。

public class shirorealm extends authorizingrealm {

 @resource
 private redisutil redisutil;

 @autowired
 private isysuserservice userservice;

 @autowired
 private isysroleservice roleservice;

 @autowired
 private isysmenuservice menuservice;

 // 必须重写此方法,不然shiro会报错
 @override
 public boolean supports(authenticationtoken token) {
 return token instanceof jwttoken;
 }

 /**
 * 只有当需要检测用户权限的时候才会调用此方法
 * 授权模块,获取用户角色和权限。
 * @param token token
 * @return authorizationinfo 权限信息
 */
 @override
 protected authorizationinfo dogetauthorizationinfo(principalcollection token) {
 integer userid = jwtutil.getuserid(token.tostring());

 simpleauthorizationinfo simpleauthorizationinfo = new simpleauthorizationinfo();

 // 获取用户角色集
 set<string> roleset = roleservice.selectrolepermissionbyuserid(userid);
 simpleauthorizationinfo.setroles(roleset);

 // 获取用户权限集
 set<string> permissionset = menuservice.finduserpermissionsbyuserid(userid);
 simpleauthorizationinfo.setstringpermissions(permissionset);
 return simpleauthorizationinfo;
 }

 /**
 * 用户认证:编写shiro判断逻辑,进行用户认证
 * @param authenticationtoken 身份认证 token
 * @return authenticationinfo 身份认证信息
 * @throws authenticationexception 认证相关异常
 */
 @override
 protected authenticationinfo dogetauthenticationinfo(authenticationtoken authenticationtoken) throws authenticationexception {
 // 这里的 token是从 jwtfilter 的 executelogin 方法传递过来的,已经经过了解密
 string token = (string) authenticationtoken.getcredentials();
 string encrypttoken = uofferutil.encrypttoken(token); //加密token
 string username = jwtutil.getusername(token); //从token中获取username
 integer userid = jwtutil.getuserid(token); //从token中获取userid

 // 通过redis查看token是否过期
 httpservletrequest request = httpcontextutil.gethttpservletrequest();
 string ip = iputil.getipaddr(request);
 string encrypttokeninredis = redisutil.get(constant.rm_token_cache + encrypttoken + stringpool.underscore + ip);
 if (!token.equalsignorecase(uofferutil.decrypttoken(encrypttokeninredis))) {
  throw new authenticationexception("token已经过期");
 }

 // 如果找不到,说明已经失效
 if (stringutils.isblank(encrypttokeninredis)) {
  throw new authenticationexception("token已经过期");
 }

 if (stringutils.isblank(username)) {
  throw new authenticationexception("token校验不通过");
 }

 // 通过用户id查询用户信息
 sysuser user = userservice.getbyid(userid);

 if (user == null) {
  throw new authenticationexception("用户名或密码错误");
 }
 if (!jwtutil.verify(token, username, user.getpassword())) {
  throw new authenticationexception("token校验不通过");
 }
 return new simpleauthenticationinfo(token, token, "febs_shiro_realm");
 }
}

6.重写filter

所有的请求都会先经过 filter,所以我们继承官方的 basichttpauthenticationfilter ,并且重写鉴权的方法。

代码的执行流程 prehandle -> isaccessallowed -> isloginattempt -> executelogin 。

@slf4j
public class jwtfilter extends basichttpauthenticationfilter {

 private static final string token = "authorization";

 private antpathmatcher pathmatcher = new antpathmatcher();

 /**
 * 对跨域提供支持
 */
 @override
 protected boolean prehandle(servletrequest request, servletresponse response) throws exception {
 httpservletrequest httpservletrequest = (httpservletrequest) request;
 httpservletresponse httpservletresponse = (httpservletresponse) response;
 httpservletresponse.setheader("access-control-allow-origin", httpservletrequest.getheader("origin"));
 httpservletresponse.setheader("access-control-allow-methods", "get,post,options,put,delete");
 httpservletresponse.setheader("access-control-allow-headers", httpservletrequest.getheader("access-control-request-headers"));
 // 跨域时会首先发送一个 option请求,这里我们给 option请求直接返回正常状态
 if (httpservletrequest.getmethod().equals(requestmethod.options.name())) {
  httpservletresponse.setstatus(httpstatus.ok.value());
  return false;
 }
 return super.prehandle(request, response);
 }
 
 @override
 protected boolean isaccessallowed(servletrequest request, servletresponse response, object mappedvalue) throws unauthorizedexception {
 httpservletrequest httpservletrequest = (httpservletrequest) request;
 uofferproperties uofferproperties = springcontextutil.getbean(uofferproperties.class);
 // 获取免认证接口 url 
 // 在application.yml中配置/adminapi/auth/dologin/**,/adminapi/auth/register/**, ...
 string[] anonurl = stringutils.splitbywholeseparatorpreservealltokens(uofferproperties.getshiro().getanonurl(), ",");

 boolean match = false;
 for (string u : anonurl) {
  if (pathmatcher.match(u, httpservletrequest.getrequesturi())) {
  match = true;
  }
 }
 if (match) {
  return true;
 }
 if (isloginattempt(request, response)) {
  return executelogin(request, response);
 }
 return false;
 }

 /**
 * 判断用户是否想要登入。
 * 检测header里面是否包含authorization字段即可
 */
 @override
 protected boolean isloginattempt(servletrequest request, servletresponse response) {
 httpservletrequest req = (httpservletrequest) request;
 string token = req.getheader(token);
 return token != null;
 }

 @override
 protected boolean executelogin(servletrequest request, servletresponse response) {
 httpservletrequest httpservletrequest = (httpservletrequest) request;
 string token = httpservletrequest.getheader(token); //得到token
 jwttoken jwttoken = new jwttoken(uofferutil.decrypttoken(token)); // 解密token
 try {
  // 提交给realm进行登入,如果错误他会抛出异常并被捕获
  getsubject(request, response).login(jwttoken);
  // 如果没有抛出异常则代表登入成功,返回true
  return true;
 } catch (exception e) {
  log.error(e.getmessage());
  return false;
 }
 }

 @override
 protected boolean sendchallenge(servletrequest request, servletresponse response) {
 log.debug("authentication required: sending 401 authentication challenge response.");
 httpservletresponse httpresponse = webutils.tohttp(response);
// httpresponse.setstatus(httpstatus.unauthorized.value());
 httpresponse.setcharacterencoding("utf-8");
 httpresponse.setcontenttype("application/json; charset=utf-8");
 final string message = "未认证,请在前端系统进行认证";
 final integer status = 401;
 try (printwriter out = httpresponse.getwriter()) {
//  string responsejson = "{\"message\":\"" + message + "\"}";
  jsonobject responsejson = new jsonobject();
  responsejson.put("msg", message);
  responsejson.put("status", status);
  out.print(responsejson);
 } catch (ioexception e) {
  log.error("sendchallenge error:", e);
 }
 return false;
 }
}

7. shiroconfig

@configuration
public class shiroconfig {

 @bean
 public shirorealm shirorealm() {
 // 配置 realm
 return new shirorealm();
 }
 
 // 创建defaultwebsecuritymanager
 @bean("securitymanager")
 public securitymanager securitymanager() {
 defaultwebsecuritymanager securitymanager = new defaultwebsecuritymanager();
 // 配置 securitymanager,并注入 shirorealm
 securitymanager.setrealm(shirorealm());
 return securitymanager;
 }
 
 // 创建shirofilterfactorybean
 @bean
 public shirofilterfactorybean shirofilterfactorybean(securitymanager securitymanager) {
 
 shirofilterfactorybean shirofilterfactorybean = new shirofilterfactorybean();
 // 设置 securitymanager
 shirofilterfactorybean.setsecuritymanager(securitymanager);

 	//添加shiro过滤器
		/**
		 * shiro内置过滤器,可以实现权限相关的拦截器
		 * 常用的过滤器:
		 * anon: 无需认证(登录)可以访问
		 * authc: 必须认证才可以访问
		 * user: 如果使用rememberme的功能可以直接访问
		 * perms: 该资源必须得到资源权限才可以访问
		 * role: 该资源必须得到角色权限才可以访问
		 */
 
 // 在 shiro过滤器链上加入 自定义过滤器jwtfilter 并取名为jwt
 linkedhashmap<string, filter> filters = new linkedhashmap<>();
 filters.put("jwt", new jwtfilter());
 shirofilterfactorybean.setfilters(filters);

 // 自定义url规则
 linkedhashmap<string, string> filterchaindefinitionmap = new linkedhashmap<>();
 // 所有请求都要经过 jwt过滤器
 filterchaindefinitionmap.put("/**", "jwt");
 shirofilterfactorybean.setfilterchaindefinitionmap(filterchaindefinitionmap);
 return shirofilterfactorybean;
 }

 /**
 * 下面的代码是添加注解支持
 */
 @bean
 @dependson({"lifecyclebeanpostprocessor"})
 public defaultadvisorautoproxycreator defaultadvisorautoproxycreator() {
 // 设置代理类
 defaultadvisorautoproxycreator creator = new defaultadvisorautoproxycreator();
 creator.setproxytargetclass(true);

 return creator;
 }

 /**
 * 开启aop注解支持
 *
 * @param securitymanager
 * @return
 */
 @bean("authorizationattributesourceadvisor")
 public authorizationattributesourceadvisor authorizationattributesourceadvisor(securitymanager securitymanager) {
 authorizationattributesourceadvisor authorizationattributesourceadvisor = new authorizationattributesourceadvisor();
 authorizationattributesourceadvisor.setsecuritymanager(securitymanager);
 return authorizationattributesourceadvisor;
 }

 
 // shiro生命周期处理器
 @bean
 public lifecyclebeanpostprocessor lifecyclebeanpostprocessor() {
 return new lifecyclebeanpostprocessor();
 }

}

8.登陆

 /**
 * 登录方法
 *
 * @param username 用户名
 * @param password 密码
 * @param code 验证码
 * @param uuid 唯一标识
 * @return 结果
 */
 @postmapping("/dologin")
 public resultvo login(string username, string password, string code, string uuid, httpservletrequest request) throws uofferexception {

 string verifykey = constant.rm_captcha_code_key + uuid;
 string captcha = redisutil.getcacheobject(verifykey);
 redisutil.del(verifykey);

 if (captcha == null) {
  return resultvo.failed(201, "验证码失效");
 }
 if (!code.equalsignorecase(captcha)) {
  return resultvo.failed(201, "验证码错误");
 }

 username = stringutils.lowercase(username);
 password = md5util.encrypt(username, password);

 final string errormessage = "用户名或密码错误";
 sysuser user = usermanager.getuser(username);

 if (user == null) {
  return resultvo.failed(201, errormessage);
 }
 if (!stringutils.equalsignorecase(user.getpassword(), password)) {
  return resultvo.failed(201, errormessage);
 }
 if (constant.status_lock.equals(user.getstatus())) {
  return resultvo.failed(201, "账号已被锁定,请联系管理员!");
 }


 integer userid = user.getuserid();
 string ip = iputil.getipaddr(request);
 string address = addressutil.getcityinfo(ip);
 // 更新用户登录时间
 sysuser sysuser = new sysuser();
 sysuser.setuserid(userid);
 sysuser.setlastlogintime(new date());
 sysuser.setlastloginip(ip);
 userservice.updatebyid(sysuser);


 // 拿到token之后加密
 string sign = jwtutil.sign(username, password, userid);
 string token = uofferutil.encrypttoken(sign);
 localdatetime expiretime = localdatetime.now().plusseconds(properties.getshiro().getjwttimeout());
 string expiretimestr = dateutil.formatfulltime(expiretime);
 jwttoken jwttoken = new jwttoken(token, expiretimestr);

 // 将登录日志存入日志表中
 sysloginlog loginlog = new sysloginlog();
 loginlog.setip(ip);
 loginlog.setaddress(address);
 loginlog.setlogintime(new date());
 loginlog.setusername(username);
 loginlog.setuserid(userid);
 loginlogservice.save(loginlog);

 savetokentoredis(username, jwttoken, ip, address);
 jsonobject data = new jsonobject();
 data.put("authorization", token);

 // 将用户配置及权限存入redis中
 usermanager.loadoneuserrediscache(userid);
 return resultvo.ok(data);
 }

9.@requirespermissions

要求subject中必须含有bus:careertalk:query的权限才能执行方法somemethod()。否则抛出异常authorizationexception。

@requirespermissions("bus:careertalk:query")
public void somemethod() {
}

引用:

总结

到此这篇关于shiro + jwt + springboot应用的文章就介绍到这了,更多相关shiro jwt springboot内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网