springboot 整合 Spring Security+JWT 实现token 认证和校验

本文主要是介绍springboot 整合 Spring Security+JWT 实现token 认证和校验,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.大概是这个样子

在这里插入图片描述

JWT 是什么?

Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。JWT的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该token也可直接被用于认证,也可被加密

java 如何实现JWT

   <dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>4.3.
工具类

package com.example.testsecurity.utils;import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;import java.util.Date;
import java.util.HashMap;
import java.util.Map;@Slf4j
@Componentpublic class JwtTokenUtils {private static final long EXPIRE_TIME = 15 * 60 * 1000;//默认15分钟//私钥private static final String TOKEN_SECRET = "gsc12345678";/*** 生成签名,15分钟过期** @param **username*** @param **password*** @return*/public static String createToken(String userName) {try {// 设置过期时间Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);// 私钥和加密算法Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);// 设置头部信息Map<String, Object> header = new HashMap<>(2);header.put("Type", "Jwt");header.put("alg", "HS256");// 返回token字符串return JWT.create().withHeader(header).withClaim("userName", userName).withExpiresAt(date).sign(algorithm);} catch (Exception e) {e.printStackTrace();return null;}}/*** 生成token,自定义过期时间 毫秒** @param **username*** @param **password*** @return*/public static String createToken(String userName, long expireDate) {try {// 设置过期时间Date date = new Date(System.currentTimeMillis() + expireDate);// 私钥和加密算法Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);// 设置头部信息Map<String, Object> header = new HashMap<>(2);header.put("Type", "Jwt");header.put("alg", "HS256");// 返回token字符串return JWT.create().withHeader(header).withClaim("userName", userName).withExpiresAt(date).sign(algorithm);} catch (Exception e) {e.printStackTrace();return null;}}/*** 检验token是否正确** @param **token*** @return*/public static boolean verifyToken(String token) {try {Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);JWTVerifier verifier = JWT.require(algorithm).build();DecodedJWT jwt = verifier.verify(token);String userId = jwt.getClaim("userId").asString();log.info(userId);return true;} catch (Exception e) {log.error(e.getLocalizedMessage());return false;}}public static String getUserName(String token) {Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);JWTVerifier verifier = JWT.require(algorithm).build();DecodedJWT jwt = verifier.verify(token);String userName = jwt.getClaim("userName").asString();return userName;}
}
怎么和security 整合在一起了?

在这里插入图片描述

1.认证成功生成一个token返回给客户端,这里就做个简单的本地保存,一般存到缓存中比如redis 里面,就是认证处理器里面做处理

