• asp.net JWT


    1、通过NuGet添加包

    2、写一个JWTHelper帮助类

     1 using JWT;
     2 using JWT.Algorithms;
     3 using JWT.Exceptions;
     4 using JWT.Serializers;
     5 using System;
     6 using System.Collections.Generic;
     7 
     8 namespace XXXXX.IM.API.Tool
     9 {
    10     public class JWTHelper
    11     {
    12         static IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//HMACSHA256加密
    13         static IJsonSerializer serializer = new JsonNetSerializer();//序列化和反序列
    14         static IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//Base64编解码
    15         static IDateTimeProvider provider = new UtcDateTimeProvider();//UTC时间获取
    16         const string secret = "8888888888888888888888888888888888888888";//服务端
    17         public static string CreateJWT(Dictionary<string, object> payload)
    18         {
    19             IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
    20             return encoder.Encode(payload, secret);
    21         }
    22         public static bool ValidateJWT(string token, out string payload, out string message)
    23         {
    24             bool isValidted = false;
    25             payload = "";
    26             try
    27             {
    28                 IJwtValidator validator = new JwtValidator(serializer, provider);//用于验证JWT的类
    29 
    30                 IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);//用于解析JWT的类
    31                 payload = decoder.Decode(token, secret, verify: true);
    32 
    33                 isValidted = true;
    34 
    35                 message = "token验证通过";
    36             }
    37             catch (TokenExpiredException ex)//当前时间大于负载过期时间(负荷中的exp),会引发Token过期异常
    38             {
    39                 message = "token过期";
    40             }
    41             catch (SignatureVerificationException ex)//如果签名不匹配,引发签名验证异常
    42             {
    43                 message = "token验证失败";
    44             }
    45             return isValidted;
    46         }
    47         public static long UnixTimeStampUTC(DateTime dateTime)
    48         {
    49             Int32 unixTimeStamp;
    50             DateTime zuluTime = dateTime.ToUniversalTime();
    51             DateTime unixEpoch = new DateTime(1970, 1, 1);
    52             unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
    53             return unixTimeStamp;
    54         }
    55     }
    56 }

    3、使用 

     1          //载荷(payload)
     2                 var payload = new Dictionary<string, object>
     3                 {
     4                     { "iss","XXXX.IM.API"},//发行人
     5                     { "exp",JWTHelper.UnixTimeStampUTC(DateTime.Now.AddHours(2))},//到期时间
     6                     { "sub", "XXXX.IM.API.Token" }, //主题
     7                     { "aud", "XXXX.IM" }, //用户
     8                     { "iat", DateTime.Now.ToString() }, //发布时间 
     9                     { "data" ,new { autor=" ",description=""} }
    10                 };
    11 
    12                 string JWTString = JWTHelper.CreateJWT(payload);
    13 
    14                 string ResultMessage;//解析完毕的消息
    15                 string Payload;//获取负载
    16                 var checkResult = JWTHelper.ValidateJWT(JWTString, out Payload, out ResultMessage);

     4、head中携带token

    新建一个js文件,例如:api-key-header-auth.js,位置随便放,我是放在scripts文件夹

     1 (function () {
     2     $(function () {
     3         $('#input_apiKey').show();
     4         $('#input_apiKey').on('change', function () {
     5             var key = this.value;
     6             if (key && key.trim() !== '') {
     7                 swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", key, "header"));
     8             }
     9         });
    10     });
    11 })();

      然后在SwaggerConfig.cs文件中找到如下代码取消注释即可 

    1 c.BasicAuth("basic")
    2                             .Description("Basic HTTP Authentication");
    3 
    4 c.InjectJavaScript(thisAssembly, "XXXX.IM.API.Scripts.api-key-header-auth.js");

      这里注意下文件位置写自己的位置,然后在页面中录入token就可以了

    感谢:

    https://www.jb51.net/article/172028.htm

    https://blog.csdn.net/weixin_39885282/article/details/79462443

    https://www.cnblogs.com/cr-cool/p/12448724.html

  • 相关阅读:
    [Bootstrap]7天深入Bootstrap(4)CSS组件
    [Bootstrap]7天深入Bootstrap(3)CSS布局
    [Bootstrap]7天深入Bootstrap(2)整体架构
    [Bootstrap]7天深入Bootstrap(1)入门准备
    如何快速给自己博客增加10000推荐量
    [Test] 单元测试艺术(2) 打破依赖,使用模拟对象,桩对象,隔离框架
    C#如何使用ES
    异步tcp通信——APM.Server 消息推送服务的实现
    异步tcp通信——APM.ConsoleDemo
    异步tcp通信——APM.Core 解包
  • 原文地址:https://www.cnblogs.com/PrintY/p/13572249.html
Copyright © 2020-2023  润新知