Authorization is a very important and every web project has there own needs and requirements. Full customisation is paramount.
Here I will show you a simple way to customise your authorization.
------------------------------CLASS BODY-----------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace auth
{
public class AuthoriseUserAttribute : AuthorizeAttribute
{
private int _kind;
private int _accessId;
public int Kind
{
get { return _kind; }
set { _kind = value; }
}
public int AccessId
{
get { return _accessId; }
set { _accessId = value; }
}
public enum AuthorizeType
{
System_Rights = 0,
Master_Rights = 1,
Document_Rights = 2,
Category_Rights = 3
}
public AuthoriseUserAttribute(int Pkind, int PaccessId)
{
Kind = Pkind;
AccessId = PaccessId;
}
public AuthoriseUserAttribute(int Pkind, int PaccessId, int userId)
{
Kind = Pkind;
AccessId = PaccessId;
}
public AuthoriseUserAttribute(int Pkind)
{
Kind = Pkind;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
/////////////This method is used for all checks////////////////////////
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (!httpContext.User.Identity.IsAuthenticated) ///First check User is login
return false;
if (Kind == Convert.ToInt32(AuthorizeType.Master_Rights) && httpContext.User.Identity.IsAuthenticated)
{
////Check Users Rights if found ok
return true;
}
else
{
///Redirect to no access page
///
return false;
}
}
}
}
----------------------------END CLASS------------------------------------------
----------------------------CUSTOM ATTRIBUTE CALL------------------------
[AuthoriseUser(0, 1)]
public ActionResult Index()
{
ViewModel.Message = "Welcome to ASP.NET MVC!";
return View();
}
[AuthoriseUser(1, 1)]
public ActionResult About()
{
return View();
}
}
Hi,
ReplyDeleteVery useful...
Regards,
Balaji
http://dotnetinfomedia.blogspot.com/
That was really interesting to know Custom Authorization With Asp.net MVC and their new strategies.
ReplyDeleteCheers !
web design india
Great thoughts you got there, believe I may possibly try just some of it throughout my daily life.
ReplyDeleteWeb devlopment