JWT 토큰 오류 401 Unauthorized in .net core 3.1

Gustavo Moraes

나는 DDD와 JWT를 배우고 있으므로 응용 프로그램에서 둘 다 사용하는 것에 대해 생각했습니다. 문제는 이렇게 시작됩니다. 사용자 이름과 비밀번호로 요청을 수행하면 api가 토큰을 반환하지만 우체부의 헤더 상태 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();
        });

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Bearer 토큰의 401 오류-asp.net Core 3.1

분류에서Dev

JWT 토큰은 항상 401 .net Core 3.1 웹 API를 반환합니다.

분류에서Dev

Apple Store Connect에서 Python JSON 웹 토큰 (JWT) GET 요청 401 오류

분류에서Dev

401 오류-가져 오기를 사용하여 JWT 토큰을 찾을 수 없습니다.

분류에서Dev

ASP.Net Core JWT 토큰 유효성 검사

분류에서Dev

Django RestFramework JWT 토큰 : Get User DoesNotExist 오류

분류에서Dev

.net Framework, OWIN 및 JWT 토큰 가져 오기

분류에서Dev

Microsoft Graph 토큰을 사용하여 Jwt Bearer 토큰으로 ASP.NET Core 웹 API 보안

분류에서Dev

Dynamics CRM 토큰을 사용할 수 없음 (401 Unauthorized)

분류에서Dev

JWT 전달자 토큰 인증이 작동하지 않음 ASP Net Core 웹 API

분류에서Dev

Azure AD 다중 테넌트, JWT 토큰이있는 .Net Core 웹 API

분류에서Dev

Angular POST 및 .NET Core 웹 API-401 권한없는 오류 / CORS

분류에서Dev

JWT 토큰이있는 API에서 GET 요청을 시도하는 동안 오류 401 (승인되지 않음)이 표시됩니다.

분류에서Dev

asp.net core 5.0에서 Bearer 토큰을 제공해도 401이 반환됩니다.

분류에서Dev

401 액세스 토큰 오류시 반환 된 상태

분류에서Dev

CSRF 토큰을 사용한 JMeter 인증 실패 (401 오류)

분류에서Dev

401 Unauthorized when using s3 API for Swift Openstack

분류에서Dev

ASP.NET Core 3.1 Azure AD B2C를 사용하여 Challenge 대신 401 Unauthorized를 반환하는 방법

분류에서Dev

ASP.NET Core SignalR은 Azure AD를 사용하여 401 Unauthorized를 반환합니다.

분류에서Dev

ASP .Net Core 2.2에서 JWT 토큰을 추가 한 후 인증이 작동하지 않습니다.

분류에서Dev

Azure B2C JWT Bearer 토큰을 전달하여 Angular에서 .NET CORE Web API Secure End-point 호출

분류에서Dev

EF .NET Core의 [AllowAnonymous] EndPoint에서 JWT 토큰을 어떻게 읽을 수 있습니까?

분류에서Dev

JWT 및 Azure AD 토큰으로 Net Core 3.0 API를 승인하는 방법이 있습니까?

분류에서Dev

JWT 토큰을 사용하는 Wordpress CPL 반환 오류

분류에서Dev

TokenResponseException을 가져 오는 중 : 401 Unauthorized

분류에서Dev

.NET Core-JWT-SecurityTokenNoExpirationException

분류에서Dev

OAuth2 토큰 새로 고침 오류, 메시지 : '{ "error": "unauthorized_client", "error_description": "Unauthorized client or scope in request." } '

분류에서Dev

구성에서 JWT를 구현하여 ASP.net Core API 오류

분류에서Dev

AspNet core 401-토큰을 추가 할 때 SecurityTokenValidator 없음

Related 관련 기사

  1. 1

    Bearer 토큰의 401 오류-asp.net Core 3.1

  2. 2

    JWT 토큰은 항상 401 .net Core 3.1 웹 API를 반환합니다.

  3. 3

    Apple Store Connect에서 Python JSON 웹 토큰 (JWT) GET 요청 401 오류

  4. 4

    401 오류-가져 오기를 사용하여 JWT 토큰을 찾을 수 없습니다.

  5. 5

    ASP.Net Core JWT 토큰 유효성 검사

  6. 6

    Django RestFramework JWT 토큰 : Get User DoesNotExist 오류

  7. 7

    .net Framework, OWIN 및 JWT 토큰 가져 오기

  8. 8

    Microsoft Graph 토큰을 사용하여 Jwt Bearer 토큰으로 ASP.NET Core 웹 API 보안

  9. 9

    Dynamics CRM 토큰을 사용할 수 없음 (401 Unauthorized)

  10. 10

    JWT 전달자 토큰 인증이 작동하지 않음 ASP Net Core 웹 API

  11. 11

    Azure AD 다중 테넌트, JWT 토큰이있는 .Net Core 웹 API

  12. 12

    Angular POST 및 .NET Core 웹 API-401 권한없는 오류 / CORS

  13. 13

    JWT 토큰이있는 API에서 GET 요청을 시도하는 동안 오류 401 (승인되지 않음)이 표시됩니다.

  14. 14

    asp.net core 5.0에서 Bearer 토큰을 제공해도 401이 반환됩니다.

  15. 15

    401 액세스 토큰 오류시 반환 된 상태

  16. 16

    CSRF 토큰을 사용한 JMeter 인증 실패 (401 오류)

  17. 17

    401 Unauthorized when using s3 API for Swift Openstack

  18. 18

    ASP.NET Core 3.1 Azure AD B2C를 사용하여 Challenge 대신 401 Unauthorized를 반환하는 방법

  19. 19

    ASP.NET Core SignalR은 Azure AD를 사용하여 401 Unauthorized를 반환합니다.

  20. 20

    ASP .Net Core 2.2에서 JWT 토큰을 추가 한 후 인증이 작동하지 않습니다.

  21. 21

    Azure B2C JWT Bearer 토큰을 전달하여 Angular에서 .NET CORE Web API Secure End-point 호출

  22. 22

    EF .NET Core의 [AllowAnonymous] EndPoint에서 JWT 토큰을 어떻게 읽을 수 있습니까?

  23. 23

    JWT 및 Azure AD 토큰으로 Net Core 3.0 API를 승인하는 방법이 있습니까?

  24. 24

    JWT 토큰을 사용하는 Wordpress CPL 반환 오류

  25. 25

    TokenResponseException을 가져 오는 중 : 401 Unauthorized

  26. 26

    .NET Core-JWT-SecurityTokenNoExpirationException

  27. 27

    OAuth2 토큰 새로 고침 오류, 메시지 : '{ "error": "unauthorized_client", "error_description": "Unauthorized client or scope in request." } '

  28. 28

    구성에서 JWT를 구현하여 ASP.net Core API 오류

  29. 29

    AspNet core 401-토큰을 추가 할 때 SecurityTokenValidator 없음

뜨겁다태그

보관