关键词:
SpringBoot整合jwt
登录功能的实现
-
登陆页面输入用户名和密码进行登录
-
服务器
验证用户生成该用户Token返回客户端
-
客户端
存储该Token -
后续
客户端
的所有请求携带该Token -
服务器
验证Token是否通过
实现原理
Session、Cookie、Token的使用状况
- http是无状态的
- 通过cookie在客户端记录状态
- 通过session在服务器端记录状态
- 通过token方式维持状态
使用条件
在同一个服务器中常用Cookie,有跨域问题时使用Token
实践测试
生成Token给客户端
pojo
@Data
public class User
private String username;
private String pwd;
private String token;
JwtUtil
public class JwtUtil
private static long time=1000*60*60*24;
private static String signature="admimn";
public static String createToken()
JwtBuilder jwtBuilder= Jwts.builder();
String jwtToken=jwtBuilder
//header
.setHeaderParam("typ","JWT")
.setHeaderParam("alg","HS256")
//payload
.claim("username","admin")
.claim("role","123456")
.setSubject("admin-test")
.setExpiration(new Date(System.currentTimeMillis()+time))
.setId(UUID.randomUUID().toString())
//signature
.signWith(SignatureAlgorithm.HS256,signature)
.compact();
return jwtToken;
Controller
@RestController
public class UserController
private final String USERNAME="admin";
private final String PASSWORD="123456";
@GetMapping("/login")
public User login(User user)
System.out.println(user);
if(USERNAME.equals(user.getUsername()) && PASSWORD.equals(user.getPwd()))
//添加token
user.setToken(JwtUtil.createToken());
return user;
return null;
解决跨域问题
@Configuration
public class CrosConfiguration implements WebMvcConfigurer
@Override
public void addCorsMappings(CorsRegistry registry)
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
Vue
<template>
<div class="about">
<button @click="clickTo()">提交测试</button>
</div>
</template>
<script>
const axios = require('axios');
export default
name:'about',
data()
return
user:
username:'admin',
pwd:'123456',
,
methods:
clickTo()
var _this=this;
axios.get("http://localhost:8080/login",params:_this.user)
.then(res=>
console.log(res.data)
//登陆成功
if(res.data!=null)
//存入localStorage
localStorage.setItem('access-admin',JSON.stringify(res.data));
//注意是router非route
_this.$router.replace(path:'/')
)
</script>
验证
查看存储到了localStorage对象中
<template>
<div class="home">
<img alt="Vue logo" src="../assets/logo.png">
<HelloWorld msg="Welcome to Your Vue.js App"/>
<p>user</p>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default
name: 'Home',
components:
HelloWorld
,
data()
return
user:""
,
created()
this.user=localStorage.getItem('access-admin');
</script>
客户端存储Token
在route路由中实现
存储
代码复用,在每一次路由跳转前都需要进行一次用户验证
router.js
//首先引入axios包
import axios from 'axios'
//然后在实例化的router后面跟执行路由的逻辑
//在进行任何一个跳转之前,都要进行验证是否登陆或者验证token是否合法
router.beforeEach((to,from,next)=>
if(to.path.startsWith('/login'))
window.localStorage.removeItem('access-admin');
next();
else
//判断是否登陆
let admin = JSON.parse(window.localStorage.getItem('access-admin'));
//没登陆的用户就去登陆
if(!admin)
next(path:'/login');
else
//登陆的用户就去校验token的合法性
axios(
url:'http://localhost:8080/checkToken',
method:'get',
headers:
token: admin.token
).then((response)=>
if(!response.data)
console.log('校验失败')
next(path:'/error')
else
//如果说正确的话,直接路由跳转
next();
)
)
Error.vue
<template>
<div>
1231
</div>
</template>
<script>
export default
name:"Error",
created()
console.log("error")
localStorage.removeItem('access-admin');
this.$router.replace(path:'/about');
</script>
<style>
</style>
JwtUtil.java
在工具类中加入解析方法,验证token的合法性
public static boolean checkToken(String token) if(token == null) return false; //正常就是正常解析,抛异常就是解析失败 try Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token); catch (Exception e) return false; return true;
UserController.java
@GetMapping("/checkToken")public Boolean checkToken(HttpServletRequest request) String token=request.getHeader("token"); return JwtUtil.checkToken(token);
运行效果
所有的其他路径都被/login所替代拦截
专业解读
- 路由守卫只管有没有Token
- 验证Token一般放在请求拦截里
- 理论上所有的接口都有校验Token
springboot2.0+shiro+jwt整合(代码片段)
SpringBoot2.0+Shiro+JWT整合JSONWebToken(JWT)是一个非常轻巧的规范。这个规范允许我们使用JWT在用户和服务器之间传递安全可靠的信息。我们利用一定的编码生成Token,并在Token中加入一些非敏感信息,将其传递。安装环境开发工具:... 查看详情
java安全框架-springboot整合jwt
文章目录1.JWT案列使用1.1.pom.xml导入依赖1.2.生成token1.3.验证token1.4.常见的异常2.Springboot整合JWT2.1.封装JWT工具类2.2.导入依赖2.3.appliaction.properties2.4.数据库配置2.5.Dao层2.6.UserDaoMapper.xml2.7.Service层2.8.Controller层2.9使用拦截器进行优化2 查看详情
springboot整合jwt实现登录认证
参考技术A1、JWT的构成-头部(header):描述该JWT的最基本的信息,如类型以及签名所用的算法。-负载(payload):存放有效信息的地方。-签证(signature):base64加密后的header、base64加密后的payload和密钥secret加密后组成。2、整合JWT2.1引入JWT依... 查看详情
springboot整合jwt(代码片段)
这里写目录标题目的优缺点优点缺点代码pom引入生成jwt校验jwt刷新jwt其他用法总结目的一般系统都有登陆和验证用户是否登陆的需求,现在的项目好多都是前后端分离的,一般的session也不适合于多台机器同时提供服务的... 查看详情
springboot整合mybatis+jwt(代码片段)
Springboot整合mybatis+JWT本文学习了网络上的视频资源此处导入依赖<!--引入JWT依赖--><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.4.0</versio 查看详情
jwt整合springboot(代码片段)
文章目录JWT整合Springboot1.基于JWT认证1.1认证流程1.2JWT优势1.3JWT的结构是什么2.使用JWT3.整合SpringbootJWT整合Springboot1.基于JWT认证1.1认证流程首先,前端通过Web表单将自己的用户名和密码发送到后端的接口。这一过程一般是一个HT... 查看详情
springboot学习-4整合jwt
1、Jsonwebtoken(JWT)是为了网络应用环境间传递声明而执行的一种基于JSON的开发标准(RFC7519),该token被设计为紧凑且安全的,特别适用于分布式站点的单点登陆(SSO)场景。JWT的声明一般被用来在身份提供者和服务提供者间传... 查看详情
springboot整合shiro+jwt实现认证及权限校验
序言本文讲解如何使用SpringBoot整合Shiro框架来实现认证及权限校验,但如今的互联网已经成为前后端分离的时代,所以本文在使用SpringBoot整合Shiro框架的时候会联合JWT一起搭配使用。ShiroShiro是apache旗下一个开源框架,... 查看详情
全网最细致springboot整合springsecurity+jwt实现用户认证(代码片段)
【全网最细致】SpringBoot整合SpringSecurity+JWT实现用户认证 登录和用户认证是一个网站最基本的功能,在这篇博客里,将介绍如何用SpringBoot整合SpringSecurity+JWT实现登录及用户认证文章目录【全网最细致】SpringBoot整... 查看详情
springboot-springsecurity-jwt的整合案例分析(代码片段)
SpringBoot-SpringSecurity-Jwt的整合案例分析一、Jwt概述1、什么是Jwt?Jwt是JsonWebToken的简称,它的声明一般用于在身份提供者和服务提供者之间传递被认证的身份信息,以便从资源服务器获取资源,也可以增加一些额外... 查看详情
springboot-springsecurity-jwt的整合案例分析(代码片段)
SpringBoot-SpringSecurity-Jwt的整合案例分析一、Jwt概述1、什么是Jwt?Jwt是JsonWebToken的简称,它的声明一般用于在身份提供者和服务提供者之间传递被认证的身份信息,以便从资源服务器获取资源,也可以增加一些额外... 查看详情
一分钟完成springboot项目整合swagger2实现自动生成接口文档
...但本人认为还是利大于弊的。接下来我们将Swagger2整合到springboot项目中,并用swagger-bootstrap-ui对Swagger2进行界面美化,废话不多说,我们开始。。。在pom.xml中导入在application.yml中设置swagger2是否开启的开关,关闭后接口文档被关... 查看详情
深入总结springboot整合jwt,这应该是全网讲的最通俗易懂的了(代码片段)
...,以确保信息是可验证和可信任的。今天我们来深入总结SpringBoot整合JWT前言我们都知道JWT是一个JSON信息传输的开放标准,它可以使用密钥对信息进行数字签名,以确保信息是可验证和可信任的。今天我们来深入总结SpringBoot整合... 查看详情
springboot整合jwt
参考技术A参考网址:https://www.jb51.net/article/153145.htmJSONWebtoken简称JWT,是用于对应用程序上的用户进行身份验证的标记。也就是说,使用JWTS的应用程序不再需要保存有关其用户的cookie或其他session数据。此特性便于可伸缩性,同时保证... 查看详情
springboot整合jwt和请求拦截,实现利用token做请求安全拦截校验,且实现阻止并发登录(代码片段)
目录一、导入依赖二、编写jwt工具类,实现生成token和解析token三、在登录请求中向redis中添加token信息1、先注入redis的接口类2、在登录方法中生成token并插入redis,有效期一天四、实现请求拦截器1、编写自定义的请求拦截... 查看详情
springboot整合shiro+jwt实现认证及权限校验(代码片段)
序言本文讲解如何使用SpringBoot整合Shiro框架来实现认证及权限校验,但如今的互联网已经成为前后端分离的时代,所以本文在使用SpringBoot整合Shiro框架的时候会联合JWT一起搭配使用。ShiroShiro是apache旗下一个开源框架,... 查看详情
springboot技术专题「jwt技术专区」带你一同开发springsecurity整合jwt授权和认证实战指南(代码片段)
JWT基本概念JWT,即JSONWebTokens(RFC7519),是一个广泛用于验证RESTAPIs的标准。虽说是一个新兴技术,但它却得以迅速流行。JWT的验证过程是:前端(客户端)首先发送一些凭证来登录(我们编写... 查看详情
springboot/git/linux/easycode
SpringBootSpringBoot整合MyBatisSpringBoot整合Swagger-UI好看的SwaggerUI【重要】好看的SwaggerUI(包括配置了token)–knife4jSpringBoot整合RedisSpringBoot整合SpringSecurity和JWT的1SpringBoot整合SpringSecurity和JWT的2Spring 查看详情