Custom RoleProvider, Authorization, EF DB First and ASP.NET
how to make Custom RoleProvider, Authorization and ASP.NET MVC
1 Answer
Know the answer? Post it. Somebody with the same question will find it here.
Know the answer? Post it. Somebody with the same question will find it here.
Ankusha Rana27 pointsPosted Oct 16, 2018, 8:54 PM EDT
using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Security.Models.Security { public class AppUser : IdentityUser { } } Set up your database context using Microsoft.AspNet.Identity.EntityFramework; using Security.Models.Security; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace Security.Models.DAL { public class UserContext : IdentityDbContext<AppUser> { public UserContext() : base("UserContext") { Database.SetInitializer<UserContext>(new CreateDatabaseIfNotExists<UserContext>()); } } } Create your role provider and implement the following methods using Security.Models.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; namespace Security.Models.Security { public class AppRoleProvider : RoleProvider { public override string[] GetAllRoles() { using (var userContext = new UserContext()) { return userContext.Roles.Select(r => r.Name).ToArray(); } } public override string[] GetRolesForUser(string username) { using (var userContext = new UserContext()) { var user = userContext.Users.SingleOrDefault(u => u.UserName == username); var userRoles = userContext.Roles.Select(r => r.Name); if (user == null) return new string[] { }; return user.Roles == null ? new string[] { } : userRoles.ToArray(); } } public override bool IsUserInRole(string username, string roleName) { using (var userContext = new UserContext()) { var user = userContext.Users.SingleOrDefault(u => u.UserName == username); var userRoles = userContext.Roles.Select(r => r.Name); if (user == null) return false; return user.Roles != null && userRoles.Any(r => r == roleName); } } } }update-database Create a custom authorization attribute that will redirect to an access denied page on failure using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Security.Models.Security { public class AccessDeniedAuthorizationAttribute : AuthorizeAttribute { public override void OnAuthorization(AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if(filterContext.Result is HttpUnauthorizedResult) { filterContext.Result = new RedirectResult("~/Home/AccessDenied"); } } } }