<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 id='YfUqD'><tfoot id='YfUqD'></tfoot><dl id='YfUqD'><fieldset id='YfUqD'></fieldset></dl></div>
    • <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 代码

        时间:2023-06-01
      1. <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>

                <tbody id='9nrpJ'></tbody>

              <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 id='9nrpJ'><tfoot id='9nrpJ'></tfoot><dl id='9nrpJ'><fieldset id='9nrpJ'></fieldset></dl></div>

                • 本文介绍了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模板网!

                  上一篇:如何在控制器方法中使 JWT 令牌授权可选 下一篇:解码 Azure 移动服务 JWT 令牌时出现 JwtSecurityToke

                  相关文章

                  最新文章

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

                  1. <tfoot id='U6aBa'></tfoot>
                  2. <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 id='U6aBa'><tfoot id='U6aBa'></tfoot><dl id='U6aBa'><fieldset id='U6aBa'></fieldset></dl></div>
                    • <bdo id='U6aBa'></bdo><ul id='U6aBa'></ul>