springboot-vue-JWT使用

后端引入依赖:

     <dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>

JWT工具类:

package com.tangzhe.util;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException; /**
* API调用认证工具类,采用RSA加密
*/
public class JWTUtils {
private static RSAPrivateKey priKey;
private static RSAPublicKey pubKey; private static class SingletonHolder {
private static final JWTUtils INSTANCE = new JWTUtils();
} public synchronized static JWTUtils getInstance(String modulus, String privateExponent, String publicExponent) {
if (priKey == null && pubKey == null) {
priKey = RSAUtils.getPrivateKey(modulus, privateExponent);
pubKey = RSAUtils.getPublicKey(modulus, publicExponent);
}
return SingletonHolder.INSTANCE;
} public synchronized static void reload(String modulus, String privateExponent, String publicExponent) {
priKey = RSAUtils.getPrivateKey(modulus, privateExponent);
pubKey = RSAUtils.getPublicKey(modulus, publicExponent);
} public synchronized static JWTUtils getInstance() {
if (priKey == null && pubKey == null) {
priKey = RSAUtils.getPrivateKey(RSAUtils.modulus, RSAUtils.private_exponent);
pubKey = RSAUtils.getPublicKey(RSAUtils.modulus, RSAUtils.public_exponent);
}
return SingletonHolder.INSTANCE;
} /**
* 获取Token
* @param uid 用户ID
* @param exp 失效时间,单位分钟
* @return
*/
public static String getToken(String uid, int exp) {
long endTime = System.currentTimeMillis() + 1000 * exp;
return Jwts.builder().setSubject(uid).setExpiration(new Date(endTime))
.signWith(SignatureAlgorithm.RS512, priKey).compact();
} /**
* 获取Token
* @param uid 用户ID
* @return
*/
public String getToken(String uid) {
long endTime = System.currentTimeMillis() + 1000 * 60 * 1440;
return Jwts.builder().setSubject(uid).setExpiration(new Date(endTime))
.signWith(SignatureAlgorithm.RS512, priKey).compact();
} /**
* 检查Token是否合法
* @param token
* @return JWTResult
*/
public JWTResult checkToken(String token) {
try {
Claims claims = Jwts.parser().setSigningKey(pubKey).parseClaimsJws(token).getBody();
String sub = claims.get("sub", String.class);
return new JWTResult(true, sub, "合法请求", ResponseCode.SUCCESS_CODE.getCode());
} catch (ExpiredJwtException e) {
// 在解析JWT字符串时,如果‘过期时间字段’已经早于当前时间,将会抛出ExpiredJwtException异常,说明本次请求已经失效
return new JWTResult(false, null, "token已过期", ResponseCode.TOKEN_TIMEOUT_CODE.getCode());
} catch (SignatureException e) {
// 在解析JWT字符串时,如果密钥不正确,将会解析失败,抛出SignatureException异常,说明该JWT字符串是伪造的
return new JWTResult(false, null, "非法请求", ResponseCode.NO_AUTH_CODE.getCode());
} catch (Exception e) {
return new JWTResult(false, null, "非法请求", ResponseCode.NO_AUTH_CODE.getCode());
}
} public static class JWTResult {
private boolean status;
private String uid;
private String msg;
private int code; public JWTResult() {
super();
} public JWTResult(boolean status, String uid, String msg, int code) {
super();
this.status = status;
this.uid = uid;
this.msg = msg;
this.code = code;
} public int getCode() {
return code;
} public void setCode(int code) {
this.code = code;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} public boolean isStatus() {
return status;
} public void setStatus(boolean status) {
this.status = status;
} public String getUid() {
return uid;
} public void setUid(String uid) {
this.uid = uid;
}
} }

前端页面文件:

     <!-- 登录 -->
