pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

  • <legend id='9nrpJ'><style id='9nrpJ'><dir id='9nrpJ'><q id='9nrpJ'></q></dir></style></legend>

      <tfoot id='9nrpJ'></tfoot>
        <bdo id='9nrpJ'></bdo><ul id='9nrpJ'></ul>
    1. <small id='9nrpJ'></small><noframes id='9nrpJ'>

      <i id='9nrpJ'><tr id='9nrpJ'><dt id='9nrpJ'><q id='9nrpJ'><span id='9nrpJ'><b id='9nrpJ'><form id='9nrpJ'><ins id='9nrpJ'></ins><ul id='9nrpJ'></ul><sub id='9nrpJ'></sub></form><legend id='9nrpJ'></legend><bdo id='9nrpJ'><pre id='9nrpJ'><center id='9nrpJ'></center></pre></bdo></b><th id='9nrpJ'></th></span></q></dt></tr></i><div class="kge2ya0" id='9nrpJ'><tfoot id='9nrpJ'></tfoot><dl id='9nrpJ'><fieldset id='9nrpJ'></fieldset></dl></div>

      1. ASP.NET Core 5.0 JWT 身份驗證總是拋出 HTTP 401 代碼

        ASP.NET Core 5.0 JWT authentication is always throws HTTP 401 code(ASP.NET Core 5.0 JWT 身份驗證總是拋出 HTTP 401 代碼)

        <small id='YfUqD'></small><noframes id='YfUqD'>

          <i id='YfUqD'><tr id='YfUqD'><dt id='YfUqD'><q id='YfUqD'><span id='YfUqD'><b id='YfUqD'><form id='YfUqD'><ins id='YfUqD'></ins><ul id='YfUqD'></ul><sub id='YfUqD'></sub></form><legend id='YfUqD'></legend><bdo id='YfUqD'><pre id='YfUqD'><center id='YfUqD'></center></pre></bdo></b><th id='YfUqD'></th></span></q></dt></tr></i><div class="okakgau" id='YfUqD'><tfoot id='YfUqD'></tfoot><dl id='YfUqD'><fieldset id='YfUqD'></fieldset></dl></div>
            <tbody id='YfUqD'></tbody>
          • <bdo id='YfUqD'></bdo><ul id='YfUqD'></ul>
            <tfoot id='YfUqD'></tfoot>

              1. <legend id='YfUqD'><style id='YfUqD'><dir id='YfUqD'><q id='YfUqD'></q></dir></style></legend>

                  本文介紹了ASP.NET Core 5.0 JWT 身份驗證總是拋出 HTTP 401 代碼的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

                  問題描述

                  限時送ChatGPT賬號..

                  我想在 ASP.NET Core 中實現基于 JWT 的安全性.我現在要做的就是讀取按鈕 @Html.ActionLink(Test",Oper",Home") 中的令牌,授權標頭并驗證它們違背我的標準.我不知道錯過了什么,但它總是返回 HTTP 401 代碼.

                  I want to implement JWT-based security in ASP.NET Core. All I want it to do, for now, is to read tokens in the button @Html.ActionLink("Test","Oper","Home") , authorize header and validate them against my criteria. I don't know what missed but it is always returning HTTP 401 code.

                  文件HomeController.cs

                          private string GenerateJSONWebToken(UserPaul userinfo)
                          {
                              var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
                              var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
                              var claims = new[]
                              {
                                  new Claim(JwtRegisteredClaimNames.Sub,userinfo.Username),
                                  new Claim(JwtRegisteredClaimNames.Email,userinfo.Email),
                                  new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()),
                              };
                              var token = new JwtSecurityToken(
                                  issuer: _config["Jwt:Issuer"],
                                  audience: _config["Jwt:Issuer"],
                                  claims,
                                  expires: DateTime.Now.AddMinutes(10),
                                  signingCredentials: credentials
                                  );
                              var encodetoken = new JwtSecurityTokenHandler().WriteToken(token);
                              var cookieOptions = new CookieOptions();         
                              cookieOptions.HttpOnly = true;
                              cookieOptions.Expires = DateTime.Now.AddMinutes(1);
                              //cookieOptions.Domain = Request.Host.Value;
                              cookieOptions.Path = "/";
                              Response.Cookies.Append("jwt", encodetoken, cookieOptions);
                              return encodetoken;
                          }
                          [HttpPost]
                          public IActionResult Login()
                          {
                              string AccountNumber="TestUser";
                              JWTtokenMVC.Models.TestContext userQuery = new JWTtokenMVC.Models.TestContext();
                              var query = userQuery.Testxxxx.Where(N => N.UserId ==AccountNumber).FirstOrDefault();
                              IActionResult response = Unauthorized();
                              if (query != null)
                              {
                                  var tokenStr = GenerateJSONWebToken(query);
                                  response = Ok(new { token = tokenStr });
                              }
                              return response;
                          }
                  
                          [Authorize]
                          [HttpGet("Home/Oper")]
                          public IActionResult Oper()
                          {
                              var authenticationCookieName = "jwt";
                              var cookie = HttpContext.Request.Cookies[authenticationCookieName];
                              List<Test_SHOW> sHOWs = new List<Test_SHOW>();
                              JWTtokenMVC.Models.Test.TestContext userQuery= new JWTtokenMVC.Models.Test.TestContext();
                              var query = userQuery.Test.Select(T => new Test_SHOW
                              {number= T.number,name= T.name,mail= T.mail}).OrderBy(o => o.Iid);
                              sHOWs.AddRange(query);
                  
                              return View("Views/Home/Oper.cshtml", sHOWs);
                   
                          }
                  
                  

                  這是 Startup.cs 代碼

                  using System;
                  using System.Collections.Generic;
                  using System.Linq;
                  using System.Threading.Tasks;
                  using Microsoft.AspNetCore.Builder;
                  using Microsoft.AspNetCore.Hosting;
                  using Microsoft.AspNetCore.HttpsPolicy;
                  using Microsoft.Extensions.Configuration;
                  using Microsoft.Extensions.DependencyInjection;
                  using Microsoft.Extensions.Hosting;
                  using Microsoft.Extensions.FileProviders;
                  using System.IO;
                  using Microsoft.IdentityModel.Tokens;
                  using System.Text;
                  using Microsoft.AspNetCore.Authentication.JwtBearer;
                  
                  namespace JWTtokenMVC
                  {
                      public class Startup
                      {
                          public Startup(IConfiguration configuration)
                          {
                              Configuration = configuration;
                          }
                  
                          public IConfiguration Configuration { get; }
                  
                          // This method gets called by the runtime. Use this method to add services to the container.
                          public void ConfigureServices(IServiceCollection services)
                          {
                              services.AddControllersWithViews();
                              services.AddCors(options =>
                              {
                                  options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials().Build());
                              });
                  
                              services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                              .AddJwtBearer(options =>
                              {
                                  options.IncludeErrorDetails = true;
                                  options.TokenValidationParameters = new TokenValidationParameters
                                  {
                  
                  NameClaimType ="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
                                     
                  RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
                                      ValidateIssuer = true,
                                      ValidateAudience = false,
                                      ValidateLifetime = true,
                                      ValidateIssuerSigningKey = true,
                                      ValidIssuer = Configuration["Jwt:Issuer"],
                                      ValidAudience = Configuration["Jwt:Issuer"],
                                      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])
                  
                                      )
                                  };
                  
                              });
                          }
                  
                          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
                          public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
                          {
                              if (env.IsDevelopment())
                              {
                                  app.UseDeveloperExceptionPage();
                              }
                              else
                              {
                                  app.UseExceptionHandler("/Home/Error");
                                  // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                                  app.UseHsts();
                              }
                              app.UseHttpsRedirection();
                              app.UseStaticFiles();
                              app.UseStaticFiles(new StaticFileOptions
                              {
                                  FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "node_modules")),
                                  RequestPath = "/" + "node_modules"
                              });
                              app.UseCookiePolicy();
                  
                              app.UseRouting();
                              app.UseAuthentication();
                  
                              app.UseAuthorization();
                  
                              app.UseEndpoints(endpoints =>
                              {
                                  endpoints.MapControllerRoute(
                                      name: "default",
                                      pattern: "{controller=Home}/{action=Index}/{id?}");
                              });
                          }
                      }
                  }
                  
                  

                  Startup.cs 圖片

                  Startup.cs image

                  Startup.cs 添加 UseAuthentication

                  Startup.cs Add UseAuthentication

                  推薦答案

                  所以我假設您正在嘗試使用 Angular 項目的 asp.net core.我認為您錯過了將客戶端 URL 添加到您的 .net core 項目.AddCors對 IServiceCollection 的擴展調用只是注冊了所有需要的服務,但它沒有將 Cors 中間件添加到 HTTP 請求管道中.所以添加此代碼 app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200")); 在您的 Configure 方法中.我認為它可以解決您的問題.

                  So I assume you are trying asp.net core with an angular project.I think you are missed adding your client-side URL to your .net core project. AddCorson extension call for IServiceCollection just registers all required services, but it does not add Cors middleware to the HTTP request pipeline.So add this code app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200")); in your Configure method.i think it's resolve your issue.

                  
                   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
                          {
                              if (env.IsDevelopment())
                              {
                                  //clarify code
                                
                              }
                              else{  
                  
                                 //clarify code    
                  
                              }
                              
                  
                              app.UseHttpsRedirection();
                  
                              app.UseRouting();
                  
                              app.UseCors(x => 
                    x.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200")); //your  client side URL.you are missing this unfortunately
                  
                              app.UseAuthentication();
                  
                              app.UseAuthorization();
                  
                             //clarify code
                          }
                  
                  

                  更新

                  安裝Microsoft.AspNetCore.Cors

                  只需刪除 AllowCredentials() 即可解決您的問題.

                  Just remove AllowCredentials() and it's will fix your issue.

                  這篇關于ASP.NET Core 5.0 JWT 身份驗證總是拋出 HTTP 401 代碼的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

                  【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

                  相關文檔推薦

                  What are good algorithms for vehicle license plate detection?(車牌檢測有哪些好的算法?)
                  onClick event for Image in Unity(Unity中圖像的onClick事件)
                  Running Total C#(運行總 C#)
                  Deleting a directory when clicked on a hyperlink with JAvascript.ASP.NET C#(單擊帶有 JAvascript.ASP.NET C# 的超鏈接時刪除目錄)
                  asp.net listview highlight row on click(asp.net listview 在單擊時突出顯示行)
                  Calling A Button OnClick from a function(從函數調用按鈕 OnClick)

                  <small id='U6aBa'></small><noframes id='U6aBa'>

                  1. <tfoot id='U6aBa'></tfoot>
                    • <legend id='U6aBa'><style id='U6aBa'><dir id='U6aBa'><q id='U6aBa'></q></dir></style></legend>

                      <i id='U6aBa'><tr id='U6aBa'><dt id='U6aBa'><q id='U6aBa'><span id='U6aBa'><b id='U6aBa'><form id='U6aBa'><ins id='U6aBa'></ins><ul id='U6aBa'></ul><sub id='U6aBa'></sub></form><legend id='U6aBa'></legend><bdo id='U6aBa'><pre id='U6aBa'><center id='U6aBa'></center></pre></bdo></b><th id='U6aBa'></th></span></q></dt></tr></i><div class="0yuiokq" id='U6aBa'><tfoot id='U6aBa'></tfoot><dl id='U6aBa'><fieldset id='U6aBa'></fieldset></dl></div>
                        <tbody id='U6aBa'></tbody>
                      • <bdo id='U6aBa'></bdo><ul id='U6aBa'></ul>
                            主站蜘蛛池模板: 凝胶成像仪,化学发光凝胶成像系统,凝胶成像分析系统-上海培清科技有限公司 | 北京公积金代办/租房发票/租房备案-北京金鼎源公积金提取服务中心 | 干培两用箱-细菌恒温培养箱-菲斯福仪器 | 篷房[仓储-婚庆-展览-活动]生产厂家-江苏正德装配式帐篷有限公司 | 武汉森源蓝天环境科技工程有限公司-为环境污染治理提供协同解决方案 | 二手色谱仪器,十万分之一分析天平,蒸发光检测器,电位滴定仪-湖北捷岛科学仪器有限公司 | 防腐木批发价格_深圳_惠州_东莞防腐木厂家_森源(深圳)防腐木有限公司 | 寮步纸箱厂_东莞纸箱厂 _东莞纸箱加工厂-东莞市寮步恒辉纸制品厂 | 二维运动混料机,加热型混料机,干粉混料机-南京腾阳干燥设备厂 | 办公室装修_上海办公室设计装修_时尚办公新主张-后街印象 | 便民信息网_家电维修,家电清洗,开锁换锁,本地家政公司 | 粉末冶金注射成型厂家|MIM厂家|粉末冶金齿轮|MIM零件-深圳市新泰兴精密科技 | 反渗透水处理设备|工业零排放|水厂设备|软化水设备|海南净水设备--海南水处理设备厂家 | 坏男孩影院-提供最新电影_动漫_综艺_电视剧_迅雷免费电影最新观看 | 全自动过滤器_反冲洗过滤器_自清洗过滤器_量子除垢环_量子环除垢_量子除垢 - 安士睿(北京)过滤设备有限公司 | 合肥仿石砖_合肥pc砖厂家_合肥PC仿石砖_安徽旭坤建材有限公司 | 哈尔滨发电机,黑龙江柴油发电机组-北方星光 | 全屋整木定制-橱柜,家具定制-四川峨眉山龙马木业有限公司 | 杭州实验室尾气处理_实验台_实验室家具_杭州秋叶实验设备有限公司 | 上海心叶港澳台联考一对一培训_上海心叶港澳台联考,港澳台联考一对一升学指导 | 正压送风机-多叶送风口-板式排烟口-德州志诺通风设备 | 缓蚀除垢剂_循环水阻垢剂_反渗透锅炉阻垢剂_有机硫化物-郑州威大水处理材料有限公司 | 杭州营业执照代办-公司变更价格-许可证办理流程_杭州福道财务管理咨询有限公司 | 3d可视化建模_三维展示_产品3d互动数字营销_三维动画制作_3D虚拟商城 【商迪3D】三维展示服务商 广东健伦体育发展有限公司-体育工程配套及销售运动器材的体育用品服务商 | 上海单片机培训|重庆曙海培训分支机构—CortexM3+uC/OS培训班,北京linux培训,Windows驱动开发培训|上海IC版图设计,西安linux培训,北京汽车电子EMC培训,ARM培训,MTK培训,Android培训 | 冷油器-冷油器换管改造-连云港灵动列管式冷油器生产厂家 | 全自动面膜机_面膜折叠机价格_面膜灌装机定制_高速折棉机厂家-深圳市益豪科技有限公司 | 口信网(kousing.com) - 行业资讯_行业展会_行业培训_行业资料 | 土壤墒情监测站_土壤墒情监测仪_土壤墒情监测系统_管式土壤墒情站-山东风途物联网 | 全钢实验台,实验室工作台厂家-无锡市辰之航装饰材料有限公司 | 洛阳装修公司-洛阳整装一站式品牌-福尚云宅装饰| 带压开孔_带压堵漏_带压封堵-菏泽金升管道工程有限公司 | 空调风机,低噪声离心式通风机,不锈钢防爆风机,前倾皮带传动风机,后倾空调风机-山东捷风风机有限公司 | 电动打包机_气动打包机_钢带捆扎机_废纸打包机_手动捆扎机 | 内六角扳手「厂家」-温州市威豪五金工具有限公司 | 中央空调温控器_风机盘管温控器_智能_液晶_三速开关面板-中央空调温控器厂家 | 注塑机-压铸机-塑料注塑机-卧式注塑机-高速注塑机-单缸注塑机厂家-广东联升精密智能装备科技有限公司 | 曙光腾达官网-天津脚手架租赁-木板架出租-移动门式脚手架租赁「免费搭设」 | 超声波清洗机_大型超声波清洗机_工业超声波清洗设备-洁盟清洗设备 | 热镀锌槽钢|角钢|工字钢|圆钢|H型钢|扁钢|花纹板-天津千百顺钢铁贸易有限公司 | 电缆隧道在线监测-智慧配电站房-升压站在线监测-江苏久创电气科技有限公司 |