ASP.NET core JWT authentication always throwing 401 unauthorized

前端 未结 4 510
借酒劲吻你
借酒劲吻你 2020-12-22 07:37

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

4条回答
  •  粉色の甜心
    2020-12-22 08:11

    Step 1 : First make sure the order of the configure method in the stratup.cs class :

    below i have given the valid order form for asp.net core 3.1

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
    
            app.UseHttpsRedirection();
    
            app.UseRouting();
            app.UseAuthentication();
            
            app.UseAuthorization();
           
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    

    If Step one not working then try Step 2: make sure the token validation parameter and the token generation parameter & algorithm are same for that go to the ConfigureServices method of the startup.cs class and also go to the class or method where you have generated the token in my case it was UserService class

    ConfigureServices method code :

    public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = Configuration.GetConnectionString("mySQLConnectionString");
    
            services.AddDbContext(options => options.UseMySql(connectionString));
            services.AddIdentity(options =>
            {
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = true;
                options.Password.RequiredLength = 5;
            }).AddEntityFrameworkStores().AddDefaultTokenProviders();
    
            services.AddAuthentication(auth =>
            {
                auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                
            }).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidAudience = Configuration["AuthSettings:Audience"],
                    ValidIssuer = Configuration["AuthSettings:Issuer"],
                    RequireExpirationTime = true,
                    IssuerSigningKey =
                        new SymmetricSecurityKey(
                            Encoding.UTF8.GetBytes(Configuration["AuthSettings:key"])),
                    ValidateIssuerSigningKey = true,
    
                };
            });
            services.AddScoped();
            services.AddControllers();
        }
    

    Token Generation code :

     public async Task LoginUserAsync(LoginVIewModel model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);
            if(user == null)
            {
                return new UserManagerResponse
                {
                    Message = "There is no user with that email",
                    iSSuccess= false
                };
            }
            var result = await _userManager.CheckPasswordAsync(user, model.Password);
            if(! result)
            {
                return new UserManagerResponse
                {
                    Message = "Your Provided password not match eith our system ",
                    iSSuccess = false
                };
    
            }
    
            var clims = new[]
            {
                new Claim("Email", model.Email),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["AuthSettings:key"]));
            var token = new JwtSecurityToken(
                issuer: _configuration["AuthSettings:Issuer"],
                audience: _configuration["AuthSettings:Audience"],
                claims: clims,
                expires: DateTime.Now.AddDays(30),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
            string tokenAsString = new JwtSecurityTokenHandler().WriteToken(token);
    
            return new UserManagerResponse
            {
                Message = tokenAsString,
                iSSuccess = true,
                ExpireDate = token.ValidTo
            };
        }
    }
    

    also please note that , In my case I have some spelling mistake in appsetting.json For example in the token generate code i have called the Audince but in the appSetting.json it was Audience . thats why both Audience not match .

                 audience: _configuration["AuthSettings:Audince"]
    

    Appsetting.json code :

    "AllowedHosts": "*",
      "AuthSettings": {
        "key": "TThis is mfw sec test token",
        "Audience": "www.mfw.com",
        "Issuer": "www.mfw.com"
      }

提交回复
热议问题