I have this code:

[Authorize] [Route("api/[controller]")] public sealed class UsersController : Controller { // GET api/users/current [HttpGet("current")] public async Task<IActionResult> Current() { var user = await GetCurrentUser(); if (user == null) { return NotFound(); } var result = Mapper.Map<GetUserViewModel>(user); return Ok(result); } } 

I want to make it so that when I try to access the Current method, an unauthorized client, instead of a submission, displays the status code 401. Now returns either the default page or the 404 code if such a page is not set in the routing settings. It is necessary that this code be returned for all methods marked with [Authorize] .

Startup class code:

 public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; AuthOptions.SetAuthOptions(Configuration); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Angular5ASPCore2", Version = "v1" }); }); services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password.RequireDigit = false; options.Password.RequiredLength = 8; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequireNonAlphanumeric = false; options.User.RequireUniqueEmail = true; }) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.Configure<SecurityStampValidatorOptions>(options => options.ValidationInterval = TimeSpan.FromSeconds(10)); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidIssuer = AuthOptions.Issuer, ValidateAudience = true, ValidAudience = AuthOptions.Audience, ValidateLifetime = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AuthOptions.Key)), ValidateIssuerSigningKey = true, }; }); services.AddTransient<IGenericUnitOfWork, GenericUnitOfWork>(); services.AddTransient<IRoleService, RoleService>(); services.AddTransient<IUserSrvice, UserSrvice>(); services.AddTransient<ISinInService, SinInService>(); services.AddTransient<ILoggingService, LoggingService>(); services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseMiddleware<ExceptionHandlerMiddleware>(); Enum.TryParse(Configuration["LogLevel"], true, out LogLevel logLevel); loggerFactory.AddConsole(logLevel); loggerFactory.AddDebug(logLevel); loggerFactory.AddContext(logLevel, Configuration.GetConnectionString("DefaultConnection")); if (env.IsDevelopment()) { loggerFactory.AddFile(Path.Combine(Directory.GetCurrentDirectory(), "logger.txt"), logLevel); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseAuthentication(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Angular5ASPCore2 V1"); }); app.UseMvc(routes => { routes.MapRoute( name: "defaultApi", template: "api/{controller}/{action}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); } } 

update

Made the following crutch: added an AccountController controller with the Login method, which always returns an UnauthorizedResult . There must be an adequate way to solve my problem.

  • What for? What 401 do not like? - Alexey
  • @Alexey can be 401, but the default view with the code 200 is now returned. Apparently you need to correct something somewhere in the Startup class, but I don’t know what - mirypoko

2 answers 2

This code helps (asp.net core 2)

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

    Yes, probably. You have no app.UseAuthentication(); Here is the Startup code on Asp.Net Core for me (Should help). I have all the rules:

     public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "White Drago API", Version = "v1" }); }); services.AddAuthorization(options => { options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build(); } ); //services.AddJwtBearerAuthentication(o => //{ // o.Audience = "myapi"; // o.Authority = "http://localhost:5000"; // o.RequireHttpsMetadata = false; //}); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = new TokenValidationParameters { // укзывает, будет ли валидироваться издатель при валидации токена ValidateIssuer = true, // строка, представляющая издателя ValidIssuer = AuthOptions.Issuer, // будет ли валидироваться потребитель токена ValidateAudience = true, // установка потребителя токена ValidAudience = AuthOptions.Audience, // будет ли валидироваться время существования ValidateLifetime = true, // установка ключа безопасности IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(), // валидация ключа безопасности ValidateIssuerSigningKey = true, }; }); services.AddMvc(); services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(LogLevel.Trace); loggerFactory.AddDebug(); // app.UseMiddleware<LogHeadersMiddleware>(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseAuthentication(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "White Drago API V1"); }); app.UseMvc(); } } 

    }