public class CustomAuthorizeAttribute : Attribute, IAsyncAuthorizationFilter
{
private readonly string[] _roles;
public CustomAuthorizeAttribute(params string[] roles)
{
_roles = roles;
}
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
// Check if the user is authenticated
if (!user.Identity.IsAuthenticated)
{
RedirectToLoginPage(context);
return;
}
// Check if the user has any of the required roles
var hasClaims = _roles.Any(role => user.IsInRole(role));
if (!hasClaims)
{
RedirectToAccessDeniedPage(context);
return;
}
await Task.CompletedTask;
}
private void RedirectToLoginPage(AuthorizationFilterContext context)
{
var returnUrl = context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;
context.Result = new RedirectToActionResult("Login", "Account", new { ReturnUrl = returnUrl });
}
private void RedirectToAccessDeniedPage(AuthorizationFilterContext context)
{
var returnUrl = context.HttpContext.Request.Headers["Referer"].ToString();
context.Result = new RedirectToActionResult("AccessDenied", "Account", new { returnUrl });
}
}
I have made a custom authorization attribute to handle the unauthorized access, but the problem is the following, when user tries to access the unautorized page(when he is logged in and tries to guess the URL), I want to display a View and in the view, I have the “return the previous page” link, but the problem is that returnUrl is always an empty string in RedirectToAccessDeniedPage method