ityCacheProvider sc = SecurityCacheFactory.GetSecurityCacheProvider("Cache Manager");
//保存身份
IToken token = sc.SaveIdentity(new GenericIdentity("SHY520"));
//使身份过期
sc.ExpireIdentity(token);
}
4、判断用户是否满足一定的规则
首先需要导入下面的命名空间:
using System.Security;
using System.Security.Principal;
using Microsoft.Practices.EnterpriseLibrary.Security;
/**//// <summary>
/// 判断用户是否满足一定的规则
/// http://pw.cnblogs.com
/// </summary>
/// <param name="username">用户名称</param>
/// <param name="role">角色名称</param>
/// <param name="rule">规则名称</param>
/// <returns></returns>
public bool CheckUserRoleByRule(string username, string role, string rule)
{
IPrincipal principal = new GenericPrincipal(new GenericIdentity(username), new string[] { role });
//创建一个默认的Authorization实例
IAuthorizationProvider autoprovider = AuthorizationFactory.GetAuthorizationProvider();
//返回验证是否通过
return autoprovider.Authorize(principal, rule);
} 通过上面的方法可以很简单的实现对用户权限的鉴定,关于Security Application Block的简单应用就说到这里,下面我们来看一下如何实现自定义的authorization provider。
1、首先我们建立自己的Provider类,该类需继承AuthorizationProvider;
2、并且要加上[ConfigurationElementType(typeof(CustomAuthorizationProviderData))]的Attribute;
3、添加构造函数,参数为NameValueCollection类型;
4、覆盖基类中的Authorize方法,在其中添加自己的验证是否授权的逻辑
这样就完成了一个自定义的authorization provider。
完整的类定义如下:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Security;
using System.Collections.Specialized;
using System.Security.Principal;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Security.Configuration;
namespace Enterprise_Library_2
{
[ConfigurationElementType(typeof(CustomAuthorizationProviderData))]
public class CustomProvider : AuthorizationProvider
{
public CustomProvider(NameValueCollection configurationItems)
{
}
public override bool Authorize(IPrincipal principal, string context)
{
//TODO:在此处添加自己需要的验证授权的逻辑既可
return true;
}
}
}
关于Security Application Block的介绍就说到这里了,有疏忽错误的地方,还请指正,希望对初学者有所帮助! |