0

I am trying to validate JWT token and on request header passing bearer token . The header gives response as only www-authenticate →Bearer . There are no other errors related to issuer or anything else . Addition to that it responds with 401 since it is not authenticating the token . And due to lack of header information I am unable to get what is going wrong here which is relating to this error.

Here is my Startup.cs config

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(jwtBearerOptions =>
{
    jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidateActor = false,
        ValidateAudience = false,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,

        ValidIssuer = Configuration["JwtIssuer"],
        ValidAudience = Configuration["JwtExpireDays"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes
                                           (Configuration["JwtKey"]))
    };
});

var policy = new AuthorizationPolicyBuilder()
   .RequireAuthenticatedUser()
   .Build();

services.AddMvc(config =>
{
    config.Filters.Add(new AuthorizeFilter(policy));
    //config.ModelBinderProviders.Insert(0, new BaseEntityModelBinderProvider());
})

The token generator -

protected async Task<string> GenerateJwtToken(string email, IdentityUser user)
{
    var claims = new List<Claim>
    {
        new Claim(JwtRegisteredClaimNames.Sub, email),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(ClaimTypes.NameIdentifier, user.Id)
    };

    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"]));
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"]));

    var token = new JwtSecurityToken(
        _configuration["JwtIssuer"],
        _configuration["JwtIssuer"],
        claims,
        expires: expires,
        signingCredentials: creds
    );

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

On requesting the client with Bearer token the response is nothing but

Request Header

Authorization:Bearer <token>

Response headers -

content-length →0
date →Thu, 08 Mar 2018 05:25:23 GMT
server →Kestrel
www-authenticate →Bearer

console information -

796ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 140.7756ms 401
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:50954/api/clinic application/json
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12]
      AuthenticationScheme: Bearer was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action eMedHat.SurveyPortal.Controllers.Api.ClinicApiController.GetClinics (eMedHat.SurveyPortal) in 73.5234ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 120.6734ms 401
Joy
  • 6,438
  • 8
  • 44
  • 75
  • Your question is not very clear. What does "JWT Token says nothing but..." mean? Pls. click on edit and change the headline and also add a clear question to the body. – jps Mar 08 '18 at 08:16
  • @jps I have edited the question title please take a look and let me know if it is preferrable – Joy Mar 08 '18 at 08:21
  • The point is not to squeeze the whole question into the title. The title should only contain a very short description of the problem. In the body you can and should write more (and not only code). Consider you are the reader who knows nothing about your project. Would you understand the question? – jps Mar 08 '18 at 08:48
  • @jps I am sorry . I have modified the title and the question description as well . Thanks for making me realize that – Joy Mar 08 '18 at 09:23
  • Any information being logged to the console? – Brad Mar 08 '18 at 09:38
  • @Brad I have updated with console information bits – Joy Mar 08 '18 at 12:03
  • You're setting the `ValidAudience` option to the config value `JwtExpireDays`. You may not be validating the audience but it just doesn't look right. – Brad Mar 08 '18 at 22:18
  • Can you show how you are sending the request. Is it from Javascript in a browser or Postman? I've seen this before when forgetting to include the `Bearer` prefix in the Authorization header. – Brad Mar 08 '18 at 22:22

0 Answers0