locked
Getting 404 error instead of 401, when token is expired or when token is not passed Asp.net core 2 RRS feed

  • Question

  • User1644426919 posted

    I created Asp.net-core 2 project and added

    1. api controller authorized by Bearer token.
    2. mvc controllers authorized by CookieAuthenticationDefaults.AuthenticationScheme.

    When i tried to call api published in iis express .it will returned 401 unauthorized .

    When i tried to call api published in iis.it will returned 404 not found.

    I am Getting 404 error instead of 401, when token is expired or when token is not passed

    and my startup

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApiContext>();
            //options =>
            //    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddTransient<ApiContextSeed>();
            //a confirmed email.
            services.AddIdentity<ApplicationUser, IdentityRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail = true;
                config.Password.RequireDigit = false;
                config.Password.RequireLowercase = false;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase = false;
                config.Password.RequiredUniqueChars =0;
                config.Password.RequiredLength = 6;
                config.User.AllowedUserNameCharacters = null;
    
            })
                .AddEntityFrameworkStores<ApiContext>()
                .AddDefaultTokenProviders();
    
            // Add application services.
            services.AddTransient<IEmailSender, EmailSender>();
            services.AddMvc().AddSessionStateTempDataProvider();
            services.AddResponseCaching();
            services.AddAutoMapper();
            services.AddSingleton<IEmailSender, EmailSender>();
            services.AddSingleton<IWizIQSender, WizIQSender>();
            services.AddSingleton<IWizIQClass, WizIQClass>();
            services.AddSingleton<ITimeZone, TimeZone>();
            services.AddSingleton<IPinCodeGenerator, PinCodeGenerator>();
            services.AddScoped<IUnitOfWorkAsync, UnitOfWorkAsync>();
            services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
            services.AddBootstrapPagerGenerator(options =>
            {
                // Use default pager options.
                options.ConfigureDefault();
            });         
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    
                  .AddCookie("UserAuth", options =>
            {
    
                options.LoginPath = string.Empty;
    
    
    
            });      
            services.AddDistributedMemoryCache();         
            #region FlashMessage
    
            services.AddSession();
            // Needed so we can access the user's session.
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped(x => x.GetRequiredService<IHttpContextAccessor>().HttpContext.Session);
    
            services.AddScoped<IMessageProvider, SessionMessageProvider>();
    
            // Customize the message types (i.e. we are using Bootstrap v3 and need to provide a custom-value for the error message-type).
            services.AddScoped<IMessageTypes>(x =>
            {
                return new MessageTypes(error: "danger");
            });
    
            services.AddScoped<IMessengerOptions, MessengerOptions>();
    
            // We are using a stack to hold messages (i.e. LIFO).
            services.AddScoped<IMessenger, StackMessenger>();
    
            #endregion
            services.AddCors(cfg =>
            {
                cfg.AddPolicy("UserPanel", bldr =>
                {
                    bldr.AllowAnyHeader()
                        .AllowAnyMethod()
                    .AllowAnyOrigin();
                });
            });
            //using JWT
            services.AddAuthentication()
                  .AddJwtBearer(cfg =>
                  {
                      cfg.RequireHttpsMetadata = false;
                      cfg.SaveToken = true;
                      cfg.TokenValidationParameters = new TokenValidationParameters()
                      {
                          ValidIssuer = Configuration["Tokens:Issuer"],
                          ValidAudience = Configuration["Tokens:Issuer"],  
                          IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                      };
    
                  });
    
    
            services.AddMvc();
            services.AddSingleton<IEmailSender, EmailSender>();
            //services.AddUrlHelper();
            services.AddTransient<IEmailSender, EmailSender>();
    
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Drossey API", Version = "v1" });
            });
    
    
        } 
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApiContextSeed seeding)
       {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
            }
            else
            {
                 app.UseExceptionHandler("/error");
                app.UseStatusCodePagesWithReExecute("/error");
    
            }
            app.UseStaticFiles();       
            app.UseSession();
            app.UseAuthentication();
            app.UseCors("UserPanel");
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Drossey Api");
            });
            app.UseMvc(routes =>
            {            
                routes.MapRoute(
                name: "areaRoute",
                template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
    
                routes.MapRoute(
                  name: "default",
                  template: "{controller=Home}/{action=Index}/{id?}");
            });           
            seeding.EnsureSeeding().Wait();
        }

    Tuesday, April 10, 2018 12:24 PM

All replies

  • User1168443798 posted

    Hi mbesher,

    I suggest you Press F12 to enable web browser debugger, and check the Network tab to trace the detail requests.

    For this error, I assume the Identity redirect the request to login page when the token is expired. Do you configure any login page?

    I suggest you try code below:

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
             {                 
                 options.Events.OnRedirectToLogin = context =>
                 {
                     context.Response.Headers["Location"] = context.RedirectUri;
                     context.Response.StatusCode = 401;
                     return Task.CompletedTask;
                 };
             });

    Best Regards,

    Edward

    Wednesday, April 11, 2018 2:56 AM
  • User1644426919 posted

    app.UseStatusCodePagesWithReExecute("/error") in startup.cs  hide 401 un-Authorized error when calling api method .

    Saturday, April 14, 2018 1:45 PM
  • User1186658909 posted
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                  .AddCookie("UserAuth", options =>
            {
                options.LoginPath = string.Empty;

    // add an access denied path in your AddCookie options
    options.AccessDeniedPath = "/your-custom-access-denied-path";
    });

    e.g. => Create an action result in any of the controllers to return a status code.

    #region Forbidden Route
    [Route("your-custom-access-denied-path")]
    public IActionResult ForbiddenBlaBla() {
    // any status code you wanted. e.g => 403
    return StatusCode(403);
    }
    #endregion
    Saturday, October 17, 2020 9:44 PM