使用JWT的ASP.NET Core身份验证:“签名无效”

时间:2019-06-16 17:39:11

标签: authentication asp.net-core jwt

我想基于jwt声明启用身份验证。由于某种原因,令牌似乎无效,更具体地说,它的签名似乎是问题所在。

我尝试验证https://jwt.io/上的签名,并且签名已成功验证。

我的令牌是

  

eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZ2VudCIsImF1dCI6WyJST0xFX0FHRU5UIl0sImlzcyI6Ik1ULVVzZXIiLCJpYXQiOjE1NjA2OTcyMDIsImV4cCI6MTU2MDY5ODEwMn0.WDTPFuEsRRuDfko2dR_5QsWWmyEwUtup-C-V3AF0tE95SJWuNtTiWQCcGoHsNdi-Y7G62pNv4TpaQ3h-deGR3A

秘密是

  

9ST5hQe5dUNfAJOQZAtt19uiDhNtKKUt

我的Startup.cs类:

public void ConfigureServices(IServiceCollection services) 
{

            /*...*/

            var key = Encoding.ASCII.GetBytes("9ST5hQe5dUNfAJOQZAtt19uiDhNtKKUt");
            var signingKey = new SymmetricSecurityKey(key);

            // Authenticate a request 
            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 = signingKey,
                    ValidateAudience = false,
                    ValidateIssuer = false
                };
            });
            // Custom policy to check if a certain claim has a certain value
            services.AddAuthorization(options =>
            {
                options.AddPolicy(
                    "IsAgentPolicy",
                    policy => policy.RequireClaim("aut", "ROLE_AGENT")
                );
            });

            /*...*/
}

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

            app.UseAuthentication();

            app.UseMvc();
        }

我的测试api控制器ValuesController.cs:

    [Route("api/[controller]")]
    public class ValuesController : ControllerBase
    {
        // GET: api/<controller>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        [HttpGet("{id}")]
        [Authorize("IsAgentPolicy")]
        public string Get(int id)
        {
            return "value";
        }
    }

我尝试点击'localhost:5000 / api / values / 1'端点(具有授权属性),将'Bearer'添加到'Authorization'标头中,但是我得到了响应标头

  

WWW-Authenticate→Bearer error =“ invalid_token”,error_description =“签名无效”


1 个答案:

答案 0 :(得分:0)

已解决

  

似乎这个秘密是Base64URL编码的,需要先进行解码,然后才能用于形成签名密钥

var key = Base64UrlEncoder.DecodeBytes("YOUR_SECRET");
SymmetricSecurityKey signingKey = new SymmetricSecurityKey(key);