ASP.NET Core 5 和 6 JWT 身份验证始终抛出 HTTP 401 代码

2023-12-10

我想在 ASP.NET Core 中实现基于 JWT 的安全性。目前我想要它做的就是读取按钮中的令牌@Html.ActionLink("Test","Oper","Home"),授权标头并根据我的标准验证它们。我不知道错过了什么,但它总是返回 HTTP 401 代码。

File 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);
 
        }

这是启动.cs code

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 映像

enter image description here

Startup.cs 添加 UseAuthentication


所以我假设您正在尝试使用 Angular 项目来尝试 asp.net core。我认为您错过了将客户端 URL 添加到 .net core 项目的过程。AddCors对 IServiceCollection 的扩展调用只是注册所有必需的服务,但它不会将 Cors 中间件添加到 HTTP 请求管道。因此添加此代码app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200"));在您的配置方法中。我认为它可以解决您的问题。


 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
        }

UPDATE

Install Microsoft.AspNetCore.Cors

只需删除AllowCredentials()它会解决你的问题。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ASP.NET Core 5 和 6 JWT 身份验证始终抛出 HTTP 401 代码 的相关文章

  • 结构化绑定中缺少类型信息

    我刚刚了解了 C 中的结构化绑定 但有一件事我不喜欢 auto x y some func is that auto正在隐藏类型x and y 我得抬头看看some func的声明来了解类型x and y 或者 我可以写 T1 x T2 y
  • 如何将 std::string& 转换为 C# 引用字符串

    我正在尝试将 C 函数转换为std string参考C 我的 API 如下所示 void GetStringDemo std string str 理想情况下 我希望在 C 中看到类似的东西 void GetStringDemoWrap r
  • C# 异步等待澄清?

    我读了here http blog stephencleary com 2012 02 async and await html that 等待检查等待的看看它是否有already完全的 如果 可等待已经完成 那么该方法将继续 运行 同步
  • 类型中的属性名称必须是唯一的

    我正在使用 Entity Framework 5 并且有以下实体 public class User public Int32 Id get set public String Username get set public virtual
  • C++11 删除重写方法

    Preface 这是一个关于最佳实践的问题 涉及 C 11 中引入的删除运算符的新含义 当应用于覆盖继承父类的虚拟方法的子类时 背景 根据标准 引用的第一个用例是明确禁止调用某些类型的函数 否则转换将是隐式的 例如最新版本第 8 4 3 节
  • 随着时间的推移,添加到 List 变得非常慢

    我正在解析一个大约有 1000 行的 html 表 我从一个字符串中添加 10 个字符串 td 每行到一个list td
  • 无限循环与无限递归。两者都是未定义的吗?

    无副作用的无限循环是未定义的行为 看here https coliru stacked crooked com view id 24e0a58778f67cd4举个例子参考参数 https en cppreference com w cpp
  • 如何使从 C# 调用的 C(P/invoke)代码“线程安全”

    我有一些简单的 C 代码 它使用单个全局变量 显然这不是线程安全的 所以当我使用 P invoke 从 C 中的多个线程调用它时 事情就搞砸了 如何为每个线程单独导入此函数 或使其线程安全 我尝试声明变量 declspec thread 但
  • 需要帮助优化算法 - 两百万以下所有素数的总和

    我正在尝试做一个欧拉计划 http projecteuler net问题 我正在寻找 2 000 000 以下所有素数的总和 这就是我所拥有的 int main int argc char argv unsigned long int su
  • C# 列表通用扩展方法与非通用扩展方法

    这是一个简单的问题 我希望 集合类中有通用和非通用方法 例如List
  • C# - 当代表执行异步任务时,我仍然需要 System.Threading 吗?

    由于我可以使用委托执行异步操作 我怀疑在我的应用程序中使用 System Threading 的机会很小 是否存在我无法避免 System Threading 的基本情况 只是我正处于学习阶段 例子 class Program public
  • x:将 ViewModel 方法绑定到 DataTemplate 内的事件

    我基本上问同样的问题这个人 https stackoverflow com questions 10752448 binding to viewmodels property from a template 但在较新的背景下x Bind V
  • 实例化类时重写虚拟方法

    我有一个带有一些虚函数的类 让我们假设这是其中之一 public class AClassWhatever protected virtual string DoAThingToAString string inputString retu
  • C 编程:带有数组的函数

    我正在尝试编写一个函数 该函数查找行为 4 列为 4 的二维数组中的最大值 其中二维数组填充有用户输入 我知道我的主要错误是函数中的数组 但我不确定它是什么 如果有人能够找到我出错的地方而不是编写新代码 我将不胜感激 除非我刚去南方 我的尝
  • 空指针与 int 等价

    Bjarne 在 C 编程语言 中写道 空指针与整数零不同 但 0 可以用作空指针的指针初始值设定项 这是否意味着 void voidPointer 0 int zero 0 int castPointer reinterpret cast
  • C# 动态/expando 对象的深度/嵌套/递归合并

    我需要在 C 中 合并 2 个动态对象 我在 stackexchange 上找到的所有内容仅涵盖非递归合并 但我正在寻找能够进行递归或深度合并的东西 非常类似于jQuery 的 extend obj1 obj2 http api jquer
  • 为什么使用小于 32 位的整数?

    我总是喜欢使用最小尺寸的变量 这样效果就很好 但是如果我使用短字节整数而不是整数 并且内存是 32 位字可寻址 这真的会给我带来好处吗 编译器是否会做一些事情来增强内存使用 对于局部变量 它可能没有多大意义 但是在具有数千甚至数百万项的结构
  • 如何实例化 ODataQueryOptions

    我有一个工作 简化 ODataController用下面的方法 public class MyTypeController ODataController HttpGet EnableQuery ODataRoute myTypes pub
  • 如何在 Linq to SQL 中使用distinct 和 group by

    我正在尝试将以下 sql 转换为 Linq 2 SQL select groupId count distinct userId from processroundissueinstance group by groupId 这是我的代码
  • MySQL Connector C/C API - 使用特殊字符进行查询

    我是一个 C 程序 我有一个接受域名参数的函数 void db domains query char name 使用 mysql query 我测试数据库中是否存在域名 如果不是这种情况 我插入新域名 char query 400 spri

