asp.net-mvcauthenticationcookiesauthorizationcookie-authentication

ASP.NET MVC Authorize with login authentication not working


I'm trying to implement the cookie auth in my ASP.NET MVC project, and I already code everything based on my research.

I really don't know what's wrong. I suspect that the folder hierarchy of my project is off, but it can't be it. But can be the razor pages not mapping or creation of an [Authorize] attribute. I don't know

The cookie is being correctly created after the login, but if I put any URL without the cookie, the page loads unauthorized

My intent on the project is to have an open home page with some menus and a hidden admin panel for data management. If there are some other suggestions on how to secure the admin pages I'm all ears.

There are no roles in my project.

Here is my code.

startup.cs

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        var connectionString = Configuration.GetConnectionString("DefaultConnection");

        services.AddControllersWithViews();

        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
        services.AddAuthentication("CookieAuth").AddCookie("CookieAuth", options =>
                {
                    options.Cookie.Name = "CookieAuth";
                    options.LoginPath = "/Secure/Login";

                    //options.ExpireTimeSpan = TimeSpan.FromHours(1);
                    
                    //options.AccessDeniedPath = "/Secure/Login";
                });
        services.AddRazorPages();

        services.AddDbContext<ApplicationContext>(options =>
        {
            options.EnableSensitiveDataLogging();
            options.UseSqlServer("Server=LAPTOP-QJIOM3MT;Database=BasePistas;Trusted_connection=True;");
        });

        services.AddScoped<IUnitOfWork, UnitOfWork>();
        services.AddScoped<IUsuarioBusiness, UsuarioBusiness>();
        services.AddScoped<IPistaBusiness, PistaBusiness>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
       
        app.UseHttpsRedirection();
        app.UseCookiePolicy();
        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            
        });
    }
}

Here is my controller with the authorize attribute:

using Microsoft.AspNetCore.Authentication;

[Authorize]
public class AprovacoesController : Controller
{
    [Authorize]
    public IActionResult Consultar()
    {
        var aprovacoes = _pistaBusiness.Filtrar();
        return View("Consulta",aprovacoes);
    }
}

I think my login auth is correct but I will put it here - the LoginController:

    [AllowAnonymous]
    [HttpPost]
    public async Task<IActionResult> Login(LoginDto model)
    {
        if (ModelState.IsValid)
        {
            var usuario = this._usuarioBusiness.Autenticar(model);

            if (usuario != null)
            {
                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.NameIdentifier, usuario.IdUsuario.ToString()),
                    new Claim(ClaimTypes.Name, usuario.Nome),
                    new Claim(ClaimTypes.GivenName, usuario.Login)
                };

                var identity = new ClaimsIdentity(claims, "CookieAuth");
                var principal = new ClaimsPrincipal(identity);
                

                await HttpContext.SignInAsync("CookieAuth", principal);

                return RedirectToAction("Index", "Home");
            }
            else
            {
                model = new LoginDto();

                TempData["ErroAutenticacao"] = "Usuário ou senha inválido";
                return View(model);
            }
        }

        return View(model);
    }

    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync("CookieAuth");
        return RedirectToAction("Login", "Secure");
    }

Here is the folder hierarchy

Here is the folder hierarchy


Solution

  • I already find my solution.

    Everything is right !!

    The reason that the authorization was not working was that I was debugging with IIS Expres and not with my project webapp.

    enter image description here

    I'm still learning a lot about ASP.NET and The Visual Studio Community plataform, this details really matter.

    If anyone wants to use this Auth model, it's working fine.