0

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

1 Answer 1

1

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;
            }
        };
                
    });
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @mj1313, thats exactly what i was looking for. Just one issue, on this "OnRedirectToAccessDenied" event, i want to re-direct to a custom view(page). Currently, i am getting an empty page. Can you kindly explain how can i re-direct to a view with this "OnRedirectToAccessDenied" event. That would be a great favour.
There is a AccessDeniedPath option in the CookieAuthenticationOptions. You can use it redirect to your custom page. I have edited my answer.
Thanks @mj1313, o.Events = new CookieAuthenticationEvents { OnRedirectToAccessDenied = new Func<RedirectContext<CookieAuthenticationOptions>, Task>(context => { context.Response.Redirect("/Home/Error"); return context.Response.CompleteAsync(); }) }; This code worked for me
i have to log this thing in Database. I am using Repository-Service pattern in my application. So, at this point (in Startup.cs) i can not access any repository or service. Do you have any idea how can i log this information in DB. I just want to do a service call whenever there is an unauthorized access request. I believe i have to bind a method to "OnRedirectToAccessDenied" event but unable to figure out yet that how can i bind a service method to this property. If you have any idea, that would be a great help for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.