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 map = new HashMap<>();
        return createJWT(id, subject, map);
    }

    /**
    * 签发token
    * @param id
    * @param subject
    * @param map
    * @return
    */
    public String createJWT(String id, String subject, Map 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 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 {
    /**
    * 返回码
    */
    private int code;
    /**
    * 提示信息
    */
    private String msg;
    /**
    * 具体内容(返回的数据)
    */
    private T data;
    /**
    * Token信息
    */
    private String token;
}

你可能感兴趣的:(JWT)