مدیریت سفارشی سطوح دسترسی کاربران در MVC
نویسنده: مهران موسوی
تاریخ: ۱۳۹۱/۱۰/۰۸ ۲۳:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace Myproject.Security
{
public class CustomRoleProvider : RoleProvider
{
}
}
public override string[] GetRolesForUser(string username)
{
using (DatabaseEntities db = new DatabaseEntities())
{
User user = db.Users.FirstOrDefault(u => u.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase));
var roles = from ur in user.UserRoles
from r in db.Roles
where ur.RoleId == r.Id
select r.Name;
if (roles != null)
return roles.ToArray();
else
return new string[] {}; ;
}
}
public override bool IsUserInRole(string username, string roleName)
{
using (DatabaseEntities db = new DatabaseEntities())
{
User user = db.Users.FirstOrDefault(u => u.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase));
var roles = from ur in user.UserRoles
from r in db.Roles
where ur.RoleId == r.Id
select r.Name;
if (user != null)
return roles.Any(r => r.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
else
return false;
}
}
public override bool IsUserInRole(string username, string roleName)
{
return this.GetRolesForUser(username).Contains(roleName);
}
<system.web>
...
<rolemanager cacherolesincookie="true" defaultprovider="CustomRoleProvider" enabled="true">
<providers>
<clear />
<add name="CustomRoleProvider" type="Myproject.Security.CustomRoleProvider" />
</providers>
</rolemanager>
...
</system.web>
using System;
using System.Web.Mvc;
namespace MyProject.Areas.Admin.Controllers
{
[Authorize(Roles = "Administrators")]
public class HomeController : Controller
{
//
// GET: /Admin/Home/
public ActionResult Index()
{
return View();
}
}
}
using System;
using System.Web.Mvc;
namespace MyProject.Areas.Admin.Controllers
{
public class HomeController : Controller
{
//
// GET: /Admin/Home/
public ActionResult Index()
{
return View();
}
[Authorize(Roles = "Administrators")]
public ActionResult ViewProfile()
{
return View();
}
}
}
if (Membership.ValidateUser(UserName, Password))
{
FormsAuthentication.RedirectFromLoginPage(UserName, true);
return true;
}
<authentication mode="Forms" >
<forms loginUrl="~/Account/Login"
protection="All"
timeout="30"
name="myAppCookie"
path="/"
requireSSL="false"
slidingExpiration="true"
cookieless="UseCookies"
enableCrossAppRedirects="false" />
</authentication>
<membership >
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider"
connectionStringName="ApplicationServices" enablePasswordRetrieval="false"
enablePasswordReset="true" requiresQuestionAndAnswer="false"
requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="myApp " />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider"
connectionStringName="ApplicationServices" applicationName="myApp " />
</providers>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider"
connectionStringName="ApplicationServices" applicationName="myApp "/>
<add name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider" applicationName="myApp " />
</providers>
</roleManager>
StringComparison.CurrentCultureIgnoreCase
<roleManager cacheRolesInCookie="true" enabled="true" defaultProvider="CustomRoleProvider">
<providers>
<clear />
<add name="CustomRoleProvider"
type="MvcApp.UserInterface.Models.CustomRoleProvider"
connectionStringName="MvcAppDb"
applicationName="/" />
</providers>
</roleManager><roleManager
enabled="true"
cacheRolesInCookie="true"
defaultProvider="..."
cookieName=".ASPXROLES"
cookiePath="/"
cookieTimeout="30"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
createPersistentCookie="false"
cookieProtection="All">
<providers>
<!-- .... -->
</providers>
</roleManager>Assume that you set the value of the cachedRolesInCookie property to true in your web application. Your application serializes the RolePrincipal object into the cookie, and then sends it in response. In this situation, the role cookie value is empty in the application's following request.
سلام؛ من هم مشکل ایشون دارم و رولها کش نمیشه و هر بار متد GetRolesForUser اجرا میشود. اون هم نه یکبار بلکه به تعداد زیاد و بار زیادی به دیتابیس وارد میکنه. لینک شما هم پیغام زیر و میدهد:
An update is available for the .NET Framework 4.5 in Windows 7 SP1, Windows Server 2008 R2 SP1, Windows Server 2008 SP2, and Windows Vista SP2: January 2013
اما ویندوز من 8 هست و پیغام سایت برای ویندوزهای 2008و7وvista هستش. با گشتن هم دیدم بعضیها خودشون متد را دستی کش کردن
public override string[] GetRolesForUser(string username)
{
var cacheKey = string.Format("{0}:{1}", username, ApplicationName);
var cache = HttpContext.Current.Cache;
var roles = cache[cacheKey] as string[];
if (null == roles)
{
using (var db = new Uas3Context())
{
var u = new EfStudentService(db);
roles=u.GetUserRoles(username);
cache.Insert(cacheKey, roles, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
}
}
return roles;
} اما این متد و من کش کردم باقی متدها چی؟ کل متدها را همین طوری کش کنم؟ این کد هم به نظرم ناقصه . چون با تغییر دیتابیس به روز نمیشه و صرفا درصورت وجود کش اطلاعات میخونه. اصلا چرا در دات نت 4.5 این مشکل هست و چرا بر روی ویندوز 8 این پیغام داده میشود؟
Error2'student_mvc.Security.CustomRoleProvider' does not implement inherited abstract member 'System.Web.Security.RoleProvider.GetAllRoles()
Error3'student_mvc.Security.CustomRoleProvider' does not implement inherited abstract member 'System.Web.Security.RoleProvider.GetUsersInRole(string)
ممنون از پاسختون اما Authenticate در مند SetAuthCookie تنها نام یوزر و ذخیره میکند، برای ذخیره سایر اطلاعات چه کار باید کرد؟
اگر باید از متدهای HttpContext استفاده بشود جهت رمزنگاری کوکیها چه الگوریتمی به اندازه Authentication مطمئن است؟