<div>
<p>用户名:<input v-model="username" /></p>
<p>密码:<input v-model="password" /></p>
<button @click="login">登录</button>
</div>
...        
login: function() {
axios.post('http://localhost:8889/user/login', {
username: this.username,
password: this.password,
})
.then(function (response) {
if (response.data.status) {
alert(response.data.token);
} else {
alert("登录失败");
}
})
.catch(function (error) {
console.log(error);
});
}

后端controller:

@PostMapping("/login")
public Object login(@RequestBody LoginInfo loginInfo) {
Map<String, Object> result = new HashMap<>();
String token = userService.login(loginInfo);
if (token == null) {
result.put("status", false);
} else {
result.put("status", true);
result.put("token", token);
}
return result;
}

后端service:

public String login(LoginInfo loginInfo) {
User user = userRepository.findByUsernameAndPassword(loginInfo.getUsername(), loginInfo.getPassword());
if (user == null) {
return null;
}
String token = JWTUtils.getInstance().getToken(user.getId() + "");
return token;
}

测试登录:

登录成功返回token

token本地存储:

存储在前端

               login: function() {
axios.post('http://localhost:8889/user/login', {
username: this.username,
password: this.password,
})
.then(function (response) {
if (response.data.status) {
alert(response.data.token);
// token本地存储
localStorage.setItem("token", response.data.token);
} else {
alert("登录失败");
}
})
.catch(function (error) {
console.log(error);
});
}
// 从html本地存储中拿出token,设置到全局请求头中
axios.defaults.headers.common['Authorization'] = localStorage.getItem("token");
这样每次发送请求就能带上token的请求头了 后端解析请求头获取token,并借助jwt工具类解密出当前登录用户id:
public class LoginInfoUtils {

    /**
* 获取当前登录用户id
*/
public static String getLoginUserId(HttpServletRequest request) {
String authorization = request.getHeader("Authorization");
if (StringUtils.isNotBlank(authorization)) {
JWTUtils.JWTResult result = JWTUtils.getInstance().checkToken(authorization);
if (result.isStatus()) {
return result.getUid();
}
}
return null;
} }

后端控制台输出当前登录用户ID:

@GetMapping("/list")
public List<User> list(HttpServletRequest request) {
// 获取当前登录用户id
System.out.println("当前用户ID: " + LoginInfoUtils.getLoginUserId(request));
return userService.findAll();
}

若还没登录则输出:当前用户ID: null

用户登录则输出:当前用户ID: 6

这样,前端发送请求时,请求头中带有后端登录接口返回的token值,

后端可以从请求头中获取token并通过JWT解密获得当前登录用户id,就可以在后端获取当前登录用户了。

springboot-vue-JWT使用的更多相关文章

  1. SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 后端篇(五): 数据表设计、使用 jwt、redis、sms 工具类完善注册登录逻辑

    (1) 相关博文地址: SpringBoot + Vue + ElementUI 实现后台管理系统模板 -- 前端篇(一):搭建基本环境:https://www.cnblogs.com/l-y-h/p ...

  2. SpringBoot+Vue豆宝社区前后端分离项目手把手实战系列教程01---搭建前端工程

    豆宝社区项目实战教程简介 本项目实战教程配有免费视频教程,配套代码完全开源.手把手从零开始搭建一个目前应用最广泛的Springboot+Vue前后端分离多用户社区项目.本项目难度适中,为便于大家学习, ...

  3. springboot之Jwt验证

    简介 什么是JWT(Json Web Token) jwt是为了在网络应用环境间传递声明而执行的一种基于json的开放标准.该token被设计紧凑且安全的,特别适用于SSO场景. jwt的声明一般被用 ...

  4. springboot+vue前后端分离,nginx代理配置 tomcat 部署war包详细配置

    1.做一个小系统,使用了springboot+vue 基础框架参考这哥们的,直接拿过来用,链接https://github.com/smallsnail-wh/interest 前期的开发环境搭建就不 ...

  5. SpringBoot集成JWT实现token验证

    原文:https://www.jianshu.com/p/e88d3f8151db JWT官网: https://jwt.io/ JWT(Java版)的github地址:https://github. ...

  6. SpringBoot集成JWT 实现接口权限认证

    JWT介绍 Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的, 特别适用于分布式站点 ...

  7. SpringBoot集成JWT实现权限认证

    目录 一.JWT认证流程 二.SpringBoot整合JWT 三.测试 上一篇文章<一分钟带你了解JWT认证!>介绍了JWT的组成和认证原理,本文将介绍下SpringBoot整合JWT实现 ...

  8. SpringBoot+Vue+WebSocket 实现在线聊天

    一.前言 本文将基于 SpringBoot + Vue + WebSocket 实现一个简单的在线聊天功能 页面如下: 在线体验地址:http://www.zhengqingya.com:8101 二 ...

  9. Springboot vue.js html 跨域 前后分离 shiro权限 集成代码生成器

    本代码为 Springboot vue.js  前后分离 + 跨域 版本 (权限控制到菜单和按钮) 后台框架:springboot2.1.2+ mybaits+maven+接口 前端页面:html + ...

  10. .gitignore 标准模板 -适用于SpringBoot+Vue项目 -Idea+VSCode开发

    .gitignore 标准模板 -适用于SpringBoot+Vue项目 node_modules/ target/ !.mvn/wrapper/maven-wrapper.jar ### STS # ...

