第十次web作业

登录校验-JWT令牌

1.引入依赖

<!--        JWT令牌-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

2测试 

//生成Jwt
    @Test
    public void testGenJwt(){
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",1);
        claims.put("name","Tom");

        String jwt = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256,"itwww")//签名算法
                .setClaims(claims) //自定义的内容(载荷)
                .setExpiration(new Date(System.currentTimeMillis() + 3600*1000)) //设置有效期为1h
                .compact();

        System.out.println(jwt);
    }

    //解析Jwt
    @Test
    public void testParseJwt(){
        Claims claims = Jwts.parser()
                .setSigningKey("itwww")
                .parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiVG9tIiwiaWQiOjEsImV4cCI6MTcxODEyMTc3M30.t9DQLQL-H55ojGC4Hyl4evscZPZ18mcOAXAPj8nco1U")
                .getBody();
        System.out.println(claims);
    }

运行单元测试生成Jwt令牌:

package com.wust.controller;

import com.wust.pojo.Emp;
import com.wust.pojo.Result;
import com.wust.service.EmpService;
import com.wust.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

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

@Slf4j
@RestController
public class LoginController {

    @Autowired
    private EmpService empService;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp){
        log.info("员工登录:{}",emp);
        Emp e = empService.login(emp);

        //登陆成功,生成令牌,下发令牌
        if(e != null){
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",e.getId());
            claims.put("name",e.getName());
            claims.put("username",e.getUsername());

            String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登陆界面的员工信息
            return Result.success(jwt);
        }

        //登录失败,返回错误信息
        return Result.error("用户名或密码错误");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值