首页 > 其他分享 >JWT 生成token

JWT 生成token

时间:2023-05-09 16:45:22浏览次数:33  
标签:String JWT System 生成 secretKey token println import

 

 

package com.landray.kmss.cmex.ssooauth.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang.StringUtils;

import java.util.Calendar;
import java.util.Date;

public class TokenUtil {

    //过期时间:秒
    public static final int EXPIRE = 10;

    public static String getToken(String appKey, String secretKey) {
        if (StringUtils.isEmpty(secretKey)) {
            return null;
        }
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.SECOND, EXPIRE);
        //过期时间
        Date expireDate = nowTime.getTime();
        return Jwts.builder()
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                .setIssuedAt(new Date())
                .setIssuer(appKey)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }


    /**
     * 解析 jwt
     */
    public static boolean verifyToken(String token, String secretKey) {
        boolean validation = false;
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
            System.out.println("claims--->" + claims);
            validation = true;
        } catch (ExpiredJwtException e) {
            //此异常为生成的token过期异常
            System.out.println("token 已过期" + e.getClaims());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println(" Some other exception in JWT parsing !");
            e.printStackTrace();
        }

        return validation;
    }

    public static void main(String[] args) {
        String token = getToken("biBoard", "secret");
        System.out.println(token);
        String token1 = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2ODM2MTk4OTcsImlzcyI6ImJpQm9hcmQiLCJleHAiOjE2ODM2MTk5MDZ9.ZHw3LDlPtxtNXS5cM0LHyjyXqspde1BzDwNaVvT_s1k";
        boolean validation = verifyToken(token1, "secret");
        System.out.println(validation);
    }

}

  

 

标签:String,JWT,System,生成,secretKey,token,println,import
From: https://www.cnblogs.com/crushgirl/p/17385522.html

相关文章

  • 使用token上传git项目
    0、在github创建token2021年开始,取消远程推送时账号密码登录方式,转而用token代替,token可以在Github中生成可以把token直接添加远程仓库链接中,这样就可以避免同一个仓库每次提交代码都要输入token了已关联远程库前提下:gitremoteset-urloriginhttps://<your_token>@g......
  • C# Random类 伪随机数生成器
     Random类表示伪随机数生成器,它是一种能够产生满足某些随机性统计要求的数字序列的设备,其方法如下表:Random类方法方法说明Next已重载。返回随机数NextBytes用随机数填充指定字节数组的元素NextDouble返回一个介于0.0和1.0之间的随机数Sample返回一个介于......
  • 使用 Sa-Token 完成踢人下线功能
    一、需求在企业级项目中,踢人下线是一个很常见的需求,如果要设计比较完善的话,至少需要以下功能点:可以根据用户userId踢出指定会话,对方再次访问系统会被提示:您已被踢下线,请重新登录。可以查询出一个账号共在几个设备端登录,并返回其对应的Token凭证,以便后续操作。可以只踢出......
  • elementUI 多层结构动态生成el-form及校验
    如题,当整个el-form都是通过多层数据结构循环渲染出来的表单,那么每个el-form-item的prop和el-input、el-select等的v-model也是动态变量填充,怎么样才能内嵌rules校验呢?如下数据结构://form通过initData数据结构进行渲染constinitData=[{channel:'sms',title......
  • 使用Openapi Generator生成TS相关代码
    OpenapiGenerator是SwaggerCodegen的分支,但功能更加强大1.安装JDK【略】2.下载jar包wgethttps://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.5.0/openapi-generator-cli-6.5.0.jar-Oopenapi-generator-cli.jar或者Invoke-WebRequest-OutFileo......
  • python 小技巧, 列表生成式比 filter(lambda x:x>=0,data) 快, iteritems()方法,
    题目经timeit测试列表生成式比filter(lambdax:x>=0,data)快python2的dict的iteritems()方法,pyhton3可以看看有没有......
  • Keycloak: Requesting Token with Password Grant
    Keycloak:RequestingTokenwithPasswordGranthttps://www.appsdeveloperblog.com/keycloak-requesting-token-with-password-grant/Inthistutorial,youwilllearnhowtouseaPasswordGrantOAuth2authorizationflowtorequestanAccessTokenandaRefre......
  • PowerDesigner15在生成SQL時報錯Generation aborted due to errors detected during t
    1.用PowerDesigner15建模,在Database—>GenerateDatabase(或者用Ctrl+G快捷鍵)來生產sql語句,卻提示“Generationabort1.用PowerDesigner15建模,在Database—>GenerateDatabase(或者用Ctrl+G快捷鍵)來生產sql語句,卻提示“Generationabortedduetoerrorsdetectedduringthe......
  • 获取.Net程序集的PublicKeyToken
    C:\ProgramData\Microsoft\Windows\StartMenu\Programs\VisualStudio2022\VisualStudioToolsSN-TC:\Users\97627\.nuget\packages\system.data.sqlclient\4.8.5\ref\netcoreapp2.1\System.Data.SqlClient.dll#SN-TYou.dll   ......
  • 麻烦帮我生成一百个C开头的不带s和k的女性英文名,并同时提供中文译文
    答:1.Carina(卡琳娜)2.Clarissa(克莱丽莎)3.Cassidy(卡西迪)4.Charmaine(夏曼)5.Catherine(凯瑟琳)6.Corinne(科琳)7.Cecilia(塞西莉亚)8.Cynthia(辛西娅)9.Carmen(卡门)10.Callie(卡莉)11.Carry(凯瑞)12.Calla(卡拉)13.Colleen(科琳)14.......