C#JWT令牌授权始终返回错误

时间:2020-02-11 19:54:49

标签: c# asp.net-core jwt

我遇到了很大的问题。我在API中创建了JWT授权,当我发出生成令牌的请求时就可以了,但是当我尝试通过[Authorize(“ Bearer”)]向某个控制器发出带有Auth标头的请求时,它总是返回 Bearer error =“ invalid_token” ,不,没有Error_Description或类似内容。

我正在使用.Net Core 3.1。

解决方案

我不知道为什么,但是我不能使用多个声明,因此我只在我的令牌生成中使用了一个声明,并且它起作用了。 (?)

这是我的Startup.cs

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using API_allinone.Singleton;
using Microsoft.AspNetCore.SignalR;
using API_allinone.Auth;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authentication.JwtBearer;

namespace API_allinone
{
    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(options => options.AddPolicy("All",
              builder =>
              {
                  builder.AllowAnyHeader()
                         .AllowAnyMethod()
                         .SetIsOriginAllowed((host) => true)
                         .AllowCredentials();
              }));
            services.AddScoped<IAuthenticateService, TokenAuthenticateService>();
            services.AddScoped<IUserService, UserService>();

            services.Configure<AuthConfiguration>(Configuration.GetSection("TokenConfigurations"));

            var Token = Configuration.GetSection("TokenConfigurations").Get<AuthConfiguration>();



            var signingConfiguration = new SigningConfiguration();

            services.AddSingleton(signingConfiguration);

            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 = signingConfiguration.Key,
                    ValidAudience = Token.Audience,
                    ValidIssuer = Token.Issuer,
                    ValidateLifetime = true,
                    ValidateAudience = false,
                    ValidateIssuer = false,
                    ClockSkew = TimeSpan.FromMinutes(0)
                };
            });

            services.AddAuthorization(auth =>
            {
                auth.AddPolicy("Bearer", new AuthorizationPolicyBuilder()
                    .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser().Build());
            });

            services.AddMvc()
                .AddJsonOptions(opt => opt.JsonSerializerOptions.PropertyNamingPolicy = null)
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

            services.AddSignalR();

            services.AddControllers();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider service)
        {

            app.UseDeveloperExceptionPage();

            app.UseRouting();
            app.UseCors("All");
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(configur =>
            {
                configur.MapHub<Hubs.ProdutosHub>("/produtoshub");
                configur.MapHub<Hubs.DashboardHub>("/dashboardhub");
                configur.MapHub<Hubs.GeralHub>("/geralhub");
                //configur.MapControllerRoute("Default", "{controller}/{action=Index}/{id?}");
                configur.MapControllers();
            });

            SDashboard
                .GetInstance()
                .SetContext(service.GetService<IHubContext<Hubs.DashboardHub, Hubs.IDashboardHub>>());

            SGeral
                .GetInstance()
                .SetContext(service.GetService<IHubContext<Hubs.GeralHub, Hubs.IGeralHub>>());
        }
    }
}

SigningConfiguration.cs

using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;

namespace API_allinone.Auth
{
    public class SigningConfiguration
    {
        public SecurityKey Key { get; }
        public SigningCredentials SigningCredentials { get; }

        public SigningConfiguration()
        {
            using (var provider = new RSACryptoServiceProvider(2048))
            {
                Key = new RsaSecurityKey(provider.ExportParameters(true));
            }

            SigningCredentials = new SigningCredentials(Key, SecurityAlgorithms.RsaSha256Signature);
        }
    }
}

和AuthController.cs

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using API_allinone.Auth;
using API_allinone.Model;
using Microsoft.Extensions.Options;

namespace API_allinone.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {

        private readonly IAuthenticateService _authService;
        public AuthController(IAuthenticateService authenticateService)
        {
            _authService = authenticateService;
        }

        public int GetEmpresa()
        {
            int Empresa = 0;

            var User = HttpContext.User.Identity as ClaimsIdentity;
            var Claims = User.Claims;
            var Codigo = User.Claims.Where(w => w.Type == JwtRegisteredClaimNames.Sid).FirstOrDefault()?.Value;

            if (!string.IsNullOrEmpty(Codigo))
                Empresa = Convert.ToInt32(Codigo);

            return Empresa;
        }

        public int GetFuncionario()
        {
            int Funcionario = 0;

            var User = HttpContext.User.Identity as ClaimsIdentity;
            var Claims = User.Claims;
            var Codigo = User.Claims.Where(w => w.Type == ClaimTypes.Actor).FirstOrDefault()?.Value;

            if (!string.IsNullOrEmpty(Codigo))
                Funcionario = Convert.ToInt32(Codigo);

            return Funcionario;
        }

        [HttpPost]
        public IActionResult Post([FromBody]AuthBody AuthRequest, [FromServices]IOptions<AuthConfiguration> AuthConfiguration)
        {
           var Logado = Usuario.LogIn(AuthRequest.Login, AuthRequest.Senha, Empresa.GetId(AuthRequest.Empresa));
            if (_authService.IsAuthenticated(AuthRequest, out string Token))
            {
                return Ok(new
                {
                    Authenticate = true,
                    Created = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Expiration = DateTime.Now.AddSeconds(AuthConfiguration.Value.AccessExpiration),
                    AccessToken = Token,
                    Message = "Acesso Autorizado",
                    Empresa = Empresa.Get(AuthRequest.Empresa),
                    Usuario = Logado
                });
            }

            return BadRequest("Invalid Request");

        }

        [HttpGet]
        [Authorize("Bearer")]
        public IActionResult Valide()
        {
            var funcionario = new Funcionario(GetFuncionario());
            return Ok(new
            {
                Funcionario = funcionario,
                Empresa = Empresa.Get(GetEmpresa()),
                Acesso = Usuario.GetAcesso(funcionario.Id),
                Usuario = Usuario.Get(GetFuncionario(), GetEmpresa())
            });
        }
    }
}

0 个答案:

没有答案