Waleed Naveed
Waleed Naveed

Reputation: 2381

Capture HandleUnauthorizedRequest in ASP.NET Core MVC

I am working on an ASP.NET MVC Core application. I have policy based authentication in my Project. Added [Authorize] attribute on all my controllers. My requirement is that whenever there is an Unauthrorized Access, i have to do some work. Because of this i have to override HandleUnauthorizedRequest. But i am unable to find any way to get access to this method.

My requirement is that, all other [Authorize] attribute functionality should work as it is but whenever there is Unauthorized access i have to write it to log file and dump this in DB.

I am stuck, any help would be much appreciated

Upvotes: 0

Views: 888

Answers (1)

mj1313
mj1313

Reputation: 8459

If you are using cookie authenction, you can config the cookie AccessDenied event like this

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(config => {
        config.Events = new CookieAuthenticationEvents
        {
            config.AccessDeniedPath = "Page Path"; //Add this line
            OnRedirectToAccessDenied = context =>
            {
                //do some logging
                return Task.CompletedTask;
            }
        };
                
    });

Upvotes: 1

Related Questions