springboot3+vue3融合项目实战-大事件文章管理系统-登录主逻辑,登录认证和JWT令牌

@PostMapping("/login")
    public Result<String> login(@Pattern(regexp ="^\\S{5,16}$" ) String username,@Pattern(regexp ="^\\S{5,16}$" ) String password){
        //根据用户名查询用户
        User loginUser = userService.findByUsername(username);
        //判断该用户是否存在
        if (loginUser == null) {
            return Result.error("用户名不存在");
        }
        //密码是否正确 loginUser对象中的password是加密之后的
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            return Result.success("jwt token令牌...");
        }
        return Result.error("密码错误");

    }

为了防止在未登录的情况下,可以访问到其他资源
所以我们要开启登录认证,
在这里插入图片描述
使用方法如下:
在这里插入图片描述
代码如下:
在这里插入图片描述
新建一个JwtTest类 代码如下:

package com.itheima;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;

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

public class JwtTest {
    @Test
    public  void testGen(){
        Map<String,Object> claims=new HashMap<>();
        claims.put("username","李二狗");
        claims.put("id",1);
        //生成jwt的代码
        String token= JWT.create()
                .withClaim("user",claims)//添加载荷
                .withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12))//添加过期时间
                .sign(Algorithm.HMAC256("itheima"));//指定算法,配置密钥

        System.out.println(token);
    }
    @Test
    public void testParse(){
        //定义字符串,模拟用户传来的token
        String token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +
                ".eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6IuadjuS6jOeLlyJ9LCJleHAiOjE3NDY0MDc0NzV9." +
                "HQ0g7SiGRzXqfjtXWOfcECeBLbtforTUmHZSHB7enRs";

        //
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256("itheima")).build();

        DecodedJWT decodedJWT=jwtVerifier.verify(token);//验证token,生成一个解析后的JWT对象
        Map<String, Claim>claims=decodedJWT.getClaims();
        System.out.println(claims.get("user"));

        //如果篡改了头部和载荷部分会验证失败
        //如果密钥改了,验证失败
        //token过期,也会失败

    }
}

运行如下:
在这里插入图片描述

下期继续~~~~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值