Giải pháp của tôi là tạo nhà cung cấp vai trò tùy chỉnh. Dưới đây là các bước tôi đã, trong nhu cầu trường hợp bất cứ ai khác giúp đỡ sau:
Tạo người dùng và vai trò của lớp tùy chỉnh của bạn
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Security.Models.Security
{
public class AppRole : IdentityRole
{
}
}
và
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
{
}
}
Thiết lập cơ sở dữ liệu của bạn bối cảnh
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>());
}
}
}
Tạo nhà cung cấp vai trò của bạn và thực hiện các phương pháp sau đây
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);
}
}
}
}
Sửa web.config của bạn để thiết lập kết nối cơ sở dữ liệu và cung cấp tài liệu tham khảo vai trò
<connectionStrings>
<add name="UserContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\UserContext.mdf;Initial Catalog=UserContext;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
và
<system.web>
...
<authentication mode="Windows" />
<roleManager enabled="true" defaultProvider="AppRoleProvider">
<providers>
<clear/>
<add name="AppRoleProvider" type="Security.Models.Security.AppRoleProvider" connectionStringName = "UserContext"/>
</providers>
...
</roleManager>
</system.web>
Trong gói quản lý giao diện điều khiển, cho phép di cư
enable-migrations
Trong Cấu hình vừa được tạo ra.cs thiết lập người dùng/vai trò các cửa hàng và các nhà quản lý và cấu hình các validator quản lý người dùng chấp nhận '\' nhân vật
namespace Security.Migrations
{
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Security.Models.Security;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Security.Models.DAL.UserContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "Security.Models.DAL.UserContext";
}
protected override void Seed(Security.Models.DAL.UserContext db)
{
// Set up the role store and the role manager
var roleStore = new RoleStore<AppRole>(db);
var roleManager = new RoleManager<AppRole>(roleStore);
// Set up the user store and the user mananger
var userStore = new UserStore<AppUser>(db);
var userManager = new UserManager<AppUser>(userStore);
// Ensure that the user manager is able to accept special characters for userNames (e.g. '\' in the 'DOMAIN\username')
userManager.UserValidator = new UserValidator<AppUser>(userManager) { AllowOnlyAlphanumericUserNames = false };
// Seed the database with the administrator role if it does not already exist
if (!db.Roles.Any(r => r.Name == "Administrator"))
{
var role = new AppRole { Name = "Administrator" };
roleManager.Create(role);
}
// Seed the database with the administrator user if it does not already exist
if (!db.Users.Any(u => u.UserName == @"DOMAIN\admin"))
{
var user = new AppUser { UserName = @"DOMAIN\admin" };
userManager.Create(user);
// Assign the administrator role to this user
userManager.AddToRole(user.Id, "Administrator");
}
}
}
}
Trong gói quản lý giao diện điều khiển, đảm bảo cơ sở dữ liệu được tạo ra và hạt
update-database
Tạo thuộc tính ủy quyền tùy chỉnh sẽ chuyển hướng đến trang truy cập bị từ chối do lỗi
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");
}
}
}
}
Bạn đã hoàn tất! Bây giờ, bạn có thể tạo trang truy cập bị từ chối (trong trường hợp này là ~/Home/AccessDenied) và áp dụng thuộc tính cho bất kỳ hành động nào, ví dụ:
using Security.Models.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Security.Controllers
{
public class HomeController : Controller
{
...
[AccessDeniedAuthorizationAttribute(Roles = "Administrator")]
public ActionResult SecureArea()
{
return View();
}
public ActionResult AccessDenied()
{
return View();
}
...
}
}
Hy vọng điều này sẽ giúp ai đó trong tương lai. Chúc may mắn!
Tôi nghĩ rằng yêu cầu cách tốt nhất/sạch sẽ nhất sẽ nhận được nhiều câu trả lời khác nhau. Một cách tiếp cận tốt là từ trên xuống. Đó là - cho phép ở cấp điều khiển và sau đó hạn chế ở cấp phương thức/hành động tùy theo nhu cầu. Bạn cũng có thể thực hiện một bộ điều khiển cơ sở khu vực và sau đó mỗi bộ điều khiển trong khu vực đó thực hiện cơ sở. Bộ điều khiển cơ sở khu vực có thể chuyển hướng đến một trang thích hợp nếu mức độ ủy quyền không được đáp ứng. – Benthon