不懂就学,什么是JWT?( 二 )


那么Application Server如何进行验证呢?可以利用JWT前两段,用同一套哈希算法和同一个secret计算一个签名值,然后把计算出来的签名值和收到的JWT第三段比较,如果相同则认证通过 。
JWT的优点

  • json格式的通用性,所以JWT可以跨语言支持,比如Java、JavaScript、php、Node等等 。
  • 可以利用Payload存储一些非敏感的信息 。
  • 便于传输,JWT结构简单,字节占用小 。
  • 不需要在服务端保存会话信息,易于应用的扩展 。
怎么使用JWT首先引入Maven依赖 。
<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency>创建工具类,用于创建jwt字符串和解析jwt 。
@Componentpublic class JwtUtil {@Value("${jwt.secretKey}")private String secretKey;public String createJWT(String id, String subject, long ttlMillis, Map<String, Object> map) throws Exception {JwtBuilder builder = Jwts.builder().setSubject(null) // 发行者.setId(id).setSubject(subject).setIssuedAt(new Date()) // 发行时间.signWith(SignatureAlgorithm.HS256, secretKey) // 签名类型 与 密钥.compressWith(CompressionCodecs.DEFLATE);// 对载荷进行压缩if (!CollectionUtils.isEmpty(map)) {builder.setClaims(map);}if (ttlMillis > 0) {builder.setExpiration(new Date(System.currentTimeMillis() + ttlMillis));}return builder.compact();}public Claims parseJWT(String jwtString) {return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwtString).getBody();}}接着在application.yml配置文件配置jwt.secretKey 。
## 用户生成jwt字符串的secretKeyjwt:secretKey: ak47接着创建一个响应体 。
public class BaseResponse {private String code;private String msg;public static BaseResponse success() {return new BaseResponse("0", "成功");}public static BaseResponse fail() {return new BaseResponse("1", "失败");}//构造器、getter、setter方法}public class JwtResponse extends BaseResponse {private String jwtData;public static JwtResponse success(String jwtData) {BaseResponse success = BaseResponse.success();return new JwtResponse(success.getCode(), success.getMsg(), jwtData);}public static JwtResponse fail(String jwtData) {BaseResponse fail = BaseResponse.fail();return new JwtResponse(fail.getCode(), fail.getMsg(), jwtData);}//构造器、getter、setter方法}接着创建一个UserController:
@RestController@RequestMapping("/user")public class UserController {@Resourceprivate UserService userService;@RequestMapping(value = https://www.isolves.com/it/cxkf/bk/2021-12-07/"/login", method = RequestMethod.POST)public JwtResponse login(@RequestParam(name = "userName") String userName,@RequestParam(name = "password") String passWord){String jwt = "";try {jwt = userService.login(userName, passWord);return JwtResponse.success(jwt);} catch (Exception e) {e.printStackTrace();return JwtResponse.fail(jwt);}}}还有UserService:
@Servicepublic class UserServiceImpl implements UserService {@Resourceprivate JwtUtil jwtUtil;@Resourceprivate UserMapper userMapper;@Overridepublic String login(String userName, String passWord) throws Exception {//登录验证User user = userMapper.findByUserNameAndPassword(userName, passWord);if (user == null) {return null;}//如果能查出,则表示账号密码正确,生成jwt返回String uuid = UUID.randomUUID().toString().replace("-", "");HashMap<String, Object> map = new HashMap<>();map.put("name", user.getName());map.put("age", user.getAge());return jwtUtil.createJWT(uuid, "login subject", 0L, map);}}还有UserMapper.xml:
@Mapperpublic interface UserMapper {User findByUserNameAndPassword(@Param("userName") String userName, @Param("passWord") String passWord);}<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="io.github.yehongzhi.jwtdemo.mapper.UserMapper"><select id="findByUserNameAndPassword" resultType="io.github.yehongzhi.jwtdemo.model.User">select * from user where user_name = #{userName} and pass_word = #{passWord}</select></mapper>user表结构如下:
不懂就学,什么是JWT?

文章插图
 
启动项目,然后用POSTMAN请求login接口 。
不懂就学,什么是JWT?

文章插图
 
返回的jwt字符串如下:
eyJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNqqVspLzE1VslJ6OnHFsxnzX67coKSjlJgOFDEzqAUAAAD__w.qib2DrjRKcFnY77Cuh_b1zSzXfISOpCA-g8PlAZCWoU


推荐阅读