I want to enable authentication based on jwt claims. For some reason the token seems to be invalid, more specifically its signature seems to be the problem.
I tried verifying the signature on https://jwt.io/ and it is verified successfully.
My token is
eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZ2VudCIsImF1dCI6WyJST0xFX0FHRU5UIl0sImlzcyI6Ik1ULVVzZXIiLCJpYXQiOjE1NjA2OTcyMDIsImV4cCI6MTU2MDY5ODEwMn0.WDTPFuEsRRuDfko2dR_5QsWWmyEwUtup-C-V3AF0tE95SJWuNtTiWQCcGoHsNdi-Y7G62pNv4TpaQ3h-deGR3A
And the secret is
9ST5hQe5dUNfAJOQZAtt19uiDhNtKKUt
My Startup.cs class:
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();
}
My test api controller 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";
}
}
I tried to hit the 'localhost:5000/api/values/1' endpoint (which has an authorization attribute), adding the 'Bearer ' to the 'Authorization' header, however I get a response header
WWW-Authenticate →Bearer error="invalid_token", error_description="The signature is invalid"