文章目录
前言
简单JWT入门案例
项目目录结构如下:
一、JWT是什么?
JWT(json web token) 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。
二、使用步骤
1.引入库
代码如下(示例):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
</dependencies>
2.先构建Utils工具类
package com.hh.userservicejwt.utils;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Map;
public class JWTUtils {
private static final String SING = "abcdefg";
/**
* 生成token header.payload.sing
*/
public static String getToken(String jsonObject){
Calendar istance = Calendar.getInstance();
istance.add(Calendar.DATE,1);
JWTCreator.Builder builder = JWT.create();
builder.withSubject(jsonObject);
String token = builder.withExpiresAt(istance.getTime())
.sign(Algorithm.HMAC256(SING));
return token;
}
/**
* 验证token 验证合法性 并返回值
*/
public static DecodedJWT verify(String token){
return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
}
/**
* 获取token信息 可以由验证的方法代替(可以不写)
*/
public static DecodedJWT getTokenInfo(String token){
DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
return verify;
}
}
3.在构建config配置
package com.hh.userservicejwt.config;
import com.hh.userservicejwt.interceptor.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JWTInterceptor())
.addPathPatterns("/getData")
.excludePathPatterns("/toLogin");
}
}
4.在创建过滤器用来检验Token令牌。
package com.hh.userservicejwt.interceptor;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hh.userservicejwt.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
public class JWTInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Map<String,Object> map = new HashMap<>();
String token = request.getHeader("token");//获取请求头中的令牌
try{
JWTUtils.verify(token);
return true;
}catch (SignatureVerificationException e){
e.printStackTrace();
map.put("msg","无效签名!");
}catch (TokenExpiredException e){
e.printStackTrace();
map.put("msg","token过期!");
}catch (AlgorithmMismatchException e){
e.printStackTrace();
map.put("msg","token算法不一致!");
} catch (Exception e){
e.printStackTrace();
map.put("msg","token无效!");
}
map.put("state",false);//设置状态
//将map 转换json jackson
String json = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
return false;
}
}
5.创建Controller中的数据
package com.hh.userservicejwt.controller;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hh.userservicejwt.utils.JWTUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
public class UserController {
@RequestMapping("/login")
public String login() {
return "login";
}
@RequestMapping("/toLogin")
public String toLogin(HttpServletRequest request, HttpServletResponse response,
@RequestParam("username") String username, @RequestParam("password") String password) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("username",username);
jsonObject.put("password",password);
try {
String token = JWTUtils.getToken(jsonObject.toJSONString());
response.setHeader("token",token);
request.setAttribute("token",token);
return "success";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@RequestMapping("/getData")
@ResponseBody
public String getData(@RequestHeader("token") String token) {
DecodedJWT tokenInfo = JWTUtils.getTokenInfo(token);
String subject = tokenInfo.getSubject();
return subject;
}
}
6.创建html登录页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="/toLogin">
<div>
<input type="text" name="username" placeholder="请输入账号" />
<input type="password" name="password" placeholder="请输入密码" />
</div>
<div>
<input type="submit" name="提交" />
<input type="reset" name="重置">
</div>
</form>
<script th:src="@{/jquery-3.1.1.min.js}"></script>
<script>
</script>
</body>
</html>
7.登录成功后,获取Token令牌,并且下次请求的时候带上令牌,放到请求头中,并去获取资源。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录成功</title>
</head>
<div>
登录成功
</div>
<div>
<button onclick="getInfo();">获取当前用户信息</button>
</div>
<div id="userInfo">
</div>
<body>
<input type="hidden" id="token" name="token" th:value="${token}">
<script th:src="@{/jquery-3.1.1.min.js}"></script>
<script th:src="@{/layui/layui.js}"></script>
<script th:src="@{/loadingAjax.js}"></script>
<script>
var token = $("#token").val();
var form;
layui.use(['form', 'upload', 'laydate'], function () {
form = layui.form;
console.log(token);
});
function getInfo() {
$.ajax({
url:"/getData"
, method: "get"
, headers: {"token":token}
, success: function (data) {
$("#userInfo").html(data);
}
})
}
</script>
</body>
</html>
大致如此,谢谢大家。
总结
人生物语:有了精神才会有精神生活。什么是精神?爱是一种精神,它支撑起我们人类情感的天空;奉献是一种精神,它塑造了多少值得敬仰的具体人格;牺牲是一种精神,它写就的是人生的意义。懂得爱而去爱,懂得奉献而去奉献,知道牺牲而勇于牺牲,这就是精神生活,这就是有了精神的精神生活。