Search code examples
c#asp.net-web-apijwtowin-middleware

Jwt Bearer Authentication middleware always sets User.Identity.IsAuthenticated to false


I've added UseJwtBearerAuthentication middleware to my application to Authenticate all incoming requests:

public void Configuration(IAppBuilder app)
{

    var config = new HttpConfiguration();
    WebApiConfig.Register(config);
    #region Autofac config

    var container =AutofacWebapiConfig.Initialize(GlobalConfiguration.Configuration);
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

    #endregion
    #region RoutConfig

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    #endregion

    //Register middlewares
    app.UseJwtBearerAuthentication(new MyJwtAuthenticationOptions());
    app.UseAutofacMiddleware(container);
    app.Use<ReadBodyMiddleware>();
    app.UseWebApi(config);

}

And this is my MyJwtAuthenticationOptions class:

public class MyJwtAuthenticationOptions: JwtBearerAuthenticationOptions
{
    public MyJwtAuthenticationOptions()
    {
        var secretkey = ConfigurationManager.AppSettings["SecretKey"].ToString();

        AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active;
        AuthenticationType = "Basic";
        TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretkey)),
            ValidAlgorithms = new string[] { SecurityAlgorithms.HmacSha256Signature }
        };
    }
}

Now let's see how token is generated:

public static string GenerateToken(string userid)
{
    var expireMin = ConfigurationManager.AppSettings["TokenExpirationMinutes"].ToString();
    var secretKey = ConfigurationManager.AppSettings["SecretKey"].ToString();

    byte[] key = Convert.FromBase64String(secretKey);
    SymmetricSecurityKey securityKey = new SymmetricSecurityKey(key);
    var descriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[] {
              new Claim("UserId", userid)}, "Basic"),
        Expires = DateTime.UtcNow.AddMinutes(Convert.ToInt32(expireMin)),
        SigningCredentials = new SigningCredentials(securityKey,
        SecurityAlgorithms.HmacSha256Signature)
    };

    JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
    JwtSecurityToken token = handler.CreateJwtSecurityToken(descriptor);
    return handler.WriteToken(token);
}

But when i put generated token inside Authorization header and send it to server via Postman

HttpContext.Current.User.Identity.IsAuthenticated is always false

Authorization header is correctly in Bearer format enter image description here

enter image description here


Solution

  • My issue was originated from two points:

    point1:

    public static void Register(HttpConfiguration config)
    {
        // Owin auth
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    
        // Web API routes
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
        config.MapHttpAttributeRoutes();
        config.Services.Insert(typeof(ModelBinderProvider), 0,
         new SimpleModelBinderProvider(typeof(DocumentModel), new FromFormDataBinding()));
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
    

    this line was not same as other points of my api that i used Signature

    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    

    Changed to this:

    config.Filters.Add(new HostAuthenticationFilter("Signature"));
    

    point2:

    Inside GenerateTokebn class i was reading secretkey in this way:

    byte[] key = Convert.FromBase64String(secretKey);
    

    changed to this line to be same as MyJwtAuthenticationOptions class:

    byte[] key = Encoding.UTF8.GetBytes(secretKey);