JWT

Posted yxmhl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JWT相关的知识,希望对你有一定的参考价值。

JwtUtil

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Getter
@Setter
@ConfigurationProperties("jwt.config")
public class JwtUtil {
    private String key; //加密key
    private long ttl;//过期时间
    private String name;//token名字


    /**
    * 简单签发token
    * @param id
    * @param subject
    * @return
    */
    public String createJWT(String id, String subject) {
        Map<String, Object> map = new HashMap<>();
        return createJWT(id, subject, map);
    }

    /**
    * 签发token
    * @param id
    * @param subject
    * @param map
    * @return
    */
    public String createJWT(String id, String subject, Map<String, Object> map) {
        long now = System.currentTimeMillis();
        long exp = now + ttl;
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key);
        //保存自定义信息
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            jwtBuilder.claim(entry.getKey(), entry.getValue());
        }
        if (ttl > 0) {
            jwtBuilder.setExpiration(new Date(exp));
        }
        return jwtBuilder.compact();
    }

    /**
    * 解析token
    * @param token
    * @return
    */
    public Claims parseJWT(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token).getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }
}

JwtInterceptor

import com.alibaba.fastjson.JSON;
import com.ayanami.backend.dto.Result;
import com.ayanami.backend.util.JwtUtil;
import com.ayanami.backend.util.ResultEnum;
import com.ayanami.backend.util.ResultUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //通过request获取请求token信息
        String token = request.getHeader(jwtUtil.getName());
        if (token == null || token.equals("")) {
            //通过response返回错误信息
            returnJson(response, ResultUtil.error(ResultEnum.UNAUTHENTICATED));
            return false;
        }
        //解析token
        Claims claims = jwtUtil.parseJWT(token);
        if (claims == null) {
            returnJson(response, ResultUtil.error(ResultEnum.UNAUTHENTICATED));
            return false;
        }
        //取出原token信息生成新token,保持登陆
        token = jwtUtil.createJWT(claims.getId(), claims.getSubject());
        request.setAttribute("token", token);
        return true;
    }

    /**
    * 向response中写入json字符串
    * @param response
    * @param result
    */
    private void returnJson(HttpServletResponse response, Result result) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null ;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.append(JSON.toJSONString(result));
        }
    }
}

Result

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Result<T> {
    /**
    * 返回码
    */
    private int code;
    /**
    * 提示信息
    */
    private String msg;
    /**
    * 具体内容(返回的数据)
    */
    private T data;
    /**
    * Token信息
    */
    private String token;
}

以上是关于JWT的主要内容,如果未能解决你的问题,请参考以下文章

OkHttpInterceptor 从 kotlin 拦截器导航到登录片段

AttributeError: ‘str‘ object has no attribute ‘decode‘解决方法

《代码实例》jwt参与用户凭证方式,生成jwt,security整合jwt

放置jwt.sign代码时出现JWT错误

我已经在 Spring Boot 代码中实现了 JWT 令牌安全性。如何在我的代码中的任何地方获取 jwt 令牌?需要保存审核

Jwt 代码在 .NET Core 2 上不起作用