Results 1 to 2 of 2

Thread: Redirect After 401

  1. #1

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,490

    Redirect After 401

    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?
    "Code is like humor. When you have to explain it, it’s bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

  2. #2

    Thread Starter
    Super Moderator dday9's Avatar
    Join Date
    Mar 2011
    Location
    South Louisiana
    Posts
    11,490

    Re: Redirect After 401

    Update
    Adding AuthorizeAttribute to the top of my controller and moving the order around in Program.cs so that it uses:
    Code:
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseMiddleware<ExceptionMiddleware>();
    Works, however it redirects me to /Identity/Account/Login instead of /Account/Login.
    "Code is like humor. When you have to explain it, it’s bad." - Cory House
    VbLessons | Code Tags | Sword of Fury - Jameram

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width