生成token

token作用:可以让网页在一段时间后记住密码和账号

1.SpringBoot 集成 JWT(token),
2.拦截器自动验证验证 token 是否过期
3.token 自动刷新(单个 token 刷新机制,保证活跃用户不会掉线)
4.标准统一的 RESTFul 返回体数据格式
5.异常统一拦截处理

参考https://blog.csdn.net/jarvan5/article/details/113789133

依赖:

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.10.3</version>
</dependency>

代码:

package com.shop.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;


public class TokenUtil {
    private static final String TOKEN_SECRET = "$J#F@f@G!D";

    public static String getToken(String username, String password) {

        String token = "";
        try {
            //过期时间
            Calendar insCalendar = Calendar.getInstance();
            insCalendar.add(Calendar.SECOND, 800);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username,password信息,生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("username", username)
                    .withClaim("password", password)
                    .withExpiresAt(insCalendar.getTime())
                    .sign(algorithm);
        } catch (Exception e) {
            System.out.println("*****");
            e.printStackTrace();
            return null;
        }
        return token;
    }
}

使用例子:

controller层:
	@PostMapping("/login")
    public CommonResult<Map> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        return loginService.login(username, password);
    }

service层:
	public CommonResult<Map> login(String username, String password) {
        Integer rows = loginMapper.login(username, password);
        Map<String, String> data = new HashMap<>();
        if (rows == 1) {
            data.put("token", TokenUtil.getToken(username, password));
            return new CommonResult<>(200, "success", data);
        }
        return new CommonResult<>(400, "账号或密码错误", data);
    }
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值