springboot集成JWT生成token

文章介绍了如何在SpringBoot项目中使用JWT进行用户认证,包括添加JWT依赖、创建生成和检验Token的工具类JwtUtil,以及自定义AuthFilter过滤器来验证HTTP请求中的Token。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导入依赖jar

        <!--JWT 依赖-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

创建生成token的工具类JwtUtil.java

package com.springboot.util;


import io.jsonwebtoken.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class JwtUtil {

    /**
     * 过期时间为5分钟
     */
    private static final long EXPIRE_TIME = 5 * 60 * 1000;
    /**
     * 加密密钥
     */
    private static final String KEY = "mayday";


    /**
     * 生成token
     *
     * @param userName 用户名
     * @return 返回 token
     */
    public static String createToken(String userName) {
        Map<String, Object> header = new HashMap<>();
        header.put("username", userName);
        /*
         * setExpiration:token过期时间  当前时间+有效时间
         *setSubject:用户名
         *setIssuedAt:token创建时间
         *signWith:加密方式
         */
        JwtBuilder jwtBuilder = Jwts.builder().
                setSubject(userName).
                setHeader(header).
                signWith(SignatureAlgorithm.HS256, KEY).
                setIssuedAt(new Date()).
                setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME));
        return jwtBuilder.compact();
    }


    /**
     * 检验token是否合法
     */
    public static int checkToken(String token) {
        Claims claims = null;
        try {
            /*
             * token过期后,会抛出ExpiredJwtException异常,
             * 通过这个来判定token过期,0验证成功,-1验证失败 1是过期
             */
            claims = Jwts.parser().setSigningKey(KEY).parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            return 1;
        }
        if ("admin".equals(claims.getSubject())) {
            return 0;
        }
        return -1;
    }
}

自定义一个过滤器AuthFilter.java

此过滤器的作用是《过滤掉除登录(或注册)以外的所有请求》,因为生成token需要先验证用户名,所以要过滤掉登录和注册

package com.springboot.fileter;

import cn.hutool.json.JSONObject;
import com.springboot.util.JwtUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;


public class AuthFilter implements Filter {

    private JwtUtil jwtUitl = new JwtUtil();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        JSONObject jsonObject = new JSONObject();
        String requestURI = ((HttpServletRequest) servletRequest).getRequestURI();
        if (requestURI != null) {
            /*过滤掉登录*/
            if (requestURI.contains("/login")) {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            } else {
                String token = ((HttpServletRequest) servletRequest).getHeader("token");
                if (!"".equals(token) && null != token) {
                    //token验证结果
                    int flag = JwtUtil.checkToken(token);
                    if (flag == 1) {
                        jsonObject.put("500", "token已过期");
                    }
                    if (flag == -1) {
                        jsonObject.put("500", "用户信息校验失败");
                    }
                    if (flag == 0) {
                        //验证成功,放行
                        filterChain.doFilter(servletRequest, servletResponse);
                        return;
                    }
                } else {
                    jsonObject.put("500", "未携带token信息");
                }
            }
        }
        servletResponse.setContentType("application/json");
        servletResponse.setCharacterEncoding("utf-8");
        PrintWriter writer = servletResponse.getWriter();
        writer.write(jsonObject.toString());
        writer.flush();
        writer.close();
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}

配置并注册自己的过滤器FilterConfig .java

package com.springboot.config;

import com.springboot.fileter.AuthFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean<AuthFilter> registAuth() {
        FilterRegistrationBean<AuthFilter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
        filterFilterRegistrationBean.setFilter(new AuthFilter());//注册自己的过滤器
        filterFilterRegistrationBean.setName("token-Auth");
        filterFilterRegistrationBean.addUrlPatterns("/*");//拦截所有请求
        filterFilterRegistrationBean.setOrder(1);//优先执行,数月小,优先级越高
        return filterFilterRegistrationBean;
    }
}

登录接口及实现类

package com.springboot.service;

import com.springboot.entity.UserInfo;

public interface LoginService {

    String login(UserInfo userInfo);
}

package com.springboot.service.impl;

import com.springboot.entity.UserInfo;
import com.springboot.service.LoginService;
import com.springboot.util.JwtUtil;
import org.springframework.stereotype.Service;


@Service("LoginService")
public class LoginServiceImpl implements LoginService {
    @Override
    public String login(UserInfo userInfo) {
        if ("admin".equals(userInfo.getUserName()) && "123456".equals(userInfo.getPassWord())) {
            /*
             *登录成功并且生成返回的额token 
             */
            return JwtUtil.createToken(userInfo.getUserName());
        }
        return "noThisUser";
    }
}

登录的controller

package com.springboot.controller;

import com.springboot.entity.UserInfo;
import com.springboot.service.LoginService;
import com.springboot.util.ReturnMsg;
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.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    LoginService loginService;

    @PostMapping("/login")
    public ReturnMsg skill(@RequestBody UserInfo userInfo) {
        String token = loginService.login(userInfo);
        if ("noThisUser".equals(token)) {
            return new ReturnMsg(true, "0001", "用户名不存在", token);
        }
        return new ReturnMsg(true, "0000", "登录成功", token);
    }


    /**
     * 用来测试token的
     * @return
     */
    @GetMapping("/test")
    public ReturnMsg test() {
        return new ReturnMsg(true, "0000", "请求成功", "");
    }
}


测试生成token

在这里插入图片描述

测试别的请求并且不带token

看返回结果,返回未携带token信息
{ "500": "未携带token信息" }
在这里插入图片描述

测试别的请求并且携带token

在这里插入图片描述

成功返回结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值