Jwt在javaweb项目中的应用核心步骤解读
<!--引入JWT依赖,由于是基于Java,所以需要的是java-jwt-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
passtoken
package com.pjb.springbootjjwt.annotation; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* @author jinbin
* @date 2018-07-08 20:38
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
userlogintoken
package com.pjb.springbootjjwt.annotation; import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; /**
* @author jinbin
* @date 2018-07-08 20:40
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
boolean required() default true;
}
注解解析:从上面我们新建的两个类上我们可以看到主要的等学习到的就四点
第一:如何创建一个注解
第二:在我们自定义注解上新增@Target注解(注解解释:这个注解标注我们定义的注解是可以作用在类上还是方法上还是属性上面)
第三:在我们自定义注解上新增@Retention注解(注解解释:作用是定义被它所注解的注解保留多久,一共有三种策略,SOURCE 被编译器忽略,CLASS 注解将会被保留在Class文件中,但在运行时并不会被VM保留。这是默认行为,所有没有用Retention注解的注解,都会采用这种策略。RUNTIME 保留至运行时。所以我们可以通过反射去获取注解信息。
第四:boolean required() default true; 默认required() 属性为true






附上拦截器源代码
package com.pjb.springbootjjwt.interceptor; 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 com.pjb.springbootjjwt.annotation.PassToken;
import com.pjb.springbootjjwt.annotation.UserLoginToken;
import com.pjb.springbootjjwt.entity.User;
import com.pjb.springbootjjwt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method; /**
* @author jinbin
* @date 2018-07-08 20:41
*/
public class AuthenticationInterceptor implements HandlerInterceptor { @Autowired
UserService userService; @Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception { // 从 http 请求头中取出 token
String token = httpServletRequest.getHeader("token");
// 如果不是映射到方法直接通过
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;
}
} //检查有没有需要用户权限的注解
if (method.isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
if (userLoginToken.required()) {
// 执行认证
if (token == null) {
throw new RuntimeException("无token,请重新登录");
}
// 获取 token 中的 user id
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
throw new RuntimeException("401");
}
User user = userService.findUserById(userId);
if (user == null) {
throw new RuntimeException("用户不存在,请重新登录");
} // 验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build(); try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
throw new RuntimeException("401");
}
return true;
}
}
return true;
} @Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
Jwt在javaweb项目中的应用核心步骤解读的更多相关文章
- Jwt在Java项目中的简单实际应用
1.什么是jwt 双方之间传递安全信息的简洁的.URL安全的表述性声明规范.JWT作为一个开放的标准(RFC 7519),定义了一种简洁的,自包含的方法用于通信双方之间以Json对象的形式安全的传递信 ...
- log4j在javaWeb项目中的使用
在前边的文章中对log4j的配置文件进行了说明,今天介绍如何在普通的javaWeb项目中使用log4j. 在日常的开发过程中,日志使用的很频繁,我们可以利用日志来跟踪程序的错误,程序运行时的输出参数等 ...
- Druid使用起步—在javaWeb项目中配置监控 连接池
当我们在javaWEB项目中使用到druid来作为我们的连接池的时候,一定不会忘了添加监控功能.下面我们就来看一下,在一个简单的web项目中(尚未使用任何框架)我们是如果来配置我们的web.xml来完 ...
- JavaWeb 项目中的绝对路径和相对路径以及问题的解决方式
近期在做JavaWeb项目,总是出现各种的路径错误,并且发现不同情况下 / 所代表的含义不同,导致在调试路径上浪费了大量时间. 在JavaWeb项目中尽量使用绝对路径 由于使用绝对路径是绝对不会出 ...
- JavaWeb项目中web.xml有关servlet的基本配置
JavaWeb项目中web.xml有关servlet的基本配置: 我们注意到,tomcat下的conf中也有一个web.xml文件,没错的,所有的JavaWeb项目中web.xml都继承自服务器下的w ...
- 关联分析FPGrowth算法在JavaWeb项目中的应用
关联分析(关联挖掘)是指在交易数据.关系数据或其他信息载体中,查找存在于项目集合或对象集合之间的频繁模式.关联.相关性或因果结构.关联分析的一个典型例子是购物篮分析.通过发现顾客放入购物篮中不同商品之 ...
- ElasticSearch搜索引擎在JavaWeb项目中的应用
近几篇ElasticSearch系列: 1.阿里云服务器Linux系统安装配置ElasticSearch搜索引擎 2.Linux系统中ElasticSearch搜索引擎安装配置Head插件 3.Ela ...
- 通过调用API在JavaWeb项目中实现证件识别
本文详细介绍自己如何在JavaWeb项目中通过调用API实现证件识别. 一,Face++使用简介 二,两种方式(图片URL与本地上传)实现证件识别 一,Face++使用简介 Face++旷视人工智能开 ...
- Javaweb项目中出现java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone.异常
javaweb项目中java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized or represent ...
随机推荐
- unity, StartCoroutine and StopCoroutine
startCoroutine("func",1.0f)可以用stopCoroutine("func")来停. startCoroutine(func(1.0f) ...
- [原]C#设置文件夹用户权限
var security = new DirectorySecurity(); string path=@"C:\temp" //设置权限的应用为文件夹本身.子文件夹及文件,所 ...
- RSA加密的测试demo
使用.net自带的RSA,需要引用System.Security.Cryptography 测试环境.net4.6 static void Main(string[] args) { var RSA ...
- [转]如何为图片添加热点链接?(map + area)
原文地址:https://www.cnblogs.com/jf-67/p/8135004.html 所谓图片热点链接就是为图片指定一个或多个区域以实现点击跳转到指定的页面.简单来说就是点击某一区域就能 ...
- linux 清内存
注意:首先我们需要使用sync指令,将所有未写的系统缓冲区写到磁盘中,包含已修改的 i-node.已延迟的块 I/O 和读写映射文件.否则在释放缓存的过程中,可能会丢失未保存的文件. 的值可以为0~3 ...
- struts2异常处理机制
一.处理一般异常(javaBean异常) struts2进行异常处理首先需要添加exception拦截器,而默认拦截器栈已经加入了这个拦截器,所以不用特意的声明.在Struts 2框架中,采用声明式异 ...
- Mac命令行启动MySQL
#mysql 启动 mysql.server start #mysql停止 mysql.server stop #mysql重启 mysql.server restart
- dp背包之01背包poj2184
http://poj.org/problem?id=2184 题意:给定两个属性,求这两个属性的和的最大值......... 思路:将第一个属性往后平移1000个单位,然后推导其动态转移方程,若是dp ...
- 记一次线上MySQL数据库死锁问题
最近线上项目报了一个MySQL死锁(DealLock)错误,虽说对业务上是没有什么影响的,由于自己对数据库锁这块了解不是很多,之前也没怎么的在线上碰到过.这次刚好遇到了,便在此记录一下 ...
- Spring AOP注解通过@Autowired,@Resource,@Qualifier,@PostConstruct,@PreDestroy注入属性的配置文件详解
本文介绍了使用Spring注解注入属性的方法.使用注解以前,注入属性通过类以及配置文件来实现.现在,注入属性可以通过引入@Autowired注解,或者@Resource,@Qualifier,@Pos ...