ASP.NET 核心 JWT 身份验证总是抛出 401 未授权

ASP.NET core JWT authentication always throwing 401 unauthorized(ASP.NET 核心 JWT 身份验证总是抛出 401 未授权)
本文介绍了ASP.NET 核心 JWT 身份验证总是抛出 401 未授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试尽可能简单地在我的 asp.net 核心 webAPI 上实现 JWT 身份验证.我不知道我错过了什么,但即使使用 proper 不记名令牌,它也总是返回 401.

I'm trying to implement JWT authentication on my asp.net core webAPI as simply as possible. I don't know what i'm missing but it's always returning 401 even with the proper bearer token.

这是我的 configureServices 代码

here is my configureServices code

public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(
               x =>
               {
                   x.RequireHttpsMetadata = false;
                   x.SaveToken = true;
                   x.TokenValidationParameters = new TokenValidationParameters
                   {
                       ValidateIssuerSigningKey = true,
                       IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("A_VERY_SECRET_SECURITY_KEY_FOR_JWT_AUTH")),
                       ValidateAudience = false,
                       ValidateIssuer = false,
                   };
               }
                );
            services.AddControllers();

            services.AddDbContext<dingdogdbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("dingdogdbContext")));
        }

这就是我生成令牌的方式

and this is how I'm generating token

        [AllowAnonymous]
        [HttpPost("/Login")]
        public ActionResult<User> Login(AuthModel auth)
        {
            var user = new User();
            user.Email = auth.Email;
            user.Password = auth.Password;
            //var user = await _context.User.SingleOrDefaultAsync(u=> u.Email == auth.Email && u.Password==auth.Password);
            //if(user==null) return NotFound("User not found with this creds");

            //starting token generation...
            var tokenHandler = new JwtSecurityTokenHandler();
            var seckey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("A_VERY_SECRET_SECURITY_KEY_FOR_JWT_AUTH"));
            var signingCreds = new SigningCredentials(seckey, SecurityAlgorithms.HmacSha256Signature);
            var token = tokenHandler.CreateToken(new SecurityTokenDescriptor
            {
                Subject = new System.Security.Claims.ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }),
                SigningCredentials = signingCreds,
                Expires = DateTime.UtcNow.AddDays(7),
            });
            user.Token = tokenHandler.WriteToken(token);
            return user;
        }

我在 app.useRouting() 之后添加了 app.useAuthorization().当我向/Login 发送 POST 请求时,我得到了令牌.但是当我使用令牌查询使用邮递员的任何其他端点时(在邮递员的授权/JWT 中添加令牌)每次都获得 401 未经授权.我还缺少什么吗?

And I added app.useAuthorization() very after the app.useRouting(). when i'm sending POST request to /Login I'm getting the token. but when I'm using the token in for querying any other endpoint using postman(added the token in authorization/JWT in postman) getting 401 unauthorized every time. is there anything I'm missing still?

推荐答案

记住 UseAuthenticationUseRoutingUseAuthorization 中间件必须正确,以便 ASP 框架正确地将身份上下文注入 http 请求.

Keep in mind that the UseAuthentication, UseRouting and UseAuthorization middleware must in correct in order for the ASP framework properly inject the identity context to http request.

它应该看起来像这样:(.NET Core 3.1)

It should look like this: (.NET Core 3.1)

相同的代码适用于 .NET 5 &.NET 6

the same code applies to .NET 5 & .NET 6

            app.UseAuthentication();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

这篇关于ASP.NET 核心 JWT 身份验证总是抛出 401 未授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Setup RabbitMQ consumer in ASP.NET Core application(在 ASP.NET Core 应用程序中设置 RabbitMQ 消费者)
Adding Custom header to the excel file(将自定义标题添加到 excel 文件)
ASP.NET masterpages: how to insert markup in the head section inside the aspx?(ASP.NET 母版页:如何在 aspx 内的 head 部分插入标记?)
Cache-Control Headers in ASP.NET(ASP.NET 中的缓存控制标头)
Could not load file or assembly #39;Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed#39;(无法加载文件或程序集“Newtonsoft.Json,版本=4.5.0.0,文化=中性,PublicKeyToken=30ad4fe6b2a6aeed) - IT屋-程序员软件开
Specifying a custom DateTime format when serializing with Json.Net(使用 Json.Net 序列化时指定自定义 DateTime 格式)