JWT request can't go through Authorize policy












0















I am implementing JWT Authorization on Asp.Net but I am having a trouble here. When I am trying to access the Dashboard/Home controller's method I am always recieving '401 Unauthorized' response. According to my research I can say that the request can not go through



[Authorize(Policy = "ApiUser")]


But when comment that statement I recieve an error here



var userId = _caller.Claims.Single(c => c.Type == "id");


Which states that sequence conatains no appropriate elements, and if I will print the



_httpContextAccessor.HttpContext.User.Claims


I basically recieve a ''.
Also I want you to notice that the token is
correct

I am testing the application with help of postman

I stacked on this error for two days and really rely on your help. Tell me if some additional code is needed.

Code:

Dashboard Controller:



 [Authorize(Policy = "ApiUser")]
[Route("api/[controller]/[action]")]
public class DashboardController : Controller
{
private readonly ClaimsPrincipal _caller;
private readonly BackendContext _appDbContext;
private readonly IHttpContextAccessor _httpContextAccessor;

public DashboardController(UserManager<AppUser> userManager, BackendContext appDbContext, IHttpContextAccessor httpContextAccessor)
{
_caller = httpContextAccessor.HttpContext.User;
_appDbContext = appDbContext;
_httpContextAccessor = httpContextAccessor;
}

// GET api/dashboard/home

[HttpGet]
public async Task<IActionResult> Home()
{
// retrieve the user info
//HttpContext.User
//return new OkObjectResult(_httpContextAccessor.HttpContext.User.Claims);
var userId = _caller.Claims.Single(c => c.Type == "id");

var customer = await _appDbContext.Customers.Include(c => c.Identity).SingleAsync(c => c.Identity.Id == userId.Value);

return new OkObjectResult(new
{
Message = "This is secure API and user data!",
customer.Identity.FirstName,
customer.Identity.LastName,
customer.Identity.PictureUrl,
customer.Identity.FacebookId,
customer.Location,
customer.Locale,
customer.Gender
});
}
}


Startup:



public class Startup
{
private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"; // todo: get this from somewhere secure
private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<BackendContext>()
.AddDefaultTokenProviders();

services.AddDbContext<BackendContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly("Backend")));

services.AddSingleton<IJwtFactory, JwtFactory>();
var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

// Configure JwtIssuerOptions
services.Configure<JwtIssuerOptions>(options =>
{
options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
});

var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

ValidateAudience = true,
ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

ValidateIssuerSigningKey = true,
IssuerSigningKey = _signingKey,

RequireExpirationTime = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

}).AddJwtBearer(configureOptions =>
{
configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
configureOptions.TokenValidationParameters = tokenValidationParameters;
configureOptions.SaveToken = true;
});

// api user claim policy
services.AddAuthorization(options =>
{
options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
});

// add identity
var builder = services.AddIdentityCore<AppUser>(o =>
{
// configure identity options
o.Password.RequireDigit = false;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonAlphanumeric = false;
o.Password.RequiredLength = 6;
});
builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
builder.AddEntityFrameworkStores<BackendContext>().AddDefaultTokenProviders();

services.AddAutoMapper();

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddDbContext<BackendContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
b => b.MigrationsAssembly("Backend")));
services.AddTransient<IStoreService, StoreService>();
services.AddMvc();//.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseDefaultFiles();
app.UseStaticFiles();

app.UseMvc();
}
}


Constants (used in startup):



 public static class Constants
{
public static class Strings
{
public static class JwtClaimIdentifiers
{
public const string Rol = "rol", Id = "id";
}

public static class JwtClaims
{
public const string ApiAccess = "api_access";
}
}
}









