ASP.NET Core身份验证与JWT:'签名无效'

3
我想基于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”端点(该端点需要授权),在“Authorization”标头中添加“Bearer”,但是我收到了一个响应头:

WWW-Authenticate →Bearer error="invalid_token", error_description="The signature is invalid"

其中文意为:无效的令牌错误,签名无效。

请将解决方案作为答案添加到问题中。 - undefined
1个回答

2

问题已解决

看起来这个秘密是Base64URL编码的,需要进行解码才能在形成签名密钥时使用。

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

2
遇到了同样的问题。我不明白我应该在哪里解码Base64Url代码?根据我的理解,我需要在两个地方使用密钥 - 生成令牌的地方和配置中间件的地方。这两个地方都使用appsetttings.json中的值通过IConfiguration获取。如果令牌以某种方式进行了编码,那么解码的责任应该由中间件来承担。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接