Authorize Core Authorize attribute does not work with JWT

I want to implement JVT security in ASP.Net Core. For now, all I want to do is read the carrier tokens in the Authorization header and check them against my criteria. I do not need (and do not want) to include ASP.Net Identity. In fact, I try to avoid using as many things as possible that MVC adds as much as possible if they really don't need me.

I created a minimal project that demonstrates the problem. To see the source code, just view the change history. I expected this pattern to reject all requests for / api / icons if they do not contain an HTTP Authorization header with an appropriate carrier token. The sample actually resolves all requests .

Startup.cs

 using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Routing; using Microsoft.IdentityModel.Tokens; using System.Text; using System; using Newtonsoft.Json.Serialization; namespace JWTSecurity { public class Startup { public IConfigurationRoot Configuration { get; set; } public Startup(IHostingEnvironment env) { IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath); Configuration = builder.Build(); } public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.AddAuthentication(); services.AddMvcCore().AddJsonFormatters(options => options.ContractResolver = new CamelCasePropertyNamesContractResolver()); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); app.UseJwtBearerAuthentication(new JwtBearerOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("supersecretkey")), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero } }); app.UseMvc(routes => routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}")); } } } 

Controllers / IconsController.cs

 using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace JWTSecurity.Controllers { [Route("api/[controller]")] public class IconsController : Controller { [Authorize] public IActionResult Get() { return Ok("Some content"); } } } 
+21
source share
4 answers

Found it!

The main problem in this line is:

 services.AddMvcCore().AddJsonFormatters(options => options.ContractResolver = new CamelCasePropertyNamesContractResolver()); 

I noticed that by switching from AddMvcCore () to AddMvc (), authorization suddenly started working! After digging into the ASP.NET source code to see what AddMvc() does, I realized that I needed a second call, IMvcBuilder.AddAuthorization() .

 services.AddMvcCore() .AddAuthorization() // Note - this is on the IMvcBuilder, not the service collection .AddJsonFormatters(options => options.ContractResolver = new CamelCasePropertyNamesContractResolver()); 
+48
source

You also use identity authentication and implicitly verify cookie authentication. You may be logged in with an authentication scheme and called for successful authentication.

Remove the authentication if it is not required (if only jwt authentication is required), otherwise specify the Bearer schema for the Authorize attribute, as shown below:

 [Authorize(ActiveAuthenticationSchemes = "Bearer")] 
+20
source

For those who even tried previewing the answers and were unable to solve the problem, the following shows how this problem was solved in my case.

 [Authorize(AuthenticationSchemes="Bearer")] 
+4
source

Add authentication schemes to the Authorize attribute for the carrier with Json Web Token [Authenticate (AuthenticationSchemes = "Media")]

-1
source

Source: https://habr.com/ru/post/1259874/


All Articles