c#语法JWT请求接口

发布时间 2023-12-28 11:01:40作者: 人渴浸思茶
NuGet下载System.IdentityModel.Tokens.Jwt包
下面是获取token,需要引用对应的jwt


using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;


private void button1_Click(object sender, EventArgs e) { string secretId = "a1bc3900ba8c48b3"; // 发行人 string secretKey = "3c21642c3d8f43fc9f28ea608709cac5"; // 密钥 string token = CreateToken(secretId, secretKey); textBox1.Text = token; // 将令牌显示到文本框中 } public static string CreateToken1(string secretId, string secretKey) { // 创建 JWT 对象 var tokenDescriptor = new SecurityTokenDescriptor { Subject = new System.Security.Claims.ClaimsIdentity(new[] { new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, secretId) }), Expires = DateTime.UtcNow.AddHours(1), // 设置过期时间 SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)), SecurityAlgorithms.HmacSha256Signature) }; // 将 JWT 对象转换为 JSON 字符串 var json = JsonConvert.SerializeObject(tokenDescriptor); return json; }

下面是完整的请求,可按需更取需要的代码

using ESBPM.Framework.Component; //IOC组件
using ESBPM.Framework.IComponent;
using ESBPM.Framework.IComponent.Log;
using ESBPM.UI.IBiz;//UI框架接口组件
using ESBPM.Form.IBiz;//表单接口组件
using ESBPM.Workflow.Designer.IBiz;//工作流接口组件
using ESBPM.Organization.IBiz;//组织结构接口组件
using ESBPM.Framework.Public.Entity; //实体对象
using ESBPM.Framework.Tool; //工具类
using Newtonsoft.Json; //工具类
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using System.Security.Cryptography;
using System.Linq;
using System.Web;
using CYQ.Data.EsHelp;//操作库操作组件(mssqlserver,mysql,oracle)
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

public class TTTTTIEsPlugin : IEsPlugin //每个插件编写必须要继承IEsPlugin接口
{
    private static IZyl Zyl = ContainerContext.Container.Resolve<IZyl>();
    public object RunServices<T>(T objArr) //@RunServices 固定方法名称,此方法带参数,参数值为表单字段值
    {
        if (objArr is JObject)
        {
            var postdata = objArr as JObject;//得到参数
            var loginType = postdata["loginType"] == null ? "" : postdata["loginType"].ToString();//类型
        }
        else
        {
            Dictionary<string, object> postdata = objArr as Dictionary<string, object>;///// 组件集成,传过来的是Dictionary<string, object>
            var loginType = postdata["loginType"] == null ? "" : postdata["loginType"].ToString();//类型
        }
        try
        {
            StringBuilder Json = new StringBuilder();
            Json.Append("{");
            Json.Append("\"Name\":\"小马\",");
            Json.Append("\"logA\":\"logA\",");
            Json.Append("\"accountNo\":\"" + loginType + "\",");
            Json.Append("\"logTime\":\"2023-12-26 05:50:18\"");
            Json.Append("}");
            String jsonStr = Json.ToString();
            Zyl.Log("请求接口", "请求参数:" + jsonStr);//日志记录
            string secretId = "改成自己的发行人"; // 发行人  
            string secretKey = "改成自己的密钥"; // 密钥  
            string IRM_Token = CreateToken(secretId, secretKey);//获取tokeng
            string url = "https://www.baidu.com/?tn=88093251_92_hao_pg";//自行更改
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);//webRequest请求url
            httpRequest.Method = "POST";
            httpRequest.Headers.Add("Authorization", "Bearer " + IRM_Token);//表头验证
            httpRequest.ContentType = "application/json";//是一种编码格式,窗体数据被编码为名称/值对,是标准的编码格式。
            string postStr = jsonStr;

            byte[] bTemp = System.Text.Encoding.UTF8.GetBytes(postStr);
            httpRequest.ContentLength = bTemp.Length;

            System.IO.Stream smWrite = httpRequest.GetRequestStream(); //加入请求参数
            smWrite.Write(bTemp, 0, bTemp.Length);
            smWrite.Close();

            HttpWebResponse hResponse = (HttpWebResponse)httpRequest.GetResponse();  //响应api
            StreamReader srReader = new StreamReader(hResponse.GetResponseStream(), Encoding.UTF8);
            string strResult = srReader.ReadToEnd();
            Zyl.Log("请求接口", "返回结果:" + strResult);
            srReader.Close();
            hResponse.Close();

        }
        catch (Exception el)
        {

            throw;
        }
        return objArr;
    }
    public static string CreateToken(string secretId, string secretKey)
    {
        // 创建 JWT 对象  
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new System.Security.Claims.ClaimsIdentity(new[] { new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, secretId) }),
            Expires = DateTime.UtcNow.AddHours(1), // 设置过期时间  
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)), SecurityAlgorithms.HmacSha256Signature)
        };

        // 生成 JWT 并返回 token 字符串  
        var tokenHandler = new JwtSecurityTokenHandler();
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
        
    }
}