个人博客开发之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博主文顶顶的博客这样内容图文并茂,代码齐全,示例经典,原理也有阐述,覆盖面宽广,自成系统的系列教程 ...
随机推荐
- 摄像头与毫米波雷达(Radar)融合
摄像头与毫米波雷达(Radar)融合 Input: (1)图像视频分辨率(整型int) (2)图像视频格式 (RGB,YUV,MP4等) (3)毫米波雷达点云信息(点云坐标位置x,y,浮点型float ...
- 降维-基于RDD的API
降维-基于RDD的API Singular value decomposition (SVD) Performance SVD Example Principal component analysis ...
- TVM在ARM GPU上优化移动深度学习
TVM在ARM GPU上优化移动深度学习 随着深度学习的巨大成功,将深度神经网络部署到移动设备的需求正在迅速增长.与在台式机平台上所做的类似,在移动设备中使用GPU可以提高推理速度和能源效率.但是,大 ...
- CodeGen准备存储库
CodeGen准备存储库 CodeGen几乎总是与提供用于生成源文件的元数据的存储库结构一起使用,并且许多令牌需要使用存储库结构. 基本要求是有一个结构定义,并且该结构定义包含一个或多个字段定义.有些 ...
- ARM系列处理器和架构
从一只ARM到另一只ARM! ARM处理器和架构 当前可用的处理器 ARM1 ARM2 ARM3 ARM4和5 ARM6 ARM7 ARM8 强壮有力的ARM ARM9 ARM10 ARM架构 v1 ...
- 编译器架构Compiler Architecture(上)
编译器架构Compiler Architecture(上) 编译器是程序,通常是非常大的程序.它们几乎都有一个基于翻译分析综合模型的结构. CONTENTS Overview • Compiler C ...
- kali2020.4中安装nessus 8.14.0
1.下载软件包 官网下载地址:https://www.tenable.com/downloads/nessus 2.安装nessus dpkg -i /root/Nessus-8.14.0-debia ...
- Pandas之:深入理解Pandas的数据结构
目录 简介 Series 从ndarray创建 从dict创建 从标量创建 Series 和 ndarray Series和dict 矢量化操作和标签对齐 Name属性 DataFrame 从Seri ...
- Django(64)频率认证源码分析与自定义频率认证
前言 有时候我们发送手机验证码,会发现1分钟只能发送1次,这是做了频率限制,限制的时间次数,都由开发者自己决定 频率认证源码分析 def check_throttles(self, request): ...
- 合宙Luat | 一文读懂LuaTask延时,看我如何从《射雕英雄传》角度分析。
武侠小说中,主人公之所以能纵横江湖,常常离不开一样可遇不可求的绝世法宝--武功秘籍.如今勇于尝试的开发者,笃定地告诉后来者:选Luat二次开发,就如同拥有了物联网开发的武功秘籍. 本期让我们通过< ...