Donate

Custom AuthorizeAttribute Class In ASP.NET MVC

Hello All!
In ASP.NET MVC projects, you would normally handle Unauthorized users if they access to a page in which they don't have access to. To do this I have a custom class that inherits the AuthorizeAttribute class. This class was take from accepted answers in stackoverflow with some modifications according to my needs for the project.
Here's the complete AuthorizeUser class.
using System.Configuration;
using System.Web.Mvc;

namespace AuthenticationDemo
{
    public class AuthorizeUsersAttribute : AuthorizeAttribute
    {
        private string redirectUrl = "";

        public string NotifyUrl
        {
            get { return redirectUrl; }
            set { redirectUrl = value; }
        }

        public AuthorizeUsersAttribute()
            : base()
        {
        }

        public AuthorizeUsersAttribute(string redirectUrl)
            : base()
        {
            this.redirectUrl = redirectUrl;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //passed from attribute NotifyUrl Property
            string authUrl = this.redirectUrl;

            //if null, get it from web.config
            if (string.IsNullOrEmpty(authUrl))
                authUrl = ConfigurationManager.AppSettings["RolesAuthRedirectUrl"];

            if (!string.IsNullOrEmpty(authUrl))
                filterContext.HttpContext.Response.Redirect(authUrl);

            base.HandleUnauthorizedRequest(filterContext);
        }

        public override void OnAuthorization(AuthorizationContext context)
        {
            if (context.HttpContext.Request.IsAuthenticated)
            {
                if (!context.HttpContext.User.IsInRole(this.Roles))
                    HandleUnauthorizedRequest(context);
            }
            else
            {
                HandleUnauthorizedRequest(context); 
            }
        }
    }
}
In web.config which is located at the root of the project, define the key/value for RolesAuthRedirectUrl element.
<appSettings>
 <add key="RolesAuthRedirectUrl" value="~/Error/Http404"/>
</appSettings>
The base controller class is defined as follows. This has the methods for UnauthorizedError() and Http404(). Make sure that your controllers inherit this class.
using System.Web.Mvc;
namespace AuthenticationDemo
{
    [AllowAnonymous]
    public class ErrorController : Controller
    {
        public ActionResult UnauthorizedError()
        {
            //Add some codes here... 
            return View(model);
        }
  
 public ActionResult Http404()
        {
            //Add some codes here... 
            return View(model);
        }
    }
}
 
In the controller, decorate your ActionResult Methods with the custom attribute class.
[HttpGet]
[AuthorizeUsers(Roles = "Admin", NotifyUrl = "/Error/UnauthorizedError")]
public ActionResult GetEmployeeFinancialRecords()
{
  //Add some codes here...  
  return View();
}

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Pass GUID As Parameter To Action Using ASP.NET MVC ContribGrid