token jwt配置
1. token jwt配置
1.1. pom
<!-- token验证 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
1.2. 代码
1.2.1. 生成token
@Configuration
public class JwtToken {
/**
* 生成jwt token
*/
public Token generateToken(Long userId) {
Date date = new Date();
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
Date expiration = DateUtils.addDays(new Date(), 3);
String token = Jwts.builder()
// 设置header
.setHeaderParam("typ", "JWT")
// 设置签发时间
.setHeaderParam("alg", "HS256").setIssuedAt(date)
.setExpiration(expiration)
// 设置内容
.claim("userId", String.valueOf(userId))
// 设置签发人
.setIssuer("lll")
// 签名,需要算法和key
.signWith(signatureAlgorithm, "xxxxx").compact();
return new Token().setExpireTime(expiration).setToken(token).setUserId(userId);
}
}
1.2.2. token拦截器
public class TokenInterceptor implements HandlerInterceptor {
@Autowired
private ITokenService tokenService;
@Autowired
private JwtToken jwtToken;
private Map<Long, Token> tokenMap = new ConcurrentHashMap<>();
public Set<String> passPath = new HashSet<>();
/**
* 添加token
*
* @param userId
* @return
*/
public Token addToken(Long userId) {
Token token = jwtToken.generateToken(userId);
tokenMap.put(userId, token);
Token tk = tokenService.getById(userId);
if (tk != null) {
tokenService.updateById(token);
} else {
tokenService.save(token);
}
return token;
}
public TokenInterceptor() {
init();
}
@Value("${token.enabled:false}")
public boolean openToken;
/**
* token开关
*
* @param openToken
*/
public void setOpenToken(boolean openToken) {
this.openToken = openToken;
}
@PostConstruct
private void init() {
passPath.add("/fund/user/");
passPath.add("/fund/user/login");
}
private boolean isFilter(String uri) {
if (!openToken) {
return true;
}
return passPath.stream().anyMatch(s -> s.equals(uri));
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
//普通路径放行
if (isFilter(request.getRequestURI())) {
return true;
}
//权限路径拦截
response.setCharacterEncoding("UTF-8");
final String headerToken = request.getHeader("x-access-token");
//判断请求信息
if (null == headerToken || "".equals(headerToken.trim())) {
response.getWriter().write("用户未登录,请先登录");
return false;
}
//解析Token信息
try {
Claims claims = Jwts.parser().setSigningKey("beikbank@fund").parseClaimsJws(headerToken).getBody();
String tokenUserId = (String) claims.get("userId");
Long itokenUserId = Long.parseLong(tokenUserId);
//根据客户Token查找缓存Token
Token myToken = tokenMap.get(itokenUserId);
//缓存没有Token记录
if (null == myToken) {
Token token = tokenService.getById(itokenUserId);
if (token != null) {
if (judgeToken(response, headerToken, claims, itokenUserId, token)) {
return false;
}
}
return true;
}
if (judgeToken(response, headerToken, claims, itokenUserId, myToken)) {
return false;
}
} catch (Exception e) {
e.printStackTrace();
response.getWriter().write("发生异常,请重新登录");
return false;
}
//最后才放行
return true;
}
private boolean judgeToken(HttpServletResponse response, String headerToken, Claims claims, Long itokenUserId, Token myToken) throws IOException {
//缓存Token与客户Token比较
if (!headerToken.equals(myToken.getToken())) {
response.getWriter().write("token不正确,请重新登录");
return true;
}
//判断Token过期
Date tokenDate = claims.getExpiration();
if (tokenDate.before(new Date())) {
tokenMap.remove(itokenUserId);
tokenService.removeById(itokenUserId);
response.getWriter().write("token过期,请重新登录");
return true;
}
return false;
}
}
1.2.3. 设置token
- token设置,在登录时设置
@Autowired
private TokenInterceptor tokenInterceptor;
@ApiOperation(value = "用户登录", notes = "用户登录")
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity login( @RequestBody @ApiParam(name = "user", value = "用户", required = true) @Valid User user) {
boolean result = userService.vaildLogin(user);
Token token = tokenInterceptor.addToken(user.getUserId());
return ResponseEntity.ok(result ? ok(token) : error("登录失败,请检查用户名和密码"));
}
token jwt配置的更多相关文章
- spring boot rest 接口集成 spring security(2) - JWT配置
Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 sp ...
- JSON WEB Token(JWT)
最近面试被问及单点登陆怎么解决?自己的项目前后端分离,自己实现token认证,token有失效时间,token中包含用户基本的信息.且一个当用户重新登陆后,原来的token就会失效,这么安全的一个to ...
- JSON Web Token (JWT) 简介
JSON Web Token (JWT) 是一种基于 token 的认证方案. JSON Web Token 的结构 一个 JWT token 看起来是这样的: eyJhbGciOiJIUzI1NiI ...
- JSON Web Token (JWT) 实现与使用方法
1. JSON Web Token是什么 JSON Web Token (JWT)是一个开放标准(RFC 7519),它定义了一种紧凑的.自包含的方式,用于作为JSON对象在各方之间安全地传输信息.该 ...
- Json Web Token(JWT)详解
什么是Json Web Token Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的 ...
- JSON Web Token (JWT),服务端信息传输安全解决方案。
JWT介绍 JSON Web Token(JWT)是一种开放标准(RFC 7519),它定义了一种紧凑独立的基于JSON对象在各方之间安全地传输信息的方式.这些信息可以被验证和信任,因为它是数字签名的 ...
- json web token JWT实现TP5创建和验证
根据博客进行jwt初始化配置 https://blog.csdn.net/weixin_43389208/article/details/117442266?spm=1001.2014.3001.55 ...
- 基于 Token 的身份验证:JSON Web Token(JWT)
1.传统身份验证和JWT的身份验证 传统身份验证: HTTP 是一种没有状态的协议,也就是它并不知道是谁是访问应用.这里我们把用户看成是客户端,客户端使用用户名还有密码通过了身份验证,不过 ...
- JSON Web Token (JWT) - Weak secret
This API with its /hello endpoint (accessible with GET) seems rather welcoming at first glance but i ...
随机推荐
- yum -y install pip No package pip available. Error: Nothing to do
centos下安装pip时失败: [root@wfm ~]# yum -y install pipLoaded plugins: fastestmirror, refresh-packagekit, ...
- SoapUI: 从属性变量里面读取值, 把string 转换成arraylist
- Mark about 《美国债务危机 》
1.债务是有周期的: 2.其周期性与科技进步水平无关: 3.危机的前夕往往是一片祥和:1925-1927年,主流的媒体倾向于报道xxx公司营收超过xx亿元:无线收音机技术得到长足发展:商业银行扩张势头 ...
- 使用gevent包实现concurrent.futures.executor 相同的公有方法。组成鸭子类
类名不同,但公有方法的名字和提供的基本功能大致相同,但两个类没有共同继承的祖先或者抽象类 接口来规定他,叫鸭子类. 使并发核心池能够在 threadpoolexetor和geventpoolexecu ...
- 【SpringBoot】SpringBoot配置与单元测试(二)
SpringBoot项目创建参考[SpringBoot]SpringBoot快速入门(一) 本文介绍SpringBoot项目的POM文件.配置与单元测试 POM文件 1.SpringBoot的pom文 ...
- 【漫谈数据仓库】 如何优雅地设计数据分层 ODS DW DM层级
转载http://bigdata.51cto.com/art/201710/554810.htm 一.文章主题 本文主要讲解数据仓库的一个重要环节:如何设计数据分层!其它关于数据仓库的内容可参考之前的 ...
- 使用 Alibaba 的 Homebrew 镜像源进行加速
使用 Alibaba 的 Homebrew 镜像源进行加速 平时我们执行 brew 命令安装软件的时候,跟以下 3 个仓库地址有关: brew.git homebrew-core.git homebr ...
- 超级简单,把PuppyLinux安装到U盘
先说说使用感受:上网全是乱码!不支持中文 下载最新版puppylinux,从官网下载 现在U盘引导程序制作工具Unetbootin 打开下载的UNetbootin,进行下面的操作: 制作完毕后,修改U ...
- Properties的有序读写
使用java.util.Properties提供的类,读取properties文件的时候,读出来的是乱序的 如下边的情况 import java.io.*; import java.util.Arra ...
- 去掉WARN spring.jpa.open-in-view is enabled by default
使用springboot jpa,在运行项目时发现一个WARN WARN 11472 --- [ main] aWebConfiguration$JpaWebMvcConfiguration : sp ...