我正在编写ASP.NET MVC 2应用程序,并且不想使用ASP.NET成员资格。我确实想在控制器上使用Authorize属性。到目前为止我所做的是......
的Web.config
<roleManager enabled="true" />
<authentication mode="Forms">
<forms loginUrl="~/Authentication/Login" timeout="2880"/>
</authentication>
<authorization>
<allow users="*" /> /* This is for testing */
</authorization>
在我的Global.asax
中 protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Context.User = tcmPrincipal;
}
我正在使用自定义IIdentity,以便将来可以添加一些自定义属性。要在我的Controller操作中测试这个,我做了这个......
var testPrincipal = User;
我可以看到包含所有用户信息的自定义标识,但主体对象上没有任何角色。对我错过的任何帮助都会很棒。感谢。
答案 0 :(得分:1)
我相信你需要一个角色提供者。与成员资格提供者如何处理用户成员资格,创建,删除,验证,编辑以及使用角色非常相似,您需要使用RoleProvider(ASP.NET Implementing a Role Provider)。
还需要在web.config中启用角色,例如:
<roleManager enabled="enabled" defaultProvider="AspNetSqlRoleProvider">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="ApplicationServices"
applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider"
applicationName="/" />
</providers>
</roleManager>
这可能有用: SO asp-net-mvc-roles-without-database-and-without-role-provider
可能是: ASP.NET 2.0, Custom Role assignment without a 'Role Provider'
答案 1 :(得分:1)
更新:
最后,我通过改变
来实现这一目标protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Context.User = tcmPrincipal;
}
到
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) return;
var decryptedCookie = FormsAuthentication.Decrypt(cookie.Value);
var roles = decryptedCookie.UserData.Split('|');
var tcmIdentity = new TcmIdentity(decryptedCookie.Name);
var tcmPrincipal = new GenericPrincipal(tcmIdentity, roles);
Thread.CurrentPrincipal = Context.User = tcmPrincipal;
}