Hello everyone, I am going to share the code
sample to roles base authorization and authentication in ASP.Net MVC 5 using FilterAttribute and AspNetUserRoles.
The Steps detail as given below.
ASP.NET
Forms Authentication
namespace Authorize.Controllers
{
[Authorize]
public class AccountController : Controller
{
[HttpPost]
[AllowAnonymous]
public async Task<ActionResult>
Login(LoginViewModel model, string returnUrl)
{
if
(ModelState.IsValid)
{
int timeout = 525600; // Timeout in
minutes, 525600 = 365 days.
string UserData =
GetUserData(model);
//// Create and tuck
away the cookie
FormsAuthenticationTicket
authTicket = new
FormsAuthenticationTicket(1, model.UserName, DateTime.Now, DateTime.Now.AddDays(30),
rememberMe, UserData, FormsAuthentication.FormsCookiePath);
//To encrypt
FormsAuthenticationTicket ticket set the protection attribute of the forms
element to All or Encryption.
string encTicket =
FormsAuthentication.Encrypt(authTicket);
HttpCookie AuthCookie = new
HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
System.Web.HttpContext.Current.Response.Cookies.Add(AuthCookie);
}
}
}
}
}
Authorize controller by Roles
namespace Authorize.Controllers
{
[CustomAuthorize(Roles = "Client")]
public class UsageController : BaseController
{
/// <summary>
/// This method is used
to render dashboard view.
/// </summary>
public ActionResult Index()
{
return View();
}
}
}
CustomAuthorizeAttribute class using
AuthorizeAttribute
namespace Authorize.Security
{
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
AspDotNetUserRepository _aspNetRepo = new AspDotNetUserRepository();
if
(filterContext.HttpContext.Request.IsAuthenticated)
{
var authorizedRoles = ConfigurationManager.AppSettings.Get("admin");
Roles = String.IsNullOrEmpty(Roles)
? authorizedRoles : Roles;
AspNetUser user =
_aspNetRepo.GetAspNetUser(Convert.ToString(HttpContext.Current.User.Identity.Name));
if (user != null)
{
string userRole =
_aspNetRepo.GetUserRole(Convert.ToString(user.Id));
if (!String.IsNullOrEmpty(userRole))
{
if
(!userRole.Equals(Roles))
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "Controller", "Error" }, { "Action", "AccessDenied" } });
FormsAuthentication.SignOut();
base.OnAuthorization(filterContext);//returns to
AccessDenied page URL.
}
}
}
}
}
}
}
App Settings for Roles
<appSettings>
<!-- For Authrization role -->
<add key="admin" value="adminUser"/>
</appSettings>