I'm not exactly sure what is relevant here, so I'm going to provide you with my Program.cs and ExceptionMiddleware.cs code:
Program.cs:
Code:
using BaseStack.Data;
using BaseStack.Library.Classes;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDeniedPath";
});
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseAuthentication();
app.UseAuthorization();
app.UseMiddleware<ExceptionMiddleware>();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
app.MapRazorPages();
app.Run();
ExceptionMiddleware.cs:
Code:
using BaseStack.Library.Exceptions;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Text.Json;
namespace BaseStack.Library.Classes
{
public class ExceptionMiddleware
{
private readonly RequestDelegate next;
public ExceptionMiddleware(RequestDelegate _next)
{
next = _next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
var message = "An error occurred while processing your request.";
var response = context.Response;
response.ContentType = "application/json";
if (ex is UnauthenticatedException)
{
message = "Authentication is required and has failed or has not yet been provided.";
//context.Response.Redirect("/Account/Login");
response.StatusCode = (int)HttpStatusCode.Unauthorized;
} else if (ex is UnauthorizationException)
{
message = "You do not have permission to access this resource.";
response.StatusCode = (int)HttpStatusCode.Forbidden;
} else if (ex is BusinessLogicException)
{
response.StatusCode = (int)HttpStatusCode.BadRequest;
message = ex.Message;
}
else if (ex is BusinessLogicException)
{
response.StatusCode = (int)HttpStatusCode.InternalServerError;
message = ex.Message;
} else
{
response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
var errorResponse = new
{
response.StatusCode,
Message = message,
ExceptionMessage = ex.Message
};
var jsonErrorResponse = JsonSerializer.Serialize(errorResponse);
await response.WriteAsync(jsonErrorResponse);
}
}
}
I would expect this to redirect me to /Account/Login upon a failed request because of a 401. Instead what happens is it displays the response as JSON.
I thought that by adding the following, it would redirect upon a 401:
Code:
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDeniedPath";
});
// ...
app.UseAuthentication();
But apparently not?