欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在SpringBoot中使用JWT的实现方法

程序员文章站 2024-03-02 19:48:58
jwt简介 简介 json web token简称jwt, 是用于对应用程序上的用户进行身份验证的标记。也就是说, 使用 jwts 的应用程序不再需要保存有关其用户的...

jwt简介

简介

json web token简称jwt, 是用于对应用程序上的用户进行身份验证的标记。也就是说, 使用 jwts 的应用程序不再需要保存有关其用户的 cookie 或其他session数据。此特性便于可伸缩性, 同时保证应用程序的安全。

在身份验证过程中, 当用户使用其凭据成功登录时, 将返回 json web token, 并且必须在本地保存 (通常在本地存储中)。每当用户要访问受保护的路由或资源 (端点) 时, 用户代理(user agent)必须连同请求一起发送 jwt, 通常在授权标头中使用bearer schema。后端服务器接收到带有 jwt 的请求时, 首先要做的是验证token。

jwt的格式

jwt就是一个字符串,经过加密处理与校验处理的字符串,形式为:a.b.c

a由jwt头部信息header加密得到

b由jwt用到的身份验证信息json数据加密得到

c由a和b加密得到,是校验部分

怎样使用token?

可以放到http请求的请求头中,通常是authorization字段。

流程图

在SpringBoot中使用JWT的实现方法

jwt流程图.png

jwt 实战

加入maven jwt 依赖

<dependency>
 <groupid>io.jsonwebtoken</groupid>
 <artifactid>jjwt</artifactid>
 <version>0.9.1</version>
</dependency>

在application.proterties中加入配置

# 加密yan
jwt.secret=a0b1c2d3e4f5g6h7i8j9kalbmcndoepfq0r1s2t3u4v5w6x7y8z9
# tocken 过期时间,单位秒
jwt.expire=300
# 需要认证的url,多个url使用英文逗号,分割
jwt.authorised-urls=/apis/fis/redis/**

jwthelper工具类

import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;
import java.util.map;
import javax.servlet.http.httpservletrequest;
import com.alibaba.fastjson.jsonobject;
import io.jsonwebtoken.jwts;
import io.jsonwebtoken.signaturealgorithm;

public class jwthelper {
  private long expiration_time;
  private string secret;
  private final string token_prefix = "bearer";
  private final string header_string = "authorization";

  public jwthelper(string secret, long expire) {
    this.expiration_time = expire;
    this.secret = secret;
    system.out.println("正在初始化jwthelper,expire="+expire);
  }

  public jsonobject generatetoken(map<string, object> claims) {
    calendar c = calendar.getinstance();
    c.settime(new date());
    c.add(calendar.second, expiration_time.intvalue());
    date d = c.gettime();
    string jwt = jwts.builder()
        .setclaims(claims)
        .setexpiration(d)
        .signwith(signaturealgorithm.hs512, secret)
        .compact();
    jsonobject json = new jsonobject();
    json.put("token",token_prefix + " " + jwt);
    json.put("token-type", token_prefix);
    json.put("expire-time",new simpledateformat("yyyy-mm-dd hh:ss:mm").format(d) );
    return json;
  }

  public map<string, object> validatetokenandgetclaims(httpservletrequest request) {
    string token = request.getheader(header_string);
    system.out.println("token is:"+token);
    if (token == null) {
      return null;
    } 
    map<string, object> body = jwts.parser()
        .setsigningkey(secret)
        .parseclaimsjws(token.replace(token_prefix, ""))
        .getbody();
    return body;
  }
}

jwt过滤器jwtfilter

import java.io.ioexception;
import java.util.arrays;
import java.util.list;
import javax.servlet.filter;
import javax.servlet.filterchain;
import javax.servlet.filterconfig;
import javax.servlet.servletexception;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import org.springframework.http.httpstatus;
import org.springframework.util.antpathmatcher;

/**
 * jwt过滤器
 * 
 * @author 李庆海
 *
 */
public class jwtfilter implements filter {
  private jwthelper jwthelper;
  private list<string> urls = null;
   private static final org.springframework.util.pathmatcher pathmatcher = new antpathmatcher();
  public jwtfilter(jwthelper jwthelper, string[] authorisedurls) {
    this.jwthelper = jwthelper;
    urls = arrays.aslist(authorisedurls);
  }

