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.