In VS2022 development, suddently I was unable to redirect to login page

Dondon510 221 Reputation points
2022-10-17T16:25:10.603+00:00

I'm panic now, I don't understand why my ASP MVC NETCore 6 doesn't automatically redirect to login page (in development, VS2022), I didn't make any changes to program.cs but this was happened after I rebooted the machine for Window Update.

anybody please help me?

program.cs (I have removed some unrelevant parts)

using Microsoft.AspNetCore.Authentication.Cookies;  
using Microsoft.AspNetCore.DataProtection;  
using Microsoft.AspNetCore.Mvc;  
using Microsoft.AspNetCore.Server.Kestrel.Core;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.EntityFrameworkCore.Infrastructure;  
using System.Configuration;  
  
var builder = WebApplication.CreateBuilder(args);  
  
builder.Services.AddScheduler((sender, args) =>  
{  
    args.SetObserved();  
});  
  
builder.Services.AddCors(options =>  
{  
    options.AddPolicy(name: "_myAllowSpecificOrigins",  
                      builder =>  
                      {  
                          builder.WithOrigins(hosts);  
                      });  
});  
  
builder.Services.AddDataProtection()  
                .SetApplicationName(PrimeIoT.SIM.Models.AppSettings.Application.Name)  
                .PersistKeysToFileSystem(new DirectoryInfo(PrimeIoT.SIM.Models.AppSettings.Path.Key_Ring))  
                .SetDefaultKeyLifetime(TimeSpan.FromDays(14));  
  
builder.Services.AddDistributedMemoryCache();  
  
// sengaja dibuat spt ini, utk cek session, HARUS dimatikan, masih dicari cara matikan session!  
builder.Services.AddSession(so =>  
{  
    so.Cookie.HttpOnly = true;  
    so.Cookie.IsEssential = true;  
});  
  
builder.Services.AddScoped<IUserManager, UserManager>();  
builder.Services.AddScoped<IUserRepository, UserRepository>();  
  
builder.Services.AddDbContext<CookieReadersContext>(options =>  
{  
    options.UseNpgsql(pgSQLConnectionString);  
});  
  
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>  
{  
    options.LoginPath = "/User/Login";  
    options.AccessDeniedPath = "/User/Login";  
    options.LogoutPath = "/User/Logout";  
    options.SlidingExpiration = true;  
    options.ExpireTimeSpan = TimeSpan.FromMinutes(PrimeIoT.SIM.Models.AppSettings.Application.SESSION_TIMEOUT);  
    options.Cookie.MaxAge = options.ExpireTimeSpan;  
});  
  
builder.Services.AddTransient<CustomCookieAuthenticationEvents>();  
  
builder.Services.AddHttpContextAccessor();  
builder.Services.AddMemoryCache();  
  
builder.Services.AddAntiforgery(opts => opts.Cookie.Name = "__RequestVerificationToken");  
builder.Services.AddControllersWithViews()  
    .AddSessionStateTempDataProvider();  
  
builder.Services.Configure<KestrelServerOptions>(options =>  
{  
    options.AllowSynchronousIO = true;  
});  
  
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();  
  
builder.Services.Configure<CookiePolicyOptions>(options =>  
{  
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.    
    options.Secure = CookieSecurePolicy.Always;  
    options.CheckConsentNeeded = context => true;  
    options.MinimumSameSitePolicy = SameSiteMode.None;  
});  
  
builder.Services.AddMvc(option =>  
{  
    option.EnableEndpointRouting = false;  
}).AddNewtonsoftJson();  
  
// Add websocket services  
builder.Services.AddWebSocketManager();  
  
// Add services to the container.  
builder.Services.AddControllersWithViews();  
  
// Add httpclient to the container.  
builder.Services.AddHttpClient();  
  
if (!builder.Environment.IsDevelopment())  
{  
    builder.WebHost.UseKestrel(serverOptions =>  
    {  
        serverOptions.ListenAnyIP(7228);  
    });  
}  
  
var app = builder.Build();  
app.UseMiddleware<PrimeIoT.SIM.Models.AuthExpireCheckMiddleware>();  
  
// Configure the HTTP request pipeline.  
if (!app.Environment.IsDevelopment())  
{  
    app.UseExceptionHandler("/Home/Error");  
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
    app.UseHsts();  
}  
  
app.UsePathBase(PrimeIoT.SIM.Models.AppSettings.Path.Deployment);  
app.UseCors(hosts);  
app.UseCookiePolicy();  
app.UseAuthentication();  
  
app.UseHttpsRedirection();  
app.UseStaticFiles();  
app.UseRouting();  
app.UseAuthorization();  
app.UseSession();  
app.MapControllerRoute(  
    name: "default",  
    pattern: "{controller=Home}/{action=Index}/{id?}");  
  
app.Run();  
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,400 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Dondon510 221 Reputation points
    2022-10-18T00:46:19.12+00:00

    251316-untitled.png

    This is suddenly happened after I rebooted my notebook for Windows update!, it should be routes to /user/login

    HomeController --> looks like it doesn't arrive here!

        public IActionResult Index(string ReturnUrl = null)  
        {  
            if (!Url.IsLocalUrl(ReturnUrl))  
            {  
                return RedirectToAction("Login", "User");  
            }  
    
            if (!string.IsNullOrEmpty(ReturnUrl))  
            {  
                Redirect(ReturnUrl);  
            }  
    
            return View();  
        }  
    

    UserController

        [HttpGet]  
        [Route("/User/Login")]  
        [AllowAnonymous]  
        public IActionResult Login(string ReturnUrl = null)   --> looks like it doesn't arrive here!  
        {  
            Views.User.Login login = new Views.User.Login();  
            login.ReturnUrl =  (ReturnUrl == null ? "": ReturnUrl);  
    
            return View(login);  
        }  
    

    I didn't set IsPersistent = true,

    public interface IUserManager  
    {  
        Task SignIn(HttpContext httpContext, CookieUserItem user, bool isPersistent = false);  
        Task SignOut(HttpContext httpContext);  
    }  
    
    public async Task SignIn(HttpContext httpContext, CookieUserItem user, bool isPersistent = false)  
            {  
                string authenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme;  
      
                // Generate Claims from DbEntity  
                var claims = GetUserClaims(user);  
      
                // Add Additional Claims from the Context  
                // which might be useful  
                // claims.Add(httpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name));  
      
                ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, authenticationScheme);  
                ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);  
      
                var authProperties = new AuthenticationProperties  
                {  
                    // AllowRefresh = <bool>,  
                    // Refreshing the authentication session should be allowed.  
                    // ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),  
                    // The time at which the authentication ticket expires. A   
                    // value set here overrides the ExpireTimeSpan option of   
                    // CookieAuthenticationOptions set with AddCookie.  
                    // IsPersistent = true,  
                    // Whether the authentication session is persisted across   
                    // multiple requests. Required when setting the   
                    // ExpireTimeSpan option of CookieAuthenticationOptions   
                    // set with AddCookie. Also required when setting   
                    // ExpiresUtc.  
                    // IssuedUtc = <DateTimeOffset>,  
                    // The time at which the authentication ticket was issued.  
                    // RedirectUri = "~/Account/Index"  
                    // The full path or absolute URI to be used as an http   
                    // redirect response value.  
                };  
      
                await httpContext.SignInAsync(authenticationScheme, claimsPrincipal, authProperties);  
            }  
    
    0 comments No comments

  2. Dondon510 221 Reputation points
    2022-10-18T01:17:21.66+00:00

    All,

    Please ignore this, I have resolved it!. this is because I have wrong route path in one of controller!

    0 comments No comments