随机推荐

  1. 程序人生:01如何做到招聘要求中的“要有扎实的Java基础”

    本文摘自左潇龙博客,原文出处:http://www.zuoxiaolong.com/html/article_232.html 来历 本文来自于一次和群里猿友的交流,具体的情况且听LZ慢慢道来. 一日 ...

  2. BZOJ1972:[SDOI2010]猪国杀(模拟)

    Description 太长就不贴过来了 Solution 这个题是真的不难写……唯一的难度就在于理解题意上面……感觉这就是个阅读理解题啊…… 而且你三国杀玩的越多可能就越难写因为你无法理解那些猪的思 ...

  3. vue2.* 目录结构分析 数据绑定 循环渲染数据 数据渲染02

    一.目录 结构分析 node_modules:项目依赖文件(也可以说是模块) src:开发时所用的资源 assets:静态资源文件 App.vue:根组件(最基础的公共页面) main.js:实例化v ...

  4. 解决MySQL新建用户后无法登录问题

    在PHPMyAdmin里创建了一个新的用户,并且创建了密码,但是却一直无法使用这个账户登录到MySQL里. 解决过程分享给大家~ 1.以root身份登录mysql 2.删除MySQL中默认存在一个用户 ...

  5. Tomcat 安装APR的有关问题

    Tomcat 安装APR的问题APR.APR-util.APR-iconv安装都正常apr安装命令:./configuremakemake install apr-util./configure -- ...

  6. LUA IO库

    I/O库为文件操作提供两种模式. 简单模式(simple model)拥有一个当前输入文件和一个当前输出文件.而且提供针对这些文件相关的操作.全然模式(complete model)使用外部的文件句柄 ...

  7. 05_Dockerfile实战(上)

    在上一章我们介绍了docker镜像的概念,并且介绍了构建镜像的两种方式 使用docker commit命令提交创建的容器. 使用Dockerfile文件和docker build命令,这种更为推荐和常 ...

  8. Ubuntu16.04系统中不同版本Python之间的转换

    Ubuntu系统自带的版本是2.7.12 安装好python3.6之后,改变一下Python的优先级(需要root权限). 在使用下面这个命令查看电脑里面有几个Python版本 update-alte ...

  9. c/s和b/s结构的区别

    c/s结构 1.创建Client 2.设计服务器Server 3.设计私有通讯协议 4.随着功能的升级,安装了客户端程序的计算,要不升级最新版 b/s结构 1.浏览器代替客户端 2.服务器(协议教会, ...

  10. Oracle 存储结构二

    创建和管理表空间 创建表空间 典型语句: CREATE SMALLFILE TABLESPACE "JWTS" DATAFILE '/u01/app/oracle/oradata/ ...