120.JWT(二):springboot整合jwt实例

本实例码云地址:

https://gitee.com/cxy-xupeng/springboot_jwt.git

 

1.先创建一个springboot项目

 

2.引入依赖

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

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>

        <!--引入lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!--druid-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.19</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

 

3.修改配置文件

server.port=8989

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/jwt?characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=xp880000

mybatis.type-aliases-package=com.xupeng.entity
mybatis.mapper-locations=classpath:mapper/*.xml

logging.level.com.xupeng.dao=debug

 

4.数据库创建一个jwt表格

创建一个user表,内容随便给一个

 

5.创建eneity

User:

@Data
@Accessors(chain = true)
public class User {
    private String id;
    private String name;
    private String password;
}

 

6.创建dao层

UserDao:

@Mapper
public interface UserDao {
    User login(User user);
}

UserDaoMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xupeng.dao.UserDao">
    <select id="login" parameterType="User" resultType="User">
        select * from user where name = #{name} and password = #{password}
    </select>
</mapper>

 

7.创建service层

UserService:

public interface UserService {
    User login(User user);
}

UserServiceImpl:

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public User login(User user) {
        User user1 = userDao.login(user);

        if(user1 != null){
            return user1;
        }

        throw new RuntimeException("登录失败");
    }
}

 

8.jwt工具类

JwtUtils:

package com.xupeng.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

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

/**
 * [jwt工具类]
 *
 * @author : [xupeng]
 * @version : [v1.0]
 * @createTime : [2021/6/10 15:28]
 */
public class JwtUtils {

    //签名,大家自定义
    private static final String SIGN = "xupeng";

    /**
     * 生成token header.payload.sign
     */
    public static String getToken(Map<String, String> map) {

        Calendar calendar = Calendar.getInstance();

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //设置token有效时间,默认5分钟
        calendar.add(Calendar.MINUTE, 5);

        //payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        //sign
        String token = builder.withExpiresAt(calendar.getTime())//指定令牌过期时间
                .sign(Algorithm.HMAC256(SIGN));


        return token;
    }

    /**
     * 验证token合法性
     */
    public static DecodedJWT verify(String token) {
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        return decodedJWT;
    }

    /**
     * 获取token的信息
     */
    public static DecodedJWT getTokenInfo(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        return verify;
    }
}

 

9.编辑过滤器

JwtIntercept:

package com.xupeng.intercept;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xupeng.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JwtIntercept implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap<>();
        //获取请求投诉中的token
        String token = request.getHeader("token");

        try{
            JwtUtils.verify(token);
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg","无效签名");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","token算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效");
        }
        map.put("state", false);
        //将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}

 

10.编辑配置文件

InterceptorConfig:

package com.xupeng.config;

import com.xupeng.intercept.JwtIntercept;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new JwtIntercept())
                .addPathPatterns("/user/test")  //需要token验证的都这样写
                .excludePathPatterns("/user/login"); //不需要token验证的都这样写

    }
}

 

11.controller类

UserController:

package com.xupeng.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xupeng.entity.User;
import com.xupeng.service.UserService;
import com.xupeng.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/user/login")
    public Map<String, Object> login(User user) {
        log.info("用户名:" + user.getName());
        log.info("密码:" + user.getPassword());
        Map<String, Object> map = new HashMap<>();

        try {
            User user1 = userService.login(user);

            Map<String, String> payload = new HashMap<>();
            payload.put("id", user1.getId());
            payload.put("name", user1.getName());
            //生成jwt令牌
            String token = JwtUtils.getToken(payload);
            map.put("token", token);

            map.put("state", true);
            map.put("msg", "成功");
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", "失败");
        }
        return map;
    }

    @PostMapping("/user/test")
    public Map<String, Object> test(String token) {
        Map<String, Object> map = new HashMap<>();
        //处理自己业务逻辑

        map.put("state", true);
        map.put("msg", "成功");
        return map;
    }

}

 

10.测试

 

注意,token一定要放在header里面,在请求头内:

至此一个简单的jwt就完成

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

鹏哥哥啊Aaaa

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

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

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

打赏作者

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

抵扣说明:

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

余额充值