注:这篇文章主要给新手看的,老手们可能会觉得没啥营养,就请绕过吧。
“认证”与“授权”是几乎所有系统中都会涉及的概念,通俗点讲:
认证(authentication) 就是 "判断用户有没有登录?",好比windows系统,没登录就无法使用(不管你是用Administrator或Guest用户,总之要先正确登录后,才能进入系统).
授权(authorization) 就是"用户登录后的身份/角色识别",好比"管理员用户"登录windows后,能安装软件、修改windows设置等所有操作,而Guest用户登录后,只有做有限的操作(比如安装软件就被禁止了).
.net中与"认证"对应的是IIdentity接口,而与"授权"对应的则是IPrincipal接口,这二个接口的定义均在命名空间System.Security.Principal中:
using System;
using System.Runtime.InteropServices;
namespace System.Security.Principal
{
[ComVisible(true)]
public interface IIdentity
{
string AuthenticationType { get; }
bool IsAuthenticated { get; }
string Name { get; }
}
}
using System;
using System.Runtime.InteropServices;
namespace System.Security.Principal
{
[ComVisible(true)]
public interface IPrincipal
{
IIdentity Identity { get; }
bool IsInRole(string role);
}
}
应该注意到:IPrincipal接口中包含着一个只读的IIdentity,这也跟最开始提到的概念一致:识别身份的前提是先登录,只有登录成功后能进一步确认身份。
用Membership/Role做过asp.net开发的朋友们,看到这二个接口的定义,应该会觉得很眼熟,想想我们在Asp.Net页面中是如何判断用户是否登录以及角色的?
protected void Page_Load(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
if (ctx.User.Identity.IsAuthenticated && ctx.User.IsInRole("管理员"))
{
//管理员该做的事,就写在这里
}
else
{
//Hi,您不是管理员,别胡来!
}
}
这段代码再熟悉不过了,没错!membership/role的原理就是基于这二个接口的,如果再对HttpContext.Current.User刨根问底,能发现下面的定义:
即:HttpContext.Current.User本身就是一个IPrincipal接口的实例。有了上面的预备知识,可以直奔主题了,先来一个Console控制台程序测试一下用法:
using System;
using System.Security.Principal;
using System.Threading;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
GenericIdentity _identity = new GenericIdentity("菩提树下的杨过");
GenericPrincipal _principal = new GenericPrincipal(_identity, new string[] {"管理员","网站会员" });
Thread.CurrentPrincipal = _principal;//并非必需,但在winform程序中有很用(后面会提到)
string loginName = _principal.Identity.Name;
bool isLogin = _principal.Identity.IsAuthenticated;
bool isAdmin = _principal.IsInRole("管理员");
bool isWebUser = _principal.IsInRole("网站会员");
Console.WriteLine("当前用户: {0}", loginName);
Console.WriteLine("是否已经登录? {0}", isLogin);
Console.WriteLine("是否管理员? {0}", isAdmin);
Console.WriteLine("是否网站会员? {0}", isWebUser);
Console.Read();
}
<