zoukankan      html  css  js  c++  java
  • JWT事例

    using System;
    using JWT;
    using JWT.Algorithms;
    using System.Collections;
    using System.Collections.Generic;
    using JWT.Serializers;
    namespace JwtTest
    {
    class Program
    {
    //Install-Package JWT -Version 2.4.2
    private static string secret = "fjxiaowtestadmin";
    static void Main(string[] args)
    {

    string token= SetJwtEncode();
    // Console.WriteLine("生成的token:"+ result);
    string model = GetJwtDecode(token);
    Console.WriteLine("用户信息:" + model);
    Console.ReadLine();
    }


    #region 生成JwtToken
    /// <summary>
    /// 生成JwtToken
    /// </summary>
    /// <param name="payload">不敏感的用户数据</param>
    /// <returns></returns>
    public static string SetJwtEncode()
    {

    //格式如下
    IDateTimeProvider provider = new UtcDateTimeProvider();
    var now = provider.GetNow();
    var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    //过期时间
    var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);

    var payload = new Dictionary<string, object>
    {
    { "exp", secondsSinceEpoch+3600 }, //3600秒后过期
    { "username","xiaowu" },
    { "password","111111" }
    };
    IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
    IJsonSerializer serializer = new JsonNetSerializer();
    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
    IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);

    var token = encoder.Encode(payload, secret);
    return token;
    }
    #endregion


    #region 获取实体
    /// 根据jwtToken 获取实体
    /// </summary>
    /// <param name="token">jwtToken</param>
    /// <returns></returns>
    public static string GetJwtDecode(string token)
    {
    try
    {
    IJsonSerializer serializer = new JsonNetSerializer();
    IDateTimeProvider provider = new UtcDateTimeProvider();
    IJwtValidator validator = new JwtValidator(serializer, provider);
    IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
    IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
    //token为之前生成的字符串
    var userInfo = decoder.DecodeToObject(token, secret, verify: true);
    //此处json为IDictionary<string, object> 类型
    string username = userInfo["username"].ToString(); //可获取当前用户名
    return "用户名是:" + username;

    }
    catch (TokenExpiredException)
    {
    Console.WriteLine("Token has expired");
    }
    catch (SignatureVerificationException)
    {
    Console.WriteLine("Token has invalid signature");
    }
    return "Error";
    }
    }
    #endregion
    }

  • 相关阅读:
    【实战】Weblogic xmldecoder反序列化Getshell
    【实战】JBOSS反序列化Getshell
    【实战】Tomcat管理后台Getshell
    【Python】二进制转ASCII码小脚本
    【实战】sqlmap显示有注入却无法爆出库名
    【总结】APP客户端渗透测试
    【总结】Struts2系列漏洞POC小结
    【Python】端口扫描脚本
    2020中国高校计算机大赛 华为云大数据挑战赛--热身赛--爬取天气数据
    2020中国高校计算机大赛 华为云大数据挑战赛--热身赛--赛题分析、数据理解
  • 原文地址:https://www.cnblogs.com/wugh8726254/p/12926415.html
Copyright © 2011-2022 走看看