您的位置 首页 java

Springboot 生成并发送 token

前置说明

最近在写一个 Springboot + vue 的后台管理版面,对相关知识点与实现进行记录。

本文记录前端向后端发送登录请求后,后端生成token,并存放在 cookie 中,返回到前端的过程。

代码示例

一、Maven依赖

 	<parent>
        <groupId>org.springframework. boot </groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    
    <dependencies>
        <dependency>
            <groupId>xxx.productLib</groupId>
            <artifactId>productLib-comm</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!--        token依赖-->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>
    </dependencies>
    < build >
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>  

在IDEA maven依赖引入过程中,可能会遇到JWT依赖无法自动引入的问题。可以在其他环境(另一台电脑)下下载依赖,将其直接放到开发环境的仓库里即可。

二、具体实现

1、TokenUtil

TokenUtil 对生成一个 token 的过程,进行了粗浅的拆分。

在这里我们只需要知道,token = header + payload + signature。其中

header 记录了 token 使用的算法,以及制作 token 的依赖。

payload 存放了 token 的签发者(iss)、签发时间(iat)、过期时间(exp)等以及一些我们需要写进token中的信息。

signature 将 Header 和 Playload 拼接生成一个 字符串 str=“eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyaWQiOjB9” ,使用HS256算法和我们提供的密钥(secret,服务器自己提供的一个字符串)对 str 进行加密生成最终的JWT,即我们需要的令牌(token)。

最后我们会发现,token 就是 xxxxx(header).xxxxx(payload).xxxx(signature) 的形式。

 import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.web.context. request .RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
/**
 * @author amber
 */
public class TokenUtil {
    /**
     * 签名算法使用的密钥,可以随机设置,但每个系统必须相同
     * 因为还需要密钥解码。
     */
    private static final String TOKEN_SECRET = "amberpaiosd@%#yq3e1";
    /**
     * 签发人
     */
    private static final String ISSUER = "test_amber";
    /**
     * 加密算法(需要输入密钥)
     */
    private static Algorithm JWTAlgorithm = null;
    /**
     * 验证器
     */
    private static JWTVerifier verifier = null;
    /**
     * 生成Token
     *
     * @return
     */
    public static String createToken() {
        String token = null;
        try {
            //过期时间10min
            Date expiresAt = new Date(System.currentTimeMillis() + 10L * 60L * 1000L);
            //签发日期
            Date issueAt = new Date(System.currentTimeMillis());
            token = JWT.create()
                    .withIssuer(ISSUER)
                    .withExpiresAt(expiresAt)
                    .withNotBefore(issueAt)
                    .withIssuedAt(issueAt)
                    .sign(getJWTAlgorithm());
        } catch (JWTCreationException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return token;
    }
    /**
     * 解码Token
     *
     * @param token
     * @return
     */
    public static DecodedJWT deToken(String token) {
        return getVerifier().verify(token);
    }
    /**
     * 每次前端请求后,刷新token
     *
     * @param oldToken 请求时携带的token
     * @return new token
     */
    public static String refreshToken(String oldToken) {
        DecodedJWT decodedJWT = deToken(oldToken);
        if (decodedJWT == null) {
            return null;
        }
        //如果还有2min过期
        if (decodedJWT.getExpiresAt().getTime() - System.currentTimeMillis() < 2L * 60L * 1000L) {
            return createToken();
        }
        return oldToken;
    }
    /**
     * 根据密钥生成签名算法
     *
     * @return
     */
    public static Algorithm getJWTAlgorithm() {
        if (JWTAlgorithm == null) {
            JWTAlgorithm = Algorithm.HMAC256(TOKEN_SECRET);
        }
        return JWTAlgorithm;
    }
    /**
     * 根据签名算法与签发人,生成验证器
     *
     * @return
     */
    public static JWTVerifier getVerifier() {
        if (verifier == null) {
            verifier = JWT.require(getJWTAlgorithm())
                    .withIssuer(ISSUER)
                    .build();
        }
        return verifier;
    }  

2、TokenController

将工具类中的 create 暴露在 controller 上,以便测试。

其实非常简单,将 cookie 放到 response 里返回就好了。可以理解为,cookie里面就是放了一个键值对。

 @RequestMapping(value = "/getToken", method = RequestMethod.POST)
    @ResponseBody
    public Object getTokenTest(@Valid User user, HttpServletRequest request, HttpServletResponse response) {
    
        String token = TokenUtil.createToken();
        Cookie cookie = new Cookie("token", token);
        //设置cookie失效时间
        cookie.setMaxAge(10 * 60);
        /**
          * 正常来说,cookie只能被创建它的应用调用,
  		  * 但setpath(根目录)后,可以在根目录以下的目录共享。
  		  * 此处设置就是在本次开发的系统内可以共享。
          */
        cookie.setPath("/");
        response.addCookie(cookie);
       
       return MyResponse.success("get Token!");
    }  

文章来源:智云一二三科技

文章标题:Springboot 生成并发送 token

文章地址:https://www.zhihuclub.com/190670.shtml

关于作者: 智云科技

热门文章

网站地图