SpringBoot集成JWT

文章展示了如何在Java应用中使用JWT(JSONWebTokens)进行权限管理。通过创建TokenUtils工具类生成和验证JWT,设置过期时间和密钥。同时,文章还介绍了登录拦截器的实现,检查请求头中的token并处理不同类型的验证异常,如无效签名、过期或算法不匹配。最后,提到了在SpringMVC中配置拦截器的步骤。

1.导入依赖

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

2.创建TokenUtils

​import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.ethan.exam_ms.entity.User;
import com.ethan.exam_ms.exception.ServiceException;
​
import java.util.Calendar;
import java.util.Date;
​
public class TokenUtils {
    //密钥
    public static final String SECRET = "areyoucrazy?pojie?bukenengde?";
    //过期时间:秒
    public static final int EXPIRE = 30;
    public static String getToken(String id,String username){
        Calendar nowTime = Calendar.getInstance();
        //过期时间
        nowTime.add(Calendar.SECOND, EXPIRE);
        Date expireDate = nowTime.getTime();
        String token = JWT.create()
                //这是在设置第二部分信息,不要设置密码之类的,因为这些信息可以通过浏览器获取
                //用户id
                .withClaim("id", id)
                //用户名
                .withClaim("username",username)
                //创建token的时间
                .withIssuedAt(new Date())//签名时间
                //设置token的过期时间
                .withExpiresAt(expireDate)//过期时间
                //设置第一部分
                .sign(Algorithm.HMAC256(SECRET));//签名
        return token;
​
    }
    /**
     * 验证token合法性 成功返回token
     */
    public static DecodedJWT verify(String token) throws ServiceException {
        if(StrUtil.isBlank(token)){
            throw new ServiceException("token不能为空");
        }
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SECRET)).build();
        return build.verify(token);
    }
​
​
}

3.登录拦截器

(1)没有统一返回类,用map封装


                
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ethan_Zhuo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值