【问题标题】:Problem getting a security token when using Json Web Token in a web API在 Web API 中使用 Json Web 令牌时获取安全令牌时出现问题
【发布时间】:2019-12-19 08:59:40
【问题描述】:

在为 Web API 提供适当的验证时,我无法获得安全令牌。

我已经制作了一个有效的网络 API。我现在正在添加一个 j.w.t 授权来获取数据。我遇到了一个问题,即在输入正确的 URL 路由后,我收到了 HTTP 500 错误,它旨在向我显示安全令牌。我将在下面提供代码。

Setup.cs

namespace testsitegp
{
    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.AddScoped<ICostomerRepository, CustomerRepository>();
            services.AddScoped<IOrderItemRepository, OrderItemRepository>();
            services.AddScoped<IOrderRepository, OrderRepository>();
            services.AddScoped<IProductRepository, ProductRepository>();
            services.AddScoped<ISalespersonRepository, SalespersonRepository>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            var connection = "Server=tcp:testsitegp.database.windows.net,1433;Initial Catalog=H_Plus_Sports;Persist Security Info=False;" +
                "User ID=-------;Password=---------;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";

            services.AddDbContext<H_Plus_SportsContext>(options => options.UseSqlServer(connection));

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "JwtBearer";
                options.DefaultChallengeScheme = "JwtBearer";
            })
            .AddJwtBearer("JwtBearer", jwtOptions =>
            {
                jwtOptions.TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey = TokenController.SIGNING_KEY,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.FromMinutes(5)
                };
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}

TokenController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace testsitegp.Controllers
{
    public class TokenController : Controller
    {
        private const string SECRET_KEY = "GSATDEHFG";
        public static readonly SymmetricSecurityKey SIGNING_KEY = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(SECRET_KEY));

        [HttpGet]
        [Route("api/Token/{username}/{password}")]
        public IActionResult Get(string username, string password)
        {
            if (username == password)
                return new ObjectResult(GenerateToken(username));
            else
                return BadRequest();
        }

        private string GenerateToken(string username)
        {
            var token = new JwtSecurityToken(
                claims: new Claim[]
                {
                    new Claim(ClaimTypes.Name, username)
                },
                notBefore: new DateTimeOffset(DateTime.Now).DateTime,
                expires: new DateTimeOffset(DateTime.Now.AddMinutes(60)).DateTime,
                signingCredentials: new SigningCredentials(SIGNING_KEY, SecurityAlgorithms.HmacSha256)
                );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}

A pic of the error page after entering the right route

same page but with developer exception

这是错误信息

An unhandled exception occurred while processing the request.
ArgumentOutOfRangeException: IDX10603: Decryption failed. Keys tried: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
Exceptions caught:
'[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
token: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'
Parameter name: KeySize
Microsoft.IdentityModel.Tokens.SymmetricSignatureProvider..ctor(SecurityKey key, string algorithm, bool willCreateSignatures)

在控制台中

 HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request.
GET - http://testapi.com/api/Token/yo/yo

【问题讨论】:

  • 您的代码在本地工作?你能添加 app.UseDeveloperExceptionPage();在您当前的环境中?
  • 我尝试翻转身份验证和 MVC 并没有改变任何东西@RyanWilson
  • @gpjs 我注意到您在ConfigureServices 中两次调用.AddMVC(),您能否将错误消息添加到您的帖子而不是链接。
  • @jotade 我添加了一张带有开发者例外的新图片。
  • @RyanWilson 你的权利,我删除了 .addMVC() 之一,并将错误消息添加到帖子中。

标签: c# api jwt authorization token


【解决方案1】:

您的 SECRET_KEY 似乎太短,至少需要 128 位 Not able to validate JSON Web token with .net - key to short

【讨论】:

    猜你喜欢
    • 2015-09-19
    • 2016-06-09
    • 1970-01-01
    • 2020-11-13
    • 2016-07-20
    • 2021-10-20
    • 1970-01-01
    • 2018-06-11
    • 2017-09-15
    相关资源
    最近更新 更多