菜鸟的博客

纵有疾风起,人生不言弃。

导航

登录认证-引入(JWT令牌)

//ArticleController
package com.di.bigevent.controller;

import com.di.bigevent.pojo.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @GetMapping("/list")
    public Result<String> list(){
        return Result.success("所有的文章数据....");
    }
}
//可以在浏览器用:locoalhost:8080/article/list,直接访问,所以需要令牌

//ArticleController
package com.di.bigevent.controller;

import com.di.bigevent.pojo.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @GetMapping("/list")
    public Result<String> list(){
        return Result.success("所有的文章数据....");
    }
}
//可以在浏览器用:locoalhost:8080/article/list,直接访问,所以需要令牌

引入工具:

<!--jwt令牌坐标-->
<dependency>
       <groupId>com.auth0</groupId>
       <artifactId>java-jwt</artifactId>
       <version>4.4.0</version>
</dependency>
~~~

~~~xml
 <!--单元测试的坐标-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

在test里,创建一个类

package com.di.bigevent;

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("id",1);
        claims.put("username","张三");
        //生成jwt代码
        String token = JWT.create()
                .withClaim("user",claims)//添加载荷
                .withExpiresAt(new Date(System.currentTimeMillis()+1000*60*60*12))//添加过期时间
                .sign(Algorithm.HMAC256("123456"));//指定算法,配置密钥

        System.out.println(token);
    }

    @Test
    public void testParse(){
        //定义字符串,模拟用户传递过来的token
        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoxLCJ1c2VybmFtZSI6IuW8oOS4iSJ9LCJleHAiOjE3MDYzMjMzMDV9.3YcLr0z6NAXZMVLxg3NbhsnBpP1ra8k022QenfCbF-k";

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

        DecodedJWT decodedJWT = jwtVerifier.verify(token);//验证token,生成一个解析后的JWT对象

        Map<String, Claim> claims = decodedJWT.getClaims();


        System.out.println(claims.get("user"));
    }
}

posted on 2024-08-03 15:27  hhmzd233  阅读(71)  评论(0编辑  收藏  举报