C# .NET HTTP GET POST加签名验证方法,Token验证,AppId验证

1.http Get请求

/// <summary>
        /// HTTP GET请求(带加签)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">请求URL</param>
        /// <param name="pairs">请求数据</param>
        /// <param name="appid">APPID</param>
        /// <param name="isSign">是否加签 默认为是</param>
        /// <returns></returns>
        public static T Get<T>(string url, SortedDictionary<string, object> pairs, string appid, bool isSign = true)
        {
   
            HttpWebRequest webRequest = null;
            HttpWebResponse webresponse = null;
            var str_result = string.Empty;
            try
            {
   
                string paramStr = "";
                if (pairs != null && pairs.Count > 0)
                {
   
                    paramStr = "";
                    foreach (KeyValuePair<string, object> item in pairs)
                    {
   
                        paramStr += item.Key + "=" + item.Value + "&";
                    }
                    paramStr = paramStr.Substring(0, paramStr.Length - 1);
                }
                if (paramStr != "" && !url.Contains("appid"))
                {
   
                    url += "?" + paramStr;
                }
                webRequest = (HttpWebRequest)WebRequest.Create(url);

                webRequest.Method = "GET";
                webRequest.ContentType = "application/json";
                webRequest.Timeout = 30000;
                webRequest.Headers.Add("appid", appid);
                var timespan = CreateTimeSpan();
                var nonce = CreateNonceStr(6);
                webRequest.Headers.Add("timespan", timespan);
                webRequest.Headers.Add("nonce", nonce);
                if (isSign)
                {
   
                    var sign = CreateSignature(appid, timespan, nonce, paramStr);
                    webRequest.Headers.Add(
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: 在 .NET Core Web API 中进行 Token 验证通常涉及以下步骤: 1. 安装 Microsoft.AspNetCore.Authentication.JwtBearer 包。 2. 在 Startup.cs 文件的 ConfigureServices() 方法中添身份验证服务,包括 JWTBearerOptions 配置。 3. 在 Startup.cs 文件的 Configure() 方法中启用身份验证中间件。 以下是一个基本的示例: ```csharp using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; public void ConfigureServices(IServiceCollection services) { // 配置身份验证服务 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])) }; }); // 其他服务注册... } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 启用身份验证中间件 app.UseAuthentication(); // 其他中间件注册... } ``` 上述代码中,我们使用了 `AddAuthentication()` 方法来配置身份验证服务,并指定了 JWTBearerDefaults.AuthenticationScheme 作为默认身份验证方案。 接着,我们使用 `AddJwtBearer()` 方法来配置 JWTBearerOptions,其中 `TokenValidationParameters` 属性用于指定 Token 验证参数,例如验证发行者、受众、过期时间、签名密钥等。 最后,在 Configure() 方法中,我们调用 `UseAuthentication()` 方法来启用身份验证中间件,以确保每个请求都进行身份验证。 ### 回答2: 在.NET Core Web API中配置Token验证,可以按照以下步骤进行操作: 1. 添NuGet包:在项目中添Microsoft.AspNetCore.Authentication和Microsoft.AspNetCore.Authentication.JwtBearer两个NuGet包。 2. 配置认证服务:在Startup.cs文件的ConfigureServices方法中添以下代码,以启用Bearer令牌验证: ``` services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, // 验证发行人 ValidateAudience = true, // 验证受众 ValidateLifetime = true, // 验证生命周期 ValidateIssuerSigningKey = true, // 验证颁发的签名密钥 ValidIssuer = "your_issuer", // 设置发行人 ValidAudience = "your_audience", // 设置受众 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")) // 设置签名密钥 }; }); ``` 3. 配置授权:在Startup.cs文件的Configure方法中添以下代码,以启用授权中间件: ``` app.UseAuthentication(); app.UseAuthorization(); ``` 4. 添[Authorize]特性:在需要验证Token的Controller或Action上添[Authorize]特性。 现在,当客户端请求受保护的Controller或Action时,将自动检查请求中的Token是否有效。如果Token验证失败,将返回401 Unauthorized状态码。如果验证成功,则可以继续处理请求。 ### 回答3: 在.NET Core WebAPI中配置Token验证主要涉及以下几个步骤: 1. 导入所需的包:首先,需要在`Startup.cs`文件中的`ConfigureServices`方法中导入所需的包。使用`Microsoft.AspNetCore.Authentication.JwtBearer`包来配置JWT验证。 2. 配置认证服务:在`ConfigureServices`方法中使用`services.AddAuthentication`来添认证服务,并指定默认的身份验证方案。例如: ```csharp services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; // 是否要求HTTPS options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, // 验证发行者 ValidateAudience = true, // 验证接收者 ValidateLifetime = true, // 验证令牌有效期 ValidateIssuerSigningKey = true, // 验证签名 ValidIssuer = "your_issuer", ValidAudience = "your_audience", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")) }; }); ``` 在上述代码中,可以根据自己的需求调整参数值,如验证发行者、接收者、令牌有效期、签名等。 3. 应用认证中间件:在`Configure`方法中,使用`app.UseAuthentication()`来应用认证中间件。确保此代码位于路由中间件之前。例如: ```csharp app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); ``` 4. 使用`Authorize`特性:在需要进行Token验证的Controller或Action上,可以使用`Authorize`特性来标记,以进行访问控制。例如: ```csharp [Authorize] public class MyController : ControllerBase { // ... } ``` 5. 在请求中包含Token:最后,在发送请求时,需要在请求头中包含Bearer Token,以进行验证。例如: ``` Authorization: Bearer your_token ``` 通过以上配置,就可以在.NET Core WebAPI中实现Token验证。这样,当请求到达API时,API会验证Token的有效性,并对请求进行授权控制,确保只有拥有有效Token的用户可以访问受保护的资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值