随机推荐

  • BOM 随机出现在 JSON 回复中

    我正在使用 JSON 和 cURL 实现两个服务器之间的通信 问题是 有时 JSON 回复中的开括号之前会附加 BOM 字节顺序标记 我已经设法修剪它并成功解析 JSON 字符串 但考虑到 JSON 是由我自己的代码生成的 我不知道该 BO
  • 在R中,如何在将对象发送到函数后获取对象的名称?

    我正在寻找相反的get 给定一个对象名称 我希望直接从该对象中提取代表该对象的字符串 简单的例子foo是我正在寻找的函数的占位符 z lt data frame x 1 10 y 1 10 test lt function a mean x
  • 收到 org.postgresql.util.PGobject 类型的对象

    我可以从代码中将几何数据插入数据库 但只能使用 SQL 编辑器 例如 PGAdmin III 查询数据 我无法将几何数据检索回我的代码 每次尝试都会以 已接收类型为 org postgresql util PGobject 的对象 结束 即
  • 如何在 iOS 中以编程方式添加 UITabBarItem 的标识符类型?

    我想在 iOS 中以编程方式添加 UITabBarItem 在界面生成器中 我们可以轻松选择搜索 收藏夹 最近选项卡等标识符 我想知道如何以编程方式添加这些标识符类型 您将其添加为 UIViewController 属性吗 你创建一个UIT
  • 如何捕获 ASP.NET 应用程序中未处理的异常?

    在一次 NET考试中我遇到了这个问题 您可以使用以下哪项来捕获应用程序中未处理的异常 服务器错误 页面错误 应用程序错误 响应错误 错误事件 我知道它的Application Error 但我想知道的是其他的是什么 通过一些谷歌搜索 我发现
  • 无法从我自己的 angularjs api 获取 JSONP 数据

    我正在尝试从我自己的 api 获取数据 但无法成功将数据获取到 vegdata 变量 这是控制器代码 scope filterText null scope vegdata scope init function url http 192
  • WPF TreeView 数据绑定以隐藏/显示展开/折叠图标

    我实现了一个 WPF 按需加载树视图 如中所述this 非常好的 文章 在上述解决方案中 使用虚拟元素来保留展开 图标 树视图项目行为 当用户单击扩展器时 虚拟项目将替换为真实数据 我想通过添加属性来完善模型public bool HasC
  • 哪些 Swing 组件方法是线程安全的?

    根据摇摆教程 一些 Swing 组件方法在 API 规范中被标记为 线程安全 这些可以从任何线程安全地调用 所有其他 Swing 组件方法都必须从事件分派线程调用 忽略此规则的程序可能在大多数情况下都能正常运行 但会出现难以重现的不可预测的
  • 无法创建 /dev/stdout:没有这样的设备或地址

    我想通过节点运行 shell 命令并捕获标准输出的结果 我的脚本在 OSX 上运行良好 但在 Ubuntu 上不行 我已将问题和脚本简化为以下节点脚本 var execSync require child process execSync
  • python中将edgelist导入igraph的格式

    igraph 接受的用于导入 python 的边缘列表格式是什么 包含加权边缘的文本文件应该是什么样子 我以前曾在 R 中使用过 igraph 但在我需要使用的机器上没有安装有效的 R 所以我陷入了 python 困境 我有一个 egeli
  • Python Matplotlib 滑块已绘制但不移动或更新

    我正在尝试绘制一个散点图 其中一个点根据滑块调整的参数移动 我需要参数是坐标列表中的位置 我拥有它 因此可以绘制散点图 并且我可以通过更改位置来手动移动点 但是当我尝试实现滑块时 它会显示 但无法更新绘图 任何帮助都会很棒 到目前为止我所拥
  • Catia VBA 到 .CATScript(针对“集合”类型)

    在我的 VBA 代码中 我使用以下内容 Dim docsToSave As Scripting Dictionary Set docsToSave New Scripting Dictionary Dim toRemove As Colle
  • Matlab 上 Z 归一化 (z-score) 函数的反函数

    在Matlab R2014a中我有信心使用z分数 x 功能 function z mu sigma zscore x flag dim if isequal x z return end if nargin lt 2 flag 0 end
  • 在 JPanel 上添加 .GIF 时显示黑色方块

    我的问题是 当将 GIF 添加到 JPanel 时 它会显示 GIF 的黑色方形背景 在JPanel上添加时的结果 当我使用这一行时会发生这种情况 p2 add loadBar where p2 new JPanel 但是 当我在 JFra
  • 在 swift 中使用简单 Ping (iOS)

    我正在尝试使用 Apple 的类 Simple Ping 但我无法使其正常工作 当我运行示例 mac os x 项目时 它正在工作 2015 06 17 00 03 22 569 SimplePing 20386 3133535 ping
  • Angular 5 插入动态输入属性

    我想将动态属性插入到输入 html 标记中 但我不知道该怎么做 我从组件端得到了这段代码 import Component OnInit from angular core Component selector app transclusi
  • Web 套接字在 Firefox 12 中不工作

    Firefox 无法与服务器 ws 192 168 0 155 5555 socket server3 php 建立连接 document ready function if WebSocket in window alert not av
  • 将 jQuery 自动完成与 Flask 结合使用

    这个问题之前已经被问过 我想我已经做了我在那里看到的事情 但我真的不知道我做错了什么 我对 jQuery 了解不多 但我会尽力解释我想要做什么 我想根据数据库中的查询自动完成 所以我的模板中有这样的内容
  • 张量流构建错误

    我在构建 Tensorflow 1 1 0 时遇到此错误 Starting local Bazel server and connecting to it ERROR home bishal cache bazel bazel bishal
  • ASP.NET Core 5 和 6 JWT 身份验证始终抛出 HTTP 401 代码

    我想在 ASP NET Core 中实现基于 JWT 的安全性 目前我想要它做的就是读取按钮中的令牌 Html ActionLink Test Oper Home 授权标头并根据我的标准验证它们 我不知道错过了什么 但它总是返回 HTTP