角色认证和授权
Posted
技术标签:
【中文标题】角色认证和授权【英文标题】:Role authentication and authorization 【发布时间】:2013-07-28 18:54:25 【问题描述】:我正在为我的管理页面进行身份验证。我遵循了来自各种网站的示例,但每次我尝试访问产品页面时,它总是将我踢回登录页面。
这是我的代码
login.aspx.cs
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
if (User.Identity.IsAuthenticated && Request.QueryString["ReturnUrl"] != "")
divError.Visible = true;
divError.Innerhtml = accessErrorMessage;
protected void btn_enter_Click(object sender, EventArgs e)
using (var db = new MainDB())
administrator=db.Administrators.Where(q => q.Name == txtUsername.Text && q.Password == txtPassword.Text).FirstOrDefault();
if(administrator!=null)
administrator.DateLastLogin = DateTime.Now;
roles = administrator.Role;
adminID = administrator.AdministratorId;
db.SaveChanges();
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
adminID.ToString(), // Username associated with ticket
DateTime.UtcNow, // Date/time issued
DateTime.UtcNow.AddMinutes(30), // Date/time to expire
true, // "true" for a persistent user cookie
**roles, // User-data, in this case the roles(data example: product,feedback,subscribes**
FormsAuthentication.FormsCookiePath); // Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of authentication cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
// Add the cookie to the list for outgoing response
Response.Cookies.Add(cookie);
// Redirect to requested URL, or homepage if no previous page
// requested
string returnUrl = Request.QueryString["ReturnUrl"];
if (returnUrl == null)
returnUrl = "~/admin/";
// Don't call FormsAuthentication.RedirectFromLoginPage since it
// could
// replace the authentication ticket (cookie) we just added
Response.Redirect(returnUrl);
else
divError.Visible = true;
divError.InnerHtml = loginErrorMessage;
//if (FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text))
//
// FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, false);
//
global.asax
void Application_AuthenticateRequest(object sender, EventArgs e)
if(Request.IsAuthenticated)
FormsIdentity identity = (FormsIdentity)HttpContext.Current.User.Identity;
//Add the roles to the User Principal
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(HttpContext.Current.User.Identity, identity.Ticket.UserData.Split(new char[] ',' ));
web.config
<location path="admin/product">
<system.web>
<authorization>
<!--<allow users="admin"/>-->
<allow roles="product"/>
<deny users="*"/>
</authorization>
</system.web>
<location path="admin/spotlight">
<system.web>
<authorization>
<!--<allow users="admin"/>-->
<allow roles="spotlight"/>
<deny users="*"/>
</authorization>
</system.web>
<location path="admin/career">
<system.web>
<authorization>
<!--<allow users="admin"/>-->
<allow roles="career"/>
<deny users="*"/>
</authorization>
</system.web>
<location path="admin/emailshare">
<system.web>
<authorization>
<!--<allow users="admin"/>-->
<allow roles="emailshare"/>
<deny users="*"/>
</authorization>
</system.web>
我在这里做错了吗?
【问题讨论】:
是尝试访问产品页面的经过身份验证的用户,属于任何角色吗? @FlopScientist 是的......“角色”字段中有多个值......例如:product,feedback,subscribers ,每个都用逗号分隔 好的。所以你确定 Authenticated 用户是角色: Products 吗?至少使用您一直在尝试的用户凭据,它总是将您发送到登录页面? 是的,我很肯定......因为我做了一些测试,它返回唯一发现为真的角色,我认为 web.config 文件有问题... 如果您一直未登录,请检查 web.config 以了解 Cookie 的设置以进行身份验证。我猜你的 cookie 没有设置好。请在您定义身份验证系统设置的位置显示您的配置文件 【参考方案1】:您首先允许一个角色,然后拒绝所有用户。
规则是按顺序执行的,因此请尝试将最具体的规则指定为最后一个。
<deny users="*"/>
<allow roles="emailshare"/>
另一件事,在从数据库验证用户后,您没有设置委托人。您需要在 HttpContext 中设置用户,并且标志为 Authenticated。否则如果(Request.IsAuthenticated)
将永远为假。
GenericIdentity userIdentity =
new GenericIdentity(ticket.Name);
GenericPrincipal userPrincipal =
new GenericPrincipal(userIdentity, roles);
Context.User = userPrincipal;
请注意,角色参数是一个逗号分隔的字符串。
另外,使用build-in provider model 不是更容易吗?这会阻止您自己编写所有身份验证代码。然后,您可以在需要时使用您自己的数据访问逻辑创建您的custom Membership provider。
【讨论】:
感谢您的快速回复...我做了您提到的更改,但它仍然让我回到登录页面。我很抱歉,因为我是新手,我的老板给我举了一个例子,让我按照这个方法。这就是为什么我诉诸这个.. 我更新了我的答案。我认为您可能还需要在验证用户身份后设置 IIdentity。以上是关于角色认证和授权的主要内容,如果未能解决你的问题,请参考以下文章
SpringSecurity - 用户动态授权 及 动态角色权限