前言

现在前后端分离,基于session设计到跨越问题,而且session在多台服器之前同步问题,肯能会丢失,所以倾向于使用jwt作为token认证 json web token

  1. 导入java-jwt工具包
 <dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.15.0</version>
</dependency>
  1. 通过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;
}
}
  1. 编写注解过滤拦截需要登录验证的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;
}
  1. 编写业务异常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);
} }
  1. 编写认证拦截器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登录认证的更多相关文章

  1. 个人博客开发之xadmin 布局和后台样式

    项目源码下载:http://download.vhosts.cn 一. xadmin 后台配置注册信息 1. 在apps 的blogs 和 users 两个app中添加adminx.py文件 vim ...

  2. 个人博客开发之blog-api项目统一结果集api封装

    前言 由于返回json api 格式接口,所以我们需要通过java bean封装一个统一数据返回格式,便于和前端约定交互, 状态码枚举ResultCode package cn.soboys.core ...

  3. 个人博客开发之blog-api 项目全局日志拦截记录

    前言 大型完善项目中肯定是需要一个全局日志拦截,记录每次接口访问相关信息,包括: 访问ip,访问设备,请求参数,响应结果,响应时间,开始请求时间,访问接口描述,访问的用户,接口地址,请求类型,便于项目 ...

  4. SpringBoot博客开发之AOP日志处理

    日志处理: 需求分析 日志处理需要记录的是: 请求的URL 访问者IP 调用的方法 传入的参数 返回的内容 上面的内容要求在控制台和日志中输出. 在学习这部分知识的时候,真的感觉收获很多,在之前Spr ...

  5. 个人博客开发之xadmin与ueditor集成

    项目源码下载:http://download.vhosts.cn 1. xadmin 添加ueditor 插件 vim extra_apps\xadmin\plugins\ueditor.py #没有 ...

  6. 个人博客开发之 xadmin 安装

    项目源码下载:http://download.vhosts.cn xadmin 下载地址:https://github.com/sshwsfc/xadmin或 https://github.com/s ...

  7. 个人博客开发之 ueditor 安装

  8. iOS开发之MVVM在项目中的应用

    今天写这篇博客是想达到抛砖引玉的作用,想与大家交流一下思想,相互学习,博文中有不足之处还望大家批评指正.本篇博客的内容沿袭以往博客的风格,也是以干货为主,偶尔扯扯咸蛋(哈哈~不好好工作又开始发表博客啦 ...

  9. 文顶顶iOS开发博客链接整理及部分项目源代码下载

    文顶顶iOS开发博客链接整理及部分项目源代码下载   网上的iOS开发的教程很多,但是像cnblogs博主文顶顶的博客这样内容图文并茂,代码齐全,示例经典,原理也有阐述,覆盖面宽广,自成系统的系列教程 ...

随机推荐

  1. 在NVIDIA A100 GPU上利用硬件JPEG解码器和NVIDIA nvJPEG库

    在NVIDIA A100 GPU上利用硬件JPEG解码器和NVIDIA nvJPEG库 根据调查,普通人产生的1.2万亿张图像可以通过电话或数码相机捕获.这样的图像的存储,尤其是以高分辨率的原始格式, ...

  2. CUDA 7 流并发性优化

    异构计算是指高效地使用系统中的所有处理器,包括 CPU 和 GPU .为此,应用程序必须在多个处理器上并发执行函数. CUDA 应用程序通过在 streams 中执行异步命令来管理并发性,这些命令是按 ...

  3. CAP 超详细名词解释

    目录 引言 概述 分布式 一致性 ACID中的一致性 可用性 分区容错性 可用性与分区容错性,傻傻分不清 问题1:分区容错性说分区故障正常工作,什么叫正常工作?这个正常工作是指满足可用性吗? 问题2: ...

  4. 教你在Kubernetes中快速部署ES集群

    摘要:ES集群是进行大数据存储和分析,快速检索的利器,本文简述了ES的集群架构,并提供了在Kubernetes中快速部署ES集群的样例:对ES集群的监控运维工具进行了介绍,并提供了部分问题定位经验,最 ...

  5. Samsung WLAN AP RCE漏洞及利用工具

    1.漏洞详情: 三星 WLAN AP WEA453e 路由器 远程命令执行 2.fofa语句 title=="Samsung WLAN AP" 3.复现 payload: POST ...

  6. ubuntu 如何更改 grub 界面主题

    ubuntu 如何更改 grub 界面主题 安装 Liunx 系统的人都知道,系统引导是通过 grub 去引导的,但是 grub 这个界面就很单调,大概是这样子的 这肯定不符合我们潮流青年的审美的~ ...

  7. C# 设置Word文本框中的文字旋转方向

    在Word中可插入文本框,默认情况下插入的文本框中的文字方向为横向排列,对于一些特殊文档的设计要求,需要改变文字方向,如本次测试中的文档排版为考生试卷类型,考生信息栏的内容为下图中的这种, 本文将以C ...

  8. 基于ABP落地领域驱动设计-01.全景图

    什么是领域驱动设计? 领域驱动设计(简称:DDD)是一种针对复杂需求的软件开发方法.将软件实现与不断发展的模型联系起来,专注于核心领域逻辑,而不是基础设施细节.DDD适用于复杂领域和大规模应用,而不是 ...

  9. 关于Word转Markdown的工具Writage安装及使用

    简介 Writage是为希望开始编写结构良好的文档,没有时间或不想深入了解 Markdown 语法的详细信息,或者更愿意使用 Word 作为文本编辑器的每个人设计的 下载并安装 安装包地址:https ...

  10. 44、djanjo工程(介绍)

    44.1.什么时web框架: 1.框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用看框架可以 帮助你快速开发特定的形同,简单的说,就是你用别人搭建好的舞台来做 ...