share|improve this question





























    0















    I am implementing JWT Authorization on Asp.Net but I am having a trouble here. When I am trying to access the Dashboard/Home controller's method I am always recieving '401 Unauthorized' response. According to my research I can say that the request can not go through



    [Authorize(Policy = "ApiUser")]


    But when comment that statement I recieve an error here



    var userId = _caller.Claims.Single(c => c.Type == "id");


    Which states that sequence conatains no appropriate elements, and if I will print the



    _httpContextAccessor.HttpContext.User.Claims


    I basically recieve a ''.
    Also I want you to notice that the token is
    correct

    I am testing the application with help of postman

    I stacked on this error for two days and really rely on your help. Tell me if some additional code is needed.

    Code:

    Dashboard Controller:



     [Authorize(Policy = "ApiUser")]
    [Route("api/[controller]/[action]")]
    public class DashboardController : Controller
    {
    private readonly ClaimsPrincipal _caller;
    private readonly BackendContext _appDbContext;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public DashboardController(UserManager<AppUser> userManager, BackendContext appDbContext, IHttpContextAccessor httpContextAccessor)
    {
    _caller = httpContextAccessor.HttpContext.User;
    _appDbContext = appDbContext;
    _httpContextAccessor = httpContextAccessor;
    }

    // GET api/dashboard/home

    [HttpGet]
    public async Task<IActionResult> Home()
    {
    // retrieve the user info
    //HttpContext.User
    //return new OkObjectResult(_httpContextAccessor.HttpContext.User.Claims);
    var userId = _caller.Claims.Single(c => c.Type == "id");

    var customer = await _appDbContext.Customers.Include(c => c.Identity).SingleAsync(c => c.Identity.Id == userId.Value);

    return new OkObjectResult(new
    {
    Message = "This is secure API and user data!",
    customer.Identity.FirstName,
    customer.Identity.LastName,
    customer.Identity.PictureUrl,
    customer.Identity.FacebookId,
    customer.Location,
    customer.Locale,
    customer.Gender
    });
    }
    }


    Startup:



    public class Startup
    {
    private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"; // todo: get this from somewhere secure
    private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

    public Startup(IConfiguration configuration)
    {
    Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
    services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<BackendContext>()
    .AddDefaultTokenProviders();

    services.AddDbContext<BackendContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
    b => b.MigrationsAssembly("Backend")));

    services.AddSingleton<IJwtFactory, JwtFactory>();
    var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

    // Configure JwtIssuerOptions
    services.Configure<JwtIssuerOptions>(options =>
    {
    options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
    options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
    options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
    });

    var tokenValidationParameters = new TokenValidationParameters
    {
    ValidateIssuer = true,
    ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

    ValidateAudience = true,
    ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

    ValidateIssuerSigningKey = true,
    IssuerSigningKey = _signingKey,

    RequireExpirationTime = false,
    ValidateLifetime = true,
    ClockSkew = TimeSpan.Zero
    };

    services.AddAuthentication(options =>
    {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    }).AddJwtBearer(configureOptions =>
    {
    configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
    configureOptions.TokenValidationParameters = tokenValidationParameters;
    configureOptions.SaveToken = true;
    });

    // api user claim policy
    services.AddAuthorization(options =>
    {
    options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
    });

    // add identity
    var builder = services.AddIdentityCore<AppUser>(o =>
    {
    // configure identity options
    o.Password.RequireDigit = false;
    o.Password.RequireLowercase = false;
    o.Password.RequireUppercase = false;
    o.Password.RequireNonAlphanumeric = false;
    o.Password.RequiredLength = 6;
    });
    builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
    builder.AddEntityFrameworkStores<BackendContext>().AddDefaultTokenProviders();

    services.AddAutoMapper();

    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
    services.AddDbContext<BackendContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
    b => b.MigrationsAssembly("Backend")));
    services.AddTransient<IStoreService, StoreService>();
    services.AddMvc();//.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    app.UseAuthentication();
    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseMvc();
    }
    }


    Constants (used in startup):



     public static class Constants
    {
    public static class Strings
    {
    public static class JwtClaimIdentifiers
    {
    public const string Rol = "rol", Id = "id";
    }

    public static class JwtClaims
    {
    public const string ApiAccess = "api_access";
    }
    }
    }









    share|improve this question



























      0












      0








      0








      I am implementing JWT Authorization on Asp.Net but I am having a trouble here. When I am trying to access the Dashboard/Home controller's method I am always recieving '401 Unauthorized' response. According to my research I can say that the request can not go through



      [Authorize(Policy = "ApiUser")]


      But when comment that statement I recieve an error here



      var userId = _caller.Claims.Single(c => c.Type == "id");


      Which states that sequence conatains no appropriate elements, and if I will print the



      _httpContextAccessor.HttpContext.User.Claims


      I basically recieve a ''.
      Also I want you to notice that the token is
      correct

      I am testing the application with help of postman

      I stacked on this error for two days and really rely on your help. Tell me if some additional code is needed.

      Code:

      Dashboard Controller:



       [Authorize(Policy = "ApiUser")]
      [Route("api/[controller]/[action]")]
      public class DashboardController : Controller
      {
      private readonly ClaimsPrincipal _caller;
      private readonly BackendContext _appDbContext;
      private readonly IHttpContextAccessor _httpContextAccessor;

      public DashboardController(UserManager<AppUser> userManager, BackendContext appDbContext, IHttpContextAccessor httpContextAccessor)
      {
      _caller = httpContextAccessor.HttpContext.User;
      _appDbContext = appDbContext;
      _httpContextAccessor = httpContextAccessor;
      }

      // GET api/dashboard/home

      [HttpGet]
      public async Task<IActionResult> Home()
      {
      // retrieve the user info
      //HttpContext.User
      //return new OkObjectResult(_httpContextAccessor.HttpContext.User.Claims);
      var userId = _caller.Claims.Single(c => c.Type == "id");

      var customer = await _appDbContext.Customers.Include(c => c.Identity).SingleAsync(c => c.Identity.Id == userId.Value);

      return new OkObjectResult(new
      {
      Message = "This is secure API and user data!",
      customer.Identity.FirstName,
      customer.Identity.LastName,
      customer.Identity.PictureUrl,
      customer.Identity.FacebookId,
      customer.Location,
      customer.Locale,
      customer.Gender
      });
      }
      }


      Startup:



      public class Startup
      {
      private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"; // todo: get this from somewhere secure
      private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

      public Startup(IConfiguration configuration)
      {
      Configuration = configuration;
      }

      public IConfiguration Configuration { get; }

      public void ConfigureServices(IServiceCollection services)
      {
      services.AddIdentity<IdentityUser, IdentityRole>()
      .AddEntityFrameworkStores<BackendContext>()
      .AddDefaultTokenProviders();

      services.AddDbContext<BackendContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
      b => b.MigrationsAssembly("Backend")));

      services.AddSingleton<IJwtFactory, JwtFactory>();
      var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

      // Configure JwtIssuerOptions
      services.Configure<JwtIssuerOptions>(options =>
      {
      options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
      options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
      options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
      });

      var tokenValidationParameters = new TokenValidationParameters
      {
      ValidateIssuer = true,
      ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

      ValidateAudience = true,
      ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

      ValidateIssuerSigningKey = true,
      IssuerSigningKey = _signingKey,

      RequireExpirationTime = false,
      ValidateLifetime = true,
      ClockSkew = TimeSpan.Zero
      };

      services.AddAuthentication(options =>
      {
      options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
      options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

      }).AddJwtBearer(configureOptions =>
      {
      configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
      configureOptions.TokenValidationParameters = tokenValidationParameters;
      configureOptions.SaveToken = true;
      });

      // api user claim policy
      services.AddAuthorization(options =>
      {
      options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
      });

      // add identity
      var builder = services.AddIdentityCore<AppUser>(o =>
      {
      // configure identity options
      o.Password.RequireDigit = false;
      o.Password.RequireLowercase = false;
      o.Password.RequireUppercase = false;
      o.Password.RequireNonAlphanumeric = false;
      o.Password.RequiredLength = 6;
      });
      builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
      builder.AddEntityFrameworkStores<BackendContext>().AddDefaultTokenProviders();

      services.AddAutoMapper();

      services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
      services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
      services.AddDbContext<BackendContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
      b => b.MigrationsAssembly("Backend")));
      services.AddTransient<IStoreService, StoreService>();
      services.AddMvc();//.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
      }
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
      if (env.IsDevelopment())
      {
      app.UseDeveloperExceptionPage();
      }
      app.UseAuthentication();
      app.UseDefaultFiles();
      app.UseStaticFiles();

      app.UseMvc();
      }
      }


      Constants (used in startup):



       public static class Constants
      {
      public static class Strings
      {
      public static class JwtClaimIdentifiers
      {
      public const string Rol = "rol", Id = "id";
      }

      public static class JwtClaims
      {
      public const string ApiAccess = "api_access";
      }
      }
      }









      share|improve this question
















      I am implementing JWT Authorization on Asp.Net but I am having a trouble here. When I am trying to access the Dashboard/Home controller's method I am always recieving '401 Unauthorized' response. According to my research I can say that the request can not go through



      [Authorize(Policy = "ApiUser")]


      But when comment that statement I recieve an error here



      var userId = _caller.Claims.Single(c => c.Type == "id");


      Which states that sequence conatains no appropriate elements, and if I will print the



      _httpContextAccessor.HttpContext.User.Claims


      I basically recieve a ''.
      Also I want you to notice that the token is
      correct

      I am testing the application with help of postman

      I stacked on this error for two days and really rely on your help. Tell me if some additional code is needed.

      Code:

      Dashboard Controller:



       [Authorize(Policy = "ApiUser")]
      [Route("api/[controller]/[action]")]
      public class DashboardController : Controller
      {
      private readonly ClaimsPrincipal _caller;
      private readonly BackendContext _appDbContext;
      private readonly IHttpContextAccessor _httpContextAccessor;

      public DashboardController(UserManager<AppUser> userManager, BackendContext appDbContext, IHttpContextAccessor httpContextAccessor)
      {
      _caller = httpContextAccessor.HttpContext.User;
      _appDbContext = appDbContext;
      _httpContextAccessor = httpContextAccessor;
      }

      // GET api/dashboard/home

      [HttpGet]
      public async Task<IActionResult> Home()
      {
      // retrieve the user info
      //HttpContext.User
      //return new OkObjectResult(_httpContextAccessor.HttpContext.User.Claims);
      var userId = _caller.Claims.Single(c => c.Type == "id");

      var customer = await _appDbContext.Customers.Include(c => c.Identity).SingleAsync(c => c.Identity.Id == userId.Value);

      return new OkObjectResult(new
      {
      Message = "This is secure API and user data!",
      customer.Identity.FirstName,
      customer.Identity.LastName,
      customer.Identity.PictureUrl,
      customer.Identity.FacebookId,
      customer.Location,
      customer.Locale,
      customer.Gender
      });
      }
      }


      Startup:



      public class Startup
      {
      private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"; // todo: get this from somewhere secure
      private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

      public Startup(IConfiguration configuration)
      {
      Configuration = configuration;
      }

      public IConfiguration Configuration { get; }

      public void ConfigureServices(IServiceCollection services)
      {
      services.AddIdentity<IdentityUser, IdentityRole>()
      .AddEntityFrameworkStores<BackendContext>()
      .AddDefaultTokenProviders();

      services.AddDbContext<BackendContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
      b => b.MigrationsAssembly("Backend")));

      services.AddSingleton<IJwtFactory, JwtFactory>();
      var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

      // Configure JwtIssuerOptions
      services.Configure<JwtIssuerOptions>(options =>
      {
      options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
      options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
      options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
      });

      var tokenValidationParameters = new TokenValidationParameters
      {
      ValidateIssuer = true,
      ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

      ValidateAudience = true,
      ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

      ValidateIssuerSigningKey = true,
      IssuerSigningKey = _signingKey,

      RequireExpirationTime = false,
      ValidateLifetime = true,
      ClockSkew = TimeSpan.Zero
      };

      services.AddAuthentication(options =>
      {
      options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
      options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

      }).AddJwtBearer(configureOptions =>
      {
      configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
      configureOptions.TokenValidationParameters = tokenValidationParameters;
      configureOptions.SaveToken = true;
      });

      // api user claim policy
      services.AddAuthorization(options =>
      {
      options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
      });

      // add identity
      var builder = services.AddIdentityCore<AppUser>(o =>
      {
      // configure identity options
      o.Password.RequireDigit = false;
      o.Password.RequireLowercase = false;
      o.Password.RequireUppercase = false;
      o.Password.RequireNonAlphanumeric = false;
      o.Password.RequiredLength = 6;
      });
      builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
      builder.AddEntityFrameworkStores<BackendContext>().AddDefaultTokenProviders();

      services.AddAutoMapper();

      services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
      services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
      services.AddDbContext<BackendContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
      b => b.MigrationsAssembly("Backend")));
      services.AddTransient<IStoreService, StoreService>();
      services.AddMvc();//.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
      }
      public void Configure(IApplicationBuilder app, IHostingEnvironment env)
      {
      if (env.IsDevelopment())
      {
      app.UseDeveloperExceptionPage();
      }
      app.UseAuthentication();
      app.UseDefaultFiles();
      app.UseStaticFiles();

      app.UseMvc();
      }
      }


      Constants (used in startup):



       public static class Constants
      {
      public static class Strings
      {
      public static class JwtClaimIdentifiers
      {
      public const string Rol = "rol", Id = "id";
      }

      public static class JwtClaims
      {
      public const string ApiAccess = "api_access";
      }
      }
      }






      asp.net-web-api authorization jwt asp.net-core-webapi






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 15 '18 at 12:10







      Storm

















      asked Nov 15 '18 at 11:44









      StormStorm

      366




      366
























          1 Answer
          1






          active

          oldest

          votes


















          0














          For your issue is caused by the mismatch configuration between token generation and validation for Issuer and Audience.



          In Startup.cs, you configure ValidateIssuer = true and ValidateAudience = true, but for your provided token, there is no iss and aud.



          Here are two ways for a try:





          • Disable to validate Issuer and Audience



                var tokenValidationParameters = new TokenValidationParameters
            {
            ValidateIssuer = false,
            ValidIssuer = "Issuer",

            ValidateAudience = false,
            ValidAudience = "Audience",

            ValidateIssuerSigningKey = true,
            IssuerSigningKey = _signingKey,

            RequireExpirationTime = false,
            ValidateLifetime = true,
            ClockSkew = TimeSpan.Zero
            };



          • Or, provide the Issuer and Audience while generating the token.



                public IActionResult Login()
            {
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"));
            var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

            var tokeOptions = new JwtSecurityToken(
            issuer: "Issuer",
            audience: "Audience",
            claims: new List<Claim>() { new Claim("rol", "api_access") },
            expires: DateTime.Now.AddMinutes(25),
            signingCredentials: signinCredentials
            );

            var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
            return Ok(new { Token = tokenString });
            }



          Here is a working demo CoreJwt.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53318764%2fjwt-request-cant-go-through-authorize-policy%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            For your issue is caused by the mismatch configuration between token generation and validation for Issuer and Audience.



            In Startup.cs, you configure ValidateIssuer = true and ValidateAudience = true, but for your provided token, there is no iss and aud.



            Here are two ways for a try:





            • Disable to validate Issuer and Audience



                  var tokenValidationParameters = new TokenValidationParameters
              {
              ValidateIssuer = false,
              ValidIssuer = "Issuer",

              ValidateAudience = false,
              ValidAudience = "Audience",

              ValidateIssuerSigningKey = true,
              IssuerSigningKey = _signingKey,

              RequireExpirationTime = false,
              ValidateLifetime = true,
              ClockSkew = TimeSpan.Zero
              };



            • Or, provide the Issuer and Audience while generating the token.



                  public IActionResult Login()
              {
              var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"));
              var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

              var tokeOptions = new JwtSecurityToken(
              issuer: "Issuer",
              audience: "Audience",
              claims: new List<Claim>() { new Claim("rol", "api_access") },
              expires: DateTime.Now.AddMinutes(25),
              signingCredentials: signinCredentials
              );

              var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
              return Ok(new { Token = tokenString });
              }



            Here is a working demo CoreJwt.






            share|improve this answer




























              0














              For your issue is caused by the mismatch configuration between token generation and validation for Issuer and Audience.



              In Startup.cs, you configure ValidateIssuer = true and ValidateAudience = true, but for your provided token, there is no iss and aud.



              Here are two ways for a try:





              • Disable to validate Issuer and Audience



                    var tokenValidationParameters = new TokenValidationParameters
                {
                ValidateIssuer = false,
                ValidIssuer = "Issuer",

                ValidateAudience = false,
                ValidAudience = "Audience",

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = _signingKey,

                RequireExpirationTime = false,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero
                };



              • Or, provide the Issuer and Audience while generating the token.



                    public IActionResult Login()
                {
                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var tokeOptions = new JwtSecurityToken(
                issuer: "Issuer",
                audience: "Audience",
                claims: new List<Claim>() { new Claim("rol", "api_access") },
                expires: DateTime.Now.AddMinutes(25),
                signingCredentials: signinCredentials
                );

                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
                return Ok(new { Token = tokenString });
                }



              Here is a working demo CoreJwt.






              share|improve this answer


























                0












                0








                0







                For your issue is caused by the mismatch configuration between token generation and validation for Issuer and Audience.



                In Startup.cs, you configure ValidateIssuer = true and ValidateAudience = true, but for your provided token, there is no iss and aud.



                Here are two ways for a try:





                • Disable to validate Issuer and Audience



                      var tokenValidationParameters = new TokenValidationParameters
                  {
                  ValidateIssuer = false,
                  ValidIssuer = "Issuer",

                  ValidateAudience = false,
                  ValidAudience = "Audience",

                  ValidateIssuerSigningKey = true,
                  IssuerSigningKey = _signingKey,

                  RequireExpirationTime = false,
                  ValidateLifetime = true,
                  ClockSkew = TimeSpan.Zero
                  };



                • Or, provide the Issuer and Audience while generating the token.



                      public IActionResult Login()
                  {
                  var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"));
                  var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                  var tokeOptions = new JwtSecurityToken(
                  issuer: "Issuer",
                  audience: "Audience",
                  claims: new List<Claim>() { new Claim("rol", "api_access") },
                  expires: DateTime.Now.AddMinutes(25),
                  signingCredentials: signinCredentials
                  );

                  var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
                  return Ok(new { Token = tokenString });
                  }



                Here is a working demo CoreJwt.






                share|improve this answer













                For your issue is caused by the mismatch configuration between token generation and validation for Issuer and Audience.



                In Startup.cs, you configure ValidateIssuer = true and ValidateAudience = true, but for your provided token, there is no iss and aud.



                Here are two ways for a try:





                • Disable to validate Issuer and Audience



                      var tokenValidationParameters = new TokenValidationParameters
                  {
                  ValidateIssuer = false,
                  ValidIssuer = "Issuer",

                  ValidateAudience = false,
                  ValidAudience = "Audience",

                  ValidateIssuerSigningKey = true,
                  IssuerSigningKey = _signingKey,

                  RequireExpirationTime = false,
                  ValidateLifetime = true,
                  ClockSkew = TimeSpan.Zero
                  };



                • Or, provide the Issuer and Audience while generating the token.



                      public IActionResult Login()
                  {
                  var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("iNivDmHLpUA223sqsfhqGbMRdRj1PVkH"));
                  var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                  var tokeOptions = new JwtSecurityToken(
                  issuer: "Issuer",
                  audience: "Audience",
                  claims: new List<Claim>() { new Claim("rol", "api_access") },
                  expires: DateTime.Now.AddMinutes(25),
                  signingCredentials: signinCredentials
                  );

                  var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
                  return Ok(new { Token = tokenString });
                  }



                Here is a working demo CoreJwt.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 16 '18 at 6:40









                Tao ZhouTao Zhou

                6,88331332




                6,88331332
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53318764%2fjwt-request-cant-go-through-authorize-policy%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Xamarin.iOS Cant Deploy on Iphone

                    Glorious Revolution

                    Dulmage-Mendelsohn matrix decomposition in Python