在springboot框架下使用JWT对用户信息进行加密,从而实现单点登录等业务。在用户登录成功时将token发送到前端,由前端进行保存,每次前端发送请求时在请求头中加入token。
这里将三层架构进行省略,只写出有关JWT的部分。
导入依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.14.0</version>
</dependency>
JWT工具类
在工具类中规定JWT的密钥、加密算法、令牌失效时间
package com.jwt.util;
import java.util.Calendar;
import java.util.Map;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
public class JWTUtil {
private static String TOKEN = "123456";
/**
* 生成token
* @param map
* @return
*/
public static String getToken(Map<String, String> map) {
JWTCreator.Builder builder = JWT.create();
map.forEach((k,v)->{
builder.withClaim(k, v);
});
Calendar instance = Calendar.getInstance();
instance.add(Calendar.MINUTE, 10);
builder.withExpiresAt(instance.getTime());
return builder.sign(Algorithm.HMAC256(TOKEN)).toString();
}
/**
* 验证token
* @param token
*/
// public static void verify(String token) {
// JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
// }
/**
* 获取token中的payload
* @param token
* @return
*/
public static DecodedJWT verify(String token) {
return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
}
}
JWT拦截器
验证令牌,抛出异常
package com.jwt.interceptors;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
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.jwt.util.JWTUtil;
public class JWTInterceptors 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 {
JWTUtil.verify(token);// 验证令牌
return true;//直接放行
} catch (SignatureVerificationException e) {
e.printStackTrace();
map.put("msg", "无效签名");
}catch (TokenExpiredException e) {
e.printStackTrace();
map.put("msg", "令牌过期");
}catch (AlgorithmMismatchException e) {
e.printStackTrace();
map.put("msg", "把算法不一致");
}catch (Exception e) {
e.printStackTrace();
map.put("msg", "令牌无效");
}
map.put("state", false);
// map响应到前端
String json = new ObjectMapper().writeValueAsString(map);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
return false;
}
}
拦截器配置
配置哪些接口需要令牌验证,哪些接口可以直接放行
package com.jwt.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.jwt.interceptors.JWTInterceptors;
@Configuration
public class InterceptorsConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JWTInterceptors())
.addPathPatterns("/user/test")// 需要拦截的接口 /** 全部接口
.excludePathPatterns("/user/login"); // 可以放行的接口
}
}
实体类
public class User {
private Integer userId;
private String username;
private String password;
public User() {
super();
}
}
数据层
省略
服务层
实现类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.jwt.dao.UserDao;
import com.jwt.pojo.User;
import com.jwt.service.UserService;
@Service
@Transactional
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public User login(User user) {
User userLogin = userDao.login(user);
if(userLogin!=null) {
return userLogin;
}
throw new RuntimeException("登录失败");
}
}
控制层
package com.jwt.controller;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.jwt.pojo.User;
import com.jwt.service.UserService;
import com.jwt.util.JWTUtil;
@RestController
@RequestMapping("/user")
public class UserController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
@GetMapping("/login")
public Map<String, Object> login(@RequestParam("name") String name, @RequestParam("password") String password) {
Map<String, Object> map = new HashMap<String, Object>();
LOGGER.info("用户名:[{}]", name);
LOGGER.info("密码:[{}]", password);
User user = new User(name, password);
try {
User userLogin = userService.login(user);
Map<String, String> payload = new HashMap<>();
payload.put("id", userLogin.getUserId().toString());
payload.put("name", userLogin.getUsername());
payload.put("password", userLogin.getPassword());
// 生成JWT令牌
String token = JWTUtil.getToken(payload);
map.put("state", true);
map.put("msg", "登录成功");
map.put("token", token);
} catch (Exception e) {
map.put("state", false);
map.put("msg", e.getMessage());
}
return map;
}
/**
* 处理业务逻辑
* @return
*/
@PostMapping("/test")
public Map<String, Object> test() {
Map<String, Object> map = new HashMap<>();
map.put("state", true);
map.put("msg", "请求成功");
return map;
}
}
/**
* 解析token
*
* @return
*/
@RequestMapping(value = "/update/version", method = RequestMethod.GET)
public ResultMessage updateVersion(HttpServletRequest request) {
String token = request.getHeader("token");
DecodedJWT verify = JWTUtil.verify(token);
String id = verify.getClaim("id").asString();
String latestVersion = verify.getClaim("latestVersion").asString();
int res = userService.updateVersion(Integer.parseInt(id), Integer.parseInt(latestVersion));
if (res > 0) {
return new ResultMessage(true, "版本更新成功", null);
}
return new ResultMessage(false, "版本更新失败", null);
}
测试
登录成功后返回生成的令牌
在请求头中写入token
解析token获取数据
@Test
public void test() {
// 创建验证对象
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("123456")).build();
DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTY1NTE5NzksInVzZXJJZCI6MSwidXNlcm5hbWUiOiJoengifQ.HCrcaJmblh0P7hL7-C7q-I4FzAjOFyZOJtoH-yfDcTw");
System.out.println(verify.getClaim("userId").asInt());
System.out.println(verify.getClaim("username").asString());
}