  @override
  public void init(filterconfig filterconfig) throws servletexception {
    //springbeanautowiringsupport.processinjectionbasedonservletcontext(this, filterconfig.getservletcontext());
  }

  @override
  public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception {
    httpservletrequest httprequest = (httpservletrequest) request;
    httpservletresponse httpresponse = (httpservletresponse) response;
    httpresponse.setcharacterencoding("utf-8");
    httpresponse.setcontenttype("application/json; charset=utf-8");
    httpresponse.setheader("access-control-allow-origin", "*");
    if ("options".equals(httprequest.getmethod())) {
      httpresponse.setstatus(httpstatus.no_content.value()); // httpstatus.sc_no_content = 204
      httpresponse.setheader("access-control-allow-credentials", "true");
      httpresponse.setheader("access-control-allow-headers", "content-type, x-requested-with, token");
      httpresponse.setheader("access-control-allow-methods", "options,get,post,delete,put");
    }
    string spath = httprequest.getservletpath();
    try {
      // 验证受保护的接口
      for (string url : urls) {
        if (pathmatcher.match(url, spath)) {
          object token = jwthelper.validatetokenandgetclaims(httprequest);
          if (token != null) {
            chain.dofilter(request, response);
            return;
          }else{
             httpresponse.senderror(httpservletresponse.sc_unauthorized, "未授权或者授权已经过期");
             return;
          }
        }else{
          chain.dofilter(request, response);
          return;
        }
      }
    } catch (exception e) {
      e.printstacktrace();
    }
    chain.dofilter(request, response);
    return;
  }

  @override
  public void destroy() {

  }
}

配置jwt

import java.util.arraylist;
import java.util.list;
import org.springframework.beans.factory.annotation.value;
import org.springframework.boot.web.servlet.filterregistrationbean;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;

import cn.com.yd.fis.client.jwt.jwtfilter;
import cn.com.yd.fis.client.jwt.jwthelper;

@configuration
public class jwtconfig {

  @value("${jwt.secret}")
  private string secret;

  @value("${jwt.expire}")
  private long expire;

  @value("${jwt.authorised-urls}")
  private string[] authorisedurls;

  @bean
  public jwthelper jwthelperbean() {
    return new jwthelper(secret, expire);
  }

  @bean
  public filterregistrationbean basicfilterregistrationbean() {
    filterregistrationbean registrationbean = new filterregistrationbean();
    jwtfilter filter = new jwtfilter(jwthelperbean(), authorisedurls);
    registrationbean.setfilter(filter);
    list<string> urlpatterns = new arraylist<string>();
    urlpatterns.add("/*");
    registrationbean.seturlpatterns(urlpatterns);
    return registrationbean;
  }
}

在controller中使用jwt

此处仅为说明jwt的用法,在实际应用时可以根据具体的业务需要加入不同的或者更多的参数,一并作为claims进行参数传递。

import java.util.hashmap;
import java.util.map;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.restcontroller;
import cn.com.yd.fis.client.jwt.jwthelper;
import cn.com.yd.fis.client.util.jsonresult;
import io.swagger.annotations.api;
import io.swagger.annotations.apioperation;
import io.swagger.annotations.apiparam;

@restcontroller
@requestmapping("${api-url}/auth")
public class authorizecontroller {

  @autowired
  private jwthelper jwthelper;

  @postmapping("/login")
  public object login(string loginname,string password) throws exception {
    map<string, object> claims = new hashmap<string, object>();
    claims.put("loginname", loginname);
    if ("1".equals(password)) {
      return jsonresult.success(jwthelper.generatetoken(claims));
    } else {
      return jsonresult.fail("登录帐号或者登录密码错误");
    }
  }
}

辅助工具类jsonresult

import com.alibaba.fastjson.jsonobject;

public class jsonresult {
  public static jsonobject success(object obj) {
    jsonobject json = new jsonobject();
    json.put("state", true);
    json.put("msg", "成功");
    if (null != obj) {
      json.put("obj", obj);
    }
    return json;
  }

  public static jsonobject fail(object obj) {
    jsonobject json = new jsonobject();
    json.put("state", false);
    json.put("msg", "失败");
    if (null != obj) {
      json.put("obj", obj);
    }
    return json;
  }

  public static jsonobject tojsonobject(boolean state, string msg, object obj) {
    jsonobject json = new jsonobject();
    json.put("state", state);
    json.put("msg", msg);
    if (null != obj) {
      json.put("obj", obj);
    }
    return json;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。