.net core 3.1 中 JWT 令牌错误 401 Unauthorized

JWT token error 401 Unauthorized in .net core 3.1

我正在学习 DDD 和 JWT,所以我考虑在我的应用程序中同时使用它们。 问题是这样开始的。 当我使用用户名和密码进行请求时,api returns 令牌,但是当我将其放入邮递员的 header 状态 401.

我试过输入 http 和 https。

LoginController.cs

using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Grp.Domain.Entities;
using Grp.Service.Services;

namespace Grp.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly LoginService _loginService;
        private readonly RepresentanteService _representanteService;
        public LoginController(LoginService loginService,
            RepresentanteService representanteService)
        {
            _loginService = loginService;
            _representanteService = representanteService;
        }

        // POST: api/Login
        [HttpPost]
        [AllowAnonymous]
        public ActionResult<dynamic> Authenticate([FromBody]Representante representante)
        {
            try
            {
                representante.Senha = _representanteService.CriptografarSenha(representante.Senha);
                var usuarioValido = _loginService.UsuarioValido(representante);

                if (!usuarioValido)
                    return BadRequest(new { message = "Usuário ou senha inválidos" });


                var token = TokenService.GenerateToken(representante);
                representante.Senha = "";

                return new
                {
                    representante,
                    token
                };
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }
        }
    }
}

ClientesController.cs

using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Grp.Domain.Entities;
using Grp.Service.Services;
using Grp.Service.Validators;

namespace OpersanEM.Api.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class ClientesController : ControllerBase
    {
        private readonly BaseService<Cliente> _service;
        public ClientesController(BaseService<Cliente> service)
        {
            _service = service;
        }
        // GET: api/Clientes
        [HttpGet]
        public IActionResult Get()
        {
            try
            {
                return new ObjectResult(_service.Get());
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // GET: api/Clientes/5
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            try
            {
                return new ObjectResult(_service.Get(id));
            }
            catch (ArgumentException ex)
            {
                return NotFound(ex);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // POST: api/Clientes
        [HttpPost]
        public IActionResult Post([FromBody] Cliente item)
        {
            try
            {
                _service.Post<ClienteValidator>(item);

                return new ObjectResult(item.Id);
            }
            catch (ArgumentNullException ex)
            {
                return NotFound(ex);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // PUT: api/Clientes/5
        [HttpPut("{id}")]
        public IActionResult Put([FromBody] Cliente item)
        {
            try
            {
                _service.Put<ClienteValidator>(item);

                return new ObjectResult(item);
            }
            catch (ArgumentNullException ex)
            {
                return NotFound(ex);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // DELETE: api/ApiWithActions/5
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            try
            {
                _service.Delete(id);

                return new NoContentResult();
            }
            catch (ArgumentException ex)
            {
                return NotFound(ex);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}

Startup.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Grp.Domain.Entities;
using Grp.Infra.CrossCutting;
using Grp.Infra.Data.Context;
using Grp.Infra.Data.Repository;
using Grp.Service.Services;
using System.Text;

namespace Grp.Api
{
    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.AddCors();
            services.AddControllers();

            var key = Encoding.ASCII.GetBytes(Settings.Secret);
            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(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddScoped<SqlContext, SqlContext>();

            services.AddScoped<BaseRepository<Cliente>>();
            services.AddScoped<BaseRepository<Representante>>();

            services.AddScoped<BaseService<Cliente>>();
            services.AddScoped<BaseService<Representante>>();
            services.AddScoped<RepresentanteService>();
            services.AddScoped<LoginService>();

            services.AddScoped<StringCipher>();


        }

        // 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();
            }

            app.UseStaticFiles();
            app.UseRouting();

            app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

            app.UseAuthentication();
            app.UseAuthorization();


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
            });
        }
    }
}

TokenService.cs

using Microsoft.IdentityModel.Tokens;
using Grp.Domain.Entities;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace Grp.Service.Services
{
    public static class TokenService
    {
        public static string GenerateToken(Representante representante)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(Settings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, representante.Nome)
                }),
                Expires = DateTime.UtcNow.AddDays(2),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
    }
}

你找到解决办法了吗?有一段时间我一直在解决同样的问题。最后我解决了它添加 [Authorize(AuthenticationSchemes=JwtBearerDefaults.AuthenticationScheme)] 在我的控制器的装饰器中。

编辑: 如果您不想在每个控制器中设置方案,请在 Startup.cs ConfigureServices()

中配置它
        services.AddAuthorization(options =>
        {
            var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(
                JwtBearerDefaults.AuthenticationScheme);

            defaultAuthorizationPolicyBuilder =
                defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();

            options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
        });

我在 401 响应中遇到了类似的问题。我是这样解决的:

检查 Startup.cs 上的 Configure 方法。您可能没有包含 app.UseAuthentication(),或者您在 app.UseAuthentication() 之前放置了 app.UseAuthorization()。您的配置方法应该类似于以下方法:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            

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

如果您像我一样实施 Identity,您可能在添加 Identity 后让控制器返回 404。然后您添加了:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

类似下面的内容

services.AddAuthentication(x =>
            {
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme;
            })

这解决了 404 错误,但现在没有授权。这是因为现在未设置 DefaultAuthenticationScheme。要解决只需将上面的行更改为

 builder.Services.AddAuthentication(options =>
            {                
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultForbidScheme = JwtBearerDefaults.AuthenticationScheme;
            })

您的 Controller 现在将按预期运行。