个人博客开发之blog-api 项目整合JWT实现token登录认证
前言
现在前后端分离,基于session设计到跨越问题,而且session在多台服器之前同步问题,肯能会丢失,所以倾向于使用jwt作为token认证 json web token
- 导入java-jwt工具包
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.15.0</version>
</dependency>
- 通过jwt生成token
编写通用TokenService
package cn.soboys.core.authentication;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* @author kenx
* @version 1.0
* @date 2021/6/22 10:23
* token 操作
*/
@Service("TokenService")
public class TokenService {
//过期时间单位 毫秒 7*24*60*60*1000
private final Long tokenExpirationTime = 604800000l;
/**
* @param uuid 用户唯一标示
* @param secret 用户密码等
* @return token生成
*/
public String generateToken(String uuid, String secret) {
//每次登录充当前时间重新计算
Date expiresDate = new Date(System.currentTimeMillis() + tokenExpirationTime);
String token = "";
token = JWT.create()
//设置过期时间
.withExpiresAt(expiresDate)
//设置接受方信息,一般时登录用户
.withAudience(uuid)// 将 user id 保存到 token 里面
//使用HMAC算法
.sign(Algorithm.HMAC256(secret));// 以 password 作为 token 的密钥
return token;
}
}
- 编写注解过滤拦截需要登录验证的
controller
PassToken用于跳过登录验证UserLoginToken表示需要登录验证
package cn.soboys.core.authentication;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author kenx
* @version 1.0
* @date 2021/6/21 17:21
* 跳过登录验证
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
package cn.soboys.core.authentication;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author kenx
* @version 1.0
* @date 2021/6/21 17:22
* 需要登录验证
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
boolean required() default true;
}
- 编写业务异常
AuthenticationException
认证失败抛出认证异常AuthenticationException
package cn.soboys.core.authentication;
import lombok.Data;
/**
* @author kenx
* @version 1.0
* @date 2021/6/22 13:58
* 认证异常
*/
@Data
public class AuthenticationException extends RuntimeException {
public AuthenticationException(String message) {
super(message);
}
}
- 编写认证拦截器
AuthenticationInterceptor,拦截需要认证请求
package cn.soboys.core.authentication;
import cn.hutool.extra.spring.SpringUtil;
import cn.soboys.core.ret.ResultCode;
import cn.soboys.mallapi.entity.User;
import cn.soboys.mallapi.service.IUserService;
import cn.soboys.mallapi.service.impl.UserServiceImpl;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
* @author kenx
* @version 1.0
* @date 2021/6/21 17:24
* 用户验证登录拦截
*/
public class AuthenticationInterceptor implements HandlerInterceptor {
//从header中获取token
public static final String AUTHORIZATION_TOKEN = "authorizationToken";
private IUserService userService= SpringUtil.getBean(UserServiceImpl.class);
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
String token = httpServletRequest.getHeader(AUTHORIZATION_TOKEN);// 从 http 请求头中取出 token
httpServletRequest.setAttribute("token", token);
// 如果不是映射到Controller mapping方法直接通过
if (!(object instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) object;
Method method = handlerMethod.getMethod();
//检查是否有passtoken注释,有则跳过认证
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
//检查有没有需要用户权限的注解
//Annotation classLoginAnnotation = handlerMethod.getBeanType().getAnnotation(UserLoginToken.class);// 类级别的要求登录标记
if (method.isAnnotationPresent(UserLoginToken.class) || handlerMethod.getBeanType().isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken =
method.getAnnotation(UserLoginToken.class) == null ?
handlerMethod.getBeanType().getAnnotation(UserLoginToken.class) : method.getAnnotation(UserLoginToken.class);
if (userLoginToken.required()) {
// 执行认证
if (token == null) {
throw new AuthenticationException("无token,请重新登录");
}
// 获取 token 中的 user id
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new AuthenticationException("非法用户");
}
User user = userService.getUserInfoById(userId);
if (user == null) {
throw new AuthenticationException("用户过期,请重新登录");
}
// 验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getUserMobile())).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new AuthenticationException("非法用户");
}
return true;
}
}
return true;
}
}
个人博客开发之blog-api 项目整合JWT实现token登录认证的更多相关文章
- 个人博客开发之xadmin 布局和后台样式
项目源码下载:http://download.vhosts.cn 一. xadmin 后台配置注册信息 1. 在apps 的blogs 和 users 两个app中添加adminx.py文件 vim ...
- 个人博客开发之blog-api项目统一结果集api封装
前言 由于返回json api 格式接口,所以我们需要通过java bean封装一个统一数据返回格式,便于和前端约定交互, 状态码枚举ResultCode package cn.soboys.core ...
- 个人博客开发之blog-api 项目全局日志拦截记录
前言 大型完善项目中肯定是需要一个全局日志拦截,记录每次接口访问相关信息,包括: 访问ip,访问设备,请求参数,响应结果,响应时间,开始请求时间,访问接口描述,访问的用户,接口地址,请求类型,便于项目 ...
- SpringBoot博客开发之AOP日志处理
日志处理: 需求分析 日志处理需要记录的是: 请求的URL 访问者IP 调用的方法 传入的参数 返回的内容 上面的内容要求在控制台和日志中输出. 在学习这部分知识的时候,真的感觉收获很多,在之前Spr ...
- 个人博客开发之xadmin与ueditor集成
项目源码下载:http://download.vhosts.cn 1. xadmin 添加ueditor 插件 vim extra_apps\xadmin\plugins\ueditor.py #没有 ...
- 个人博客开发之 xadmin 安装
项目源码下载:http://download.vhosts.cn xadmin 下载地址:https://github.com/sshwsfc/xadmin或 https://github.com/s ...
- 个人博客开发之 ueditor 安装
- iOS开发之MVVM在项目中的应用
今天写这篇博客是想达到抛砖引玉的作用,想与大家交流一下思想,相互学习,博文中有不足之处还望大家批评指正.本篇博客的内容沿袭以往博客的风格,也是以干货为主,偶尔扯扯咸蛋(哈哈~不好好工作又开始发表博客啦 ...
- 文顶顶iOS开发博客链接整理及部分项目源代码下载
文顶顶iOS开发博客链接整理及部分项目源代码下载 网上的iOS开发的教程很多,但是像cnblogs博主文顶顶的博客这样内容图文并茂,代码齐全,示例经典,原理也有阐述,覆盖面宽广,自成系统的系列教程 ...
随机推荐
- 地理围栏API服务开发
地理围栏API服务开发 要使用华为地理围栏服务API,需要确保设备已经下载并安装了HMS Core(APK),并将Location Kit的SDK集成到项目中. 指定应用权限 如果需要使用地理围栏服务 ...
- 对端边缘云网络计算模式:透明计算、移动边缘计算、雾计算和Cloudlet
对端边缘云网络计算模式:透明计算.移动边缘计算.雾计算和Cloudlet 概要 将数据发送到云端进行分析是过去几十年的一个突出趋势,推动了云计算成为主流计算范式.然而,物联网时代设备数量和数据流量的急 ...
- 用NVIDIA Tensor Cores和TensorFlow 2加速医学图像分割
用NVIDIA Tensor Cores和TensorFlow 2加速医学图像分割 Accelerating Medical Image Segmentation with NVIDIA Tensor ...
- CUDA刷新:GPU计算生态系统
CUDA刷新:GPU计算生态系统 CUDA Refresher: The GPU Computing Ecosystem 这是CUDA Refresher系列的第三篇文章,其目标是刷新CUDA中的关键 ...
- python----日志模块loggin的使用,按日志级别分类写入文件
1.日志的级别 日志一共分为5个等级,从低到高分别是: 级别 说明 DEBUG 输出详细的运行情况,主要用于调试. INFO 确认一切按预期运行,一般用于输出重要运行情况. WARNING 系统运行时 ...
- postgresql无序uuid性能测试
无序uuid对数据库的影响 由于最近在做超大表的性能测试,在该过程中发现了无序uuid做主键对表插入性能有一定影响.结合实际情况发现当表的数据量越大,对表插入性能的影响也就越大. 测试环境 Postg ...
- P1024 [NOIP2001 提高组] 一元三次方程求解
题目描述 有形如:a x^3 + b x^2 + c x + d = 0 这样的一个一元三次方程.给出该方程中各项的系数(a,b,c,d均为实数),并约定该方程存在三个不同实根(根的范围在 -100至 ...
- Java第一次博客作业
第一次博客作业 目录 三次作业题目详情 作业中的错误分析 感想与心得 题目详情 题目1:第一次作业: 类图: 题目2 类图: 题目3 类图: 题目4 题目5 题目6 类图: 题目7 类图: 题目8 第 ...
- NOIP模拟测试24「star way to hevaen·lost my music」
star way to heaven 题解 大致尝试了一下并查集,记忆化搜索,最小生成树 最小生成树是正解,跑最小生成树然后找到最大的值 欧几里德距离最小生成树学习 prim楞跑 至于为什么跑最小生成 ...
- SpringBoot_登录注册
学习SpringBoot需要的前期基础 Spring(Bean容器 IOC set 构造方法 AOP) SpringMVC(GET POST Restful) 对于SpringBoot,约定大于配置 ...