web
You’re offline. This is a read only version of the page.
close
Skip to main content
Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Blogs / Tajwal's Blog / Custom Authentication in AS...

Custom Authentication in ASP.Net MVC 5

Community Member Profile Picture Community Member

By default ASP.Net claim based authentication support authorization based usernames and Roles names, but my requirement are tittle different I have three types of user SuperAdmin, Admin and normal user and I was to manager access to controllers based user-type.

i was able to accomplish this  thought custom authorization which explained in below:

  1. Create custom class CustomAuthAttribute and inherit it from AuthorizeAttribute  as in below

public class CustomAuthAttributeHelper:AuthorizeAttribute
{
private SIContext _db;
private readonly string[] allowedUserTypes;

public CustomAuthAttributeHelper(params string[] _usertypes)
{
_db = new SIContext();
allowedUserTypes = _usertypes;
}

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
string UserType = ExtensionsHelper.GetUserInfo(“usertype”);
int UserId = Convert.ToInt32(ExtensionsHelper.GetUserInfo(“userid”));
bool authorize = false;
if (!string.IsNullOrEmpty(UserType) && UserId>0)
{
User ret = _db.Users.Find(UserId);
if (ret != null && ret.IsActive==true)
{
foreach (var utype in allowedUserTypes)
{
if ((utype == UserType) && ((
utype == Usertype.SupperAdmin.ToString())
|| utype == Usertype.Admin.ToString()
|| utype == Usertype.User.ToString()))
{
authorize = true;
}
}
}
}
return authorize;
}

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}

2. applied on controller 

all three type of user can access bin controller

[CustomAuthAttributeHelper(“SuperAdmin”,”Admin”, “User”)]
public class BinsController : Controller
{

}

only SuperAdmin Can access DocSourceTypes controller

[CustomAuthAttributeHelper(“SuperAdmin”)]
public class DocSourceTypesController : Controller
{

}

Admin and SuperAdmin can access Doc controller.

 

only SuperAdmin Can access DocSourceTypes controller

[CustomAuthAttributeHelper(“SuperAdmin”,”Admin”)]
public class DocController : Controller
{

}

 

hope this will help.

 

 


This was originally posted here.

Comments

*This post is locked for comments