public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {Result result = Result.build(1, "登录成功");MyUser user = (MyUser) authentication.getPrincipal();log.info(user.getUser().getId() + "");String userName = user.getUser().getName();String token = JwtTokenUtils.createToken(userName, 1000 * 60*30);result.setData(token);String responsejson = objectMapper.writeValueAsString(result);response.setCharacterEncoding("utf-8");response.setContentType("application/json;charset=UTF-8");response.getWriter().println(responsejson);response.getWriter().flush();}
2。认证做完了,每次客户端调用其他接口的时间就要校验处理,JWT 过滤器处理,并把token中用户信息放到安全过滤器,供过滤器链上其他过滤器
package com.example.testsecurity.filter;import com.example.testsecurity.pojo.MyUser;
import com.example.testsecurity.pojo.Result;
import com.example.testsecurity.service.MyUserService;
import com.example.testsecurity.utils.JwtTokenUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;import java.io.IOException;@Component
@Slf4j
public class JWTCheckFilter extends OncePerRequestFilter {@Autowiredprivate ObjectMapper objectMapper;@Autowiredprivate JwtTokenUtils jwtTokenUtils;@Autowiredprivate MyUserService userService;@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {String requestURI = request.getRequestURI();//login 放行token 校验log.info(requestURI);if (requestURI.equals("/login")) {doFilter(request, response, filterChain);return;}String authorization = request.getHeader("Authorization");log.info(authorization);if (ObjectUtils.isEmpty(authorization)) {Result result = Result.build(-1, "token不存在", null);String responsejson = objectMapper.writeValueAsString(result);response.setCharacterEncoding("utf-8");response.setContentType("application/json;charset=UTF-8");response.getWriter().println(responsejson);response.getWriter().flush();return;}String jwtToken = authorization.replace("bearer ", "");log.error("jwtToken>>>" + jwtToken);boolean verifyToken = jwtTokenUtils.verifyToken(jwtToken);log.error(String.valueOf(verifyToken));if (!verifyToken) {Result result = Result.build(-1, "token失效", null);String responsejson = objectMapper.writeValueAsString(result);response.setCharacterEncoding("utf-8");response.setContentType("application/json;charset=UTF-8");response.getWriter().println(responsejson);response.getWriter().flush();return;}//有效获取用户安全信息String userName = jwtTokenUtils.getUserName(jwtToken);MyUser details = (MyUser) userService.loadUserByUsername(userName);//将认证信息放入安全上下文UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(details, null, details.getAuthorities());//获取安全上下文SecurityContextHolder.getContext().setAuthentication(authenticationToken);doFilter(request, response, filterChain);}
}
配置类中配置这个过滤器才能生效:
http.addFilterBefore(checkFilter, UsernamePasswordAuthenticationFilter.class);
测试权限以及token 校验这个了写了前端uniapp

在这里插入图片描述
小李:老师 ,张三是学生,本数据库中

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

前端随便写了一下代码
<template><view class="box"><view class="username-box"><text>用户名</text><u--input placeholder="请输入用户名" border="surround" v-model="username"></u--input></view><view class="pwd-box"><text>密码</text><u--input type="password" placeholder="请输入用户名" border="surround" v-model="password"></u--input></view><u-button text="登录" type="primary" class="submit-btn" @click="login"></u-button></view>
</template><script>export default {data() {return {username: '',password: '',loginUrl: 'http://127.0.0.1:8989/login'}},methods: {login() {let params = {username: this.username,password: this.password}uni.request({url: this.loginUrl,method: 'POST',header: {'content-type': 'application/x-www-form-urlencoded',},data: params,success: (res) => {console.log(res.data);const {code,data} = res.dataif (code == 1) {//登录成功//保存tokenuni.setStorageSync('token', data)uni.navigateTo({url: '/pages/index/index'})}}});}}}
</script><style scoped lang="scss">.box {.submit-btn {margin: 20rpx 32rpx;width: 686rpx;}.username-box,.pwd-box {margin: 20rpx 32rpx 0;display: flex;align-items: center;>text {padding-right: 10rpx;display: block;width: 120rpx;}}}
</style>
<template><view><view class="title-box"><view v-if="this.menuList.length==3">我是老师:{{currentUserName}}</view><view v-else>我是学生:{{currentUserName}}</view></view><u-grid :border="false" @click="click"><u-grid-item v-for="(baseListItem,baseListIndex) in menuList" :key="baseListIndex"><u-icon :customStyle="{paddingTop:20+'rpx'}" :name="baseListItem.name" :size="22"></u-icon><text class="grid-text">{{baseListItem.title}}</text></u-grid-item></u-grid><u-toast ref="uToast" /></view>
</template><script>import {commonUrl} from '../constant.js'export default {data() {return {// menuList: [{// 		name: 'cut',// 		title: '查看作业'// 	},// 	{// 		name: 'edit-pen-fill',// 		title: '编辑作业'// 	},// 	{// 		name: 'trash-fill',// 		title: '删除作业'// 	},// ],menuList: [],authorityArr: [],currentUserName: ''}},onLoad() {},onShow() {this.menuList = []this.loadMenu()},methods: {loadMenu() {uni.request({url: commonUrl.userInfoUrl,method: 'GET',header: {'Authorization': 'bearer' + ' ' + uni.getStorageSync('token') || ''},success: (res) => {console.log('用户信息', res.data.authorities, typeof res.data.authorities);this.authorityArr = res.data.authorities;this.currentUserName = res.data.namethis.authorityArr.forEach((item, index) => {console.log('item ???', item, index);console.log(item.authority);if (item.authority == 'look:zy') {this.menuList.push({name: 'cut',title: '查看作业'})}if (item.authority == 'edit:zy') {console.log('aaa');this.menuList.push({name: 'edit-pen-fill',title: '编辑作业'})}if ('del:zy' == item.authority) {this.menuList.push({name: 'trash-fill',title: '删除作业'})}})},})},click(name) {switch (name) {case 0:this.lookzy()breakcase 1:this.editzy()breakcase 2:this.delzy()break}},loadData(url) {uni.request({url: url,header: {'Authorization': 'bearer' + ' ' + uni.getStorageSync('token') || ''},success: (res) => {console.log('res', res.data);const {code,message} = res.dataif (code != 0) {this.$refs.uToast.success(`访问失败`)uni.redirectTo({url: '/pages/login/login'})return}this.$refs.uToast.success(message)}})},lookzy() {this.loadData(commonUrl.zyUrl)},editzy() {this.loadData(commonUrl.editUrl)},delzy() {this.loadData(commonUrl.delUrl)}}}
</script><style lang="scss">.title-box {padding: 20rpx 12rpx 20rpx}.grid-text {font-size: 14px;color: #909399;padding: 10rpx 0 20rpx 0rpx;/* #ifndef APP-PLUS */box-sizing: border-box;/* #endif */}
</style>
备注以上只是简单的写了一个例子,token最好还是放到redis中

认证成功和校验的时候,去处理还有注销的时候去删除这个token 的key

这篇关于springboot 整合 Spring Security+JWT 实现token 认证和校验的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/463975

相关文章

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

Spring @Scheduled注解及工作原理

《Spring@Scheduled注解及工作原理》Spring的@Scheduled注解用于标记定时任务,无需额外库,需配置@EnableScheduling,设置fixedRate、fixedDe... 目录1.@Scheduled注解定义2.配置 @Scheduled2.1 开启定时任务支持2.2 创建

SpringBoot中使用Flux实现流式返回的方法小结

《SpringBoot中使用Flux实现流式返回的方法小结》文章介绍流式返回(StreamingResponse)在SpringBoot中通过Flux实现,优势包括提升用户体验、降低内存消耗、支持长连... 目录背景流式返回的核心概念与优势1. 提升用户体验2. 降低内存消耗3. 支持长连接与实时通信在Sp

Conda虚拟环境的复制和迁移的四种方法实现

《Conda虚拟环境的复制和迁移的四种方法实现》本文主要介绍了Conda虚拟环境的复制和迁移的四种方法实现,包括requirements.txt,environment.yml,conda-pack,... 目录在本机复制Conda虚拟环境相同操作系统之间复制环境方法一:requirements.txt方法

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

Mac系统下卸载JAVA和JDK的步骤

《Mac系统下卸载JAVA和JDK的步骤》JDK是Java语言的软件开发工具包,它提供了开发和运行Java应用程序所需的工具、库和资源,:本文主要介绍Mac系统下卸载JAVA和JDK的相关资料,需... 目录1. 卸载系统自带的 Java 版本检查当前 Java 版本通过命令卸载系统 Java2. 卸载自定

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

SpringMVC高效获取JavaBean对象指南

《SpringMVC高效获取JavaBean对象指南》SpringMVC通过数据绑定自动将请求参数映射到JavaBean,支持表单、URL及JSON数据,需用@ModelAttribute、@Requ... 目录Spring MVC 获取 JavaBean 对象指南核心机制:数据绑定实现步骤1. 定义 Ja