“认证”与“授权”是几乎所有系统中都会涉及的概念,通俗点讲:
1、认证(authentication) 就是 "判断用户有没有登录?",好比windows系统,没登录就无法使用(不管你是用Administrator或Guest用户,总之要先正确登录后,才能进入系统)。
2、授权(authorization) 就是"用户登录后的身份/角色识别",好比"管理员用户"登录windows后,能安装软件、修改windows设置等所有操作,而Guest用户登录后,只有做有限的操作(比如安装软件就被禁止了)。
.net中与"认证"对应的是IIdentity接口,而与"授权"对应的则是IPrincipal接口,这二个接口的定义均在命名空间System.Security.Principal中:
usingSystem;usingSystem.Runtime.InteropServices;namespaceSystem.Security.Principal
{
[ComVisible(true)]publicinterfaceIIdentity
{stringAuthenticationType {get; }boolIsAuthenticated {get; }stringName {get; }
}
}
usingSystem;usingSystem.Runtime.InteropServices;namespaceSystem.Security.Principal
{
[ComVisible(true)]publicinterfaceIPrincipal
{
IIdentity Identity {get; }boolIsInRole(stringrole);
}
}
应该注意到:IPrincipal接口中包含着一个只读的IIdentity,这也跟最开始提到的概念一致:识别身份的前提是先登录,只有登录成功后能进一步确认身份。
用Membership/Role做过asp.net开发的朋友们,看到这二个接口的定义,应该会觉得很眼熟,想想我们在Asp.Net页面中是如何判断用户是否登录以及角色的?
protectedvoidPage_Load(objectsender, EventArgs e)
{
HttpContext ctx=HttpContext.Current;if(ctx.User.Identit