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>
                            主站蜘蛛池模板: LINK FASHION 童装·青少年装展| 根系分析仪,大米外观品质检测仪,考种仪,藻类鉴定计数仪,叶面积仪,菌落计数仪,抑菌圈测量仪,抗生素效价测定仪,植物表型仪,冠层分析仪-杭州万深检测仪器网 | 农业四情_农业气象站_田间小型气象站_智慧农业气象站-山东风途物联网 | 成都软件开发_OA|ERP|CRM|管理系统定制开发_成都码邻蜀科技 | 珠光砂保温板-一体化保温板-有釉面发泡陶瓷保温板-杭州一体化建筑材料 | 粉丝机械,粉丝烘干机,粉丝生产线-招远市远东粉丝机械有限公司 | 威海防火彩钢板,威海岩棉复合板,威海彩钢瓦-文登区九龙岩棉复合板厂 | 安徽华耐泵阀有限公司-官方网站 安德建奇火花机-阿奇夏米尔慢走丝|高维|发那科-北京杰森柏汇 | 桥架-槽式电缆桥架-镀锌桥架-托盘式桥架 - 上海亮族电缆桥架制造有限公司 | 膜片万向弹性联轴器-冲压铸造模具「沧州昌运模具」 | 浙江红酒库-冰雕库-气调库-茶叶库安装-医药疫苗冷库-食品物流恒温恒湿车间-杭州领顺实业有限公司 | 乐之康护 - 专业护工服务平台,提供医院陪护-居家照护-居家康复 | 志高装潢官网-苏州老房旧房装修改造-二手房装修翻新 | 游泳池设计|设备|配件|药品|吸污机-东莞市太平洋康体设施有限公司 | 【直乐】河北石家庄脊柱侧弯医院_治疗椎间盘突出哪家医院好_骨科脊柱外科专业医院_治疗抽动症/关节病骨伤权威医院|排行-直乐矫形中医医院 | 磁力抛光机_磁力研磨机_磁力去毛刺机-冠古设备厂家|维修|租赁【官网】 | 屏蔽泵厂家,化工屏蔽泵_维修-淄博泵业 | 油缸定制-液压油缸厂家-无锡大鸿液压气动成套有限公司 | 肉嫩度仪-凝胶测试仪-国产质构仪-气味分析仪-上海保圣实业发展有限公司|总部 | 考试试题_试卷及答案_诗词单词成语 - 优易学 | 赛尔特智能移动阳光房-阳光房厂家-赛尔特建筑科技(广东)有限公司 | 水质传感器_水质监测站_雨量监测站_水文监测站-山东水境传感科技有限公司 | 衡阳耐适防护科技有限公司——威仕盾焊接防护用品官网/焊工手套/焊接防护服/皮革防护手套 | 干式变压器厂_干式变压器厂家_scb11/scb13/scb10/scb14/scb18干式变压器生产厂家-山东科锐变压器有限公司 | 防爆鼓风机-全风-宏丰鼓风机-上海梁瑾机电设备有限公司 | 粉末包装机-给袋式包装机-全自动包装机-颗粒-液体-食品-酱腌菜包装机生产线【润立机械】 | 乐考网-银行从业_基金从业资格考试_初级/中级会计报名时间_中级经济师 | 知网论文检测系统入口_论文查重免费查重_中国知网论文查询_学术不端检测系统 | 北京开源多邦科技发展有限公司官网| 20年条刷老厂-条刷-抛光-工业毛刷辊-惠众毛刷| 手持式3d激光扫描仪-便携式三维立体扫描仪-北京福禄克斯 | 单螺旋速冻机-双螺旋-流态化-隧道式-食品速冻机厂家-广州冰泉制冷 | 仿真茅草_人造茅草瓦价格_仿真茅草厂家_仿真茅草供应-深圳市科佰工贸有限公司 | 学校用栓剂模,玻璃瓶轧盖钳,小型安瓿熔封机,实验室安瓿熔封机-长沙中亚制药设备有限公司 | 艾乐贝拉细胞研究中心 | 国家组织工程种子细胞库华南分库 | 膏剂灌装旋盖机-眼药水灌装生产线-西林瓶粉剂分装机-南通博琅机械科技 | 杭州公司变更法人-代理记账收费价格-公司注销代办_杭州福道财务管理咨询有限公司 | 网站建设,北京网站建设,北京网站建设公司,网站系统开发,北京网站制作公司,响应式网站,做网站公司,海淀做网站,朝阳做网站,昌平做网站,建站公司 | 高考志愿规划师_高考规划师_高考培训师_高报师_升学规划师_高考志愿规划师培训认证机构「向阳生涯」 | 高压无油空压机_无油水润滑空压机_水润滑无油螺杆空压机_无油空压机厂家-科普柯超滤(广东)节能科技有限公司 | hc22_hc22价格_hc22哈氏合金—东锜特殊钢 |