Search code examples
c#.netasp.net-coreiis

ASP. NET Core 8: Error HTTP 500 and returnurl=%2F in the URL


I'm encountering a HTTP 500 error when trying to log in with ASP.NET Core Identity. The error occurs after submitting the login form with valid credentials, and the user is not logged in. After entering credentials and submitting the login form, instead of redirecting to the homepage or the intended URL, I get an HTTP 500 error. There's no detailed error message provided in the browser, just the generic 500 Internal Server Error, i checked the logs and i treally says nothing of value to solve the problem. It only happens on my IIS server, in the develop environment (VS) it works perfectly.

Here's the snipet for the POST and GET methods in my AccountController:

[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
    if (User.Identity.IsAuthenticated)
    {
        return RedirectToAction("Index", "Home");
    }
    ViewData["ReturnUrl"] = returnUrl;
    return View();
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
        if (result.Succeeded)
        {
            _logger.LogInformation("User logged in successfully.");
            return RedirectToLocal(returnUrl);
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

And this is my Program.cs:

using GH.DataContext;
using GH.Models;
using GH.Repository.Abstract;
using GH.Repository.Implementation;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer("name=DefaultConnection"));
builder.Services.AddDbContext<InventoriesDbContext>(options => options.UseSqlServer("name=DefaultConnection"));
builder.Services.AddHttpContextAccessor();
builder.Services.AddAuthorization();
builder.Services.AddScoped<IInventoryRepository, InventoryRepository>();
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
    options.Password.RequireDigit = false;
    options.Password.RequireUppercase = false;
    options.Password.RequireLowercase = false;
    options.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

// Configure authentication
builder.Services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = "/Account/Login"; // Ruta a la página de inicio de sesión
    options.LogoutPath = "/Account/LogOff"; // Ruta a la página de cierre de sesión
    options.AccessDeniedPath = "/Account/AccessDenied"; // Ruta a la página de acceso denegado
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsProduction())
{
    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.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication(); // Add this line to enable authentication middleware
app.UseAuthorization();
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

This is my login view:

@using System.Collections.Generic
@using Microsoft.AspNetCore.Http
@using Microsoft.AspNetCore.Authentication
@using GH.Models.AccountViewModels
@using GH.Models
@using Microsoft.AspNetCore.Identity
@model LoginViewModel
@inject SignInManager<ApplicationUser> SignInManager

@{
    Layout = null;
}
<head>
    <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
    <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
    <link rel="shortcut icon" type="image/png" href="/Images/icon.svg" />

</head>
<div class="container py-5 h-100">
    <div class="row d-flex justify-content-center align-items-center h-100">
        <div class="col-12 col-md-8 col-lg-6 col-xl-5">
            <div class="card text-black" style="border-radius: 1rem; background-color:#B8B8B8">
                <div class="card-body p-5 text-center">
                    <title>Inicio de Sesión</title>
                    <div class="row">
                        <div class="col-md-20">
                            <section>
                                <form asp-controller="Account" asp-action="Login" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal" role="form">
                                    <img src="~/Images/LogoHD.png" class="logo" />
                                    <hr />
                                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                                    <div class="form-group">
                                        <label class="col-md-2 control-label">Correo</label>
                                        <div class="col-md-15">
                                            <input asp-for="Email" class="form-control" />
                                            <span asp-validation-for="Email" class="text-danger"></span>
                                        </div>
                                    </div>
                                    <br />
                                    <div class="form-group">
                                        <label class="col-md-5 control-label">Contraseña</label>
                                        <div class="col-md-15">
                                            <input asp-for="Password" class="form-control" />
                                            <span asp-validation-for="Password" class="text-danger"></span>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <div class="col-md-offset-2 col-md-15">
                                            <br />
                                            <button data-mdb-button-init data-mdb-ripple-init class="btn btn-outline-dark btn-lg px-5" type="submit">Ingresar</button>
                                        </div>
                                    </div>
                                    <div class="col-md-offset-2 col-md-15">
                                    <p>
                                          <a asp-action="Register" asp-route-returnurl="@ViewData["ReturnUrl"]">¿Sin usuario? Regístrate aquí.</a>
                                    </p>
                                    </div>

                                </form>
                            </section>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Checked the logs: In my logs, I'm not seeing any detailed errors regarding the login failure. It just shows that the user failed to log in with a 500 error.

Checked database connection: The database is working fine. I can register users without issues, and they appear in the database running it from Visual Studio.

Check Identity setup: I confirmed that the UserManager and SignInManager are properly configured and injected via dependency injection in the AccountController.

Anonymous auth: enabled.

Form auth: enabled.


Solution

  • I solved it! The app wasn't connecting to the Database, it was a problem in the appsettings, specifically in the appsettings.production.json that was created in the IIS folder, it readed the wrong connection string.

    And in SQLServer i created a new user with all privileges and permissions for the DB.

    And the connection string was changed to

    "DefaultConnection": "Server=MYSERVER;Database=GHInventory;User Id=MYUSER;Password=MYPASSWORD;TrustServerCertificate=True;"