我只是不知道这两个可能非常有用的功能应该如何工作。
[Authorize(Roles="Admin")] //Method A
和
User.isInRole("Admin") //Method B
他们现在显然不适合我。我做了几个小时的研究:
我读到你需要实现System.Web.Security.RoleProvider,然后在web配置中设置它:
<roleManager defaultProvider="OdbcRoleProvider"
enabled="true"
cacheRolesInCookie="true"
cookieName=".ASPROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All" >
<providers>
<clear />
<add
name="OdbcRoleProvider"
type="Samples.AspNet.Roles.OdbcRoleProvider"
connectionStringName="OdbcServices"
applicationName="SampleApplication"
writeExceptionsToEventLog="false" />
</providers>
</roleManager>
这导致我通过构造实现了RoleProvider,但是角色检查函数肯定没有调用那里的任何方法。
然后我读到Asp.NET Identity取消了RoleProvider ,现在你需要这样做:
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthenticationModule" />
<remove name="RoleManager" />
</modules>
我做到了。
我有一个自定义UserManager连接到我的postgres后端。问题是每当我使用它时,我需要实例化一个。在我看来,如果函数A和B将起作用,那么我实现的UserManager需要在某种配置文件中被引用,所以Asp.NET隐含地知道它。这将是就像过去的RoleManager一样。
ASP.NET身份如何改变函数A和B如何使用行为检查旧RoleProvider中的角色?
答案 0 :(得分:1)
我明白了。
当你像这样调用登录代码时:
var user = await UserManager.FindAsync(model.Email, model.Password);
if (user != null && user.PasswordRequiresReset == false)
{
await SignInAsync(user, model.RememberMe); //triggers IUserRoleStore.GetRolesAsync
return RedirectToLocal(returnUrl);
}
SignInAsync从IUserRoleStore触发GetRolesAsync:
public Task<IList<string>> GetRolesAsync(TUser user) //where TUser is an ApplicationUser
{
Func<object, IList<string>> getRoles = (object user2) =>
{
TUser user3 = (TUser)user2;
return user3.Roles.Select(x => x.Role.Name).ToList();
};
return Task.Factory.StartNew(getRoles, user);
}
在上面,我选择从我已经从db加载的角色生成角色,并在FindAsync中创建它时存储在ApplicationUser对象中。
GetRolesAsync中的角色必须加载到cookie中,可以通过函数A和B快速轻松地访问它们。