您的位置:首页 > 其它

关于Enterprise Library Security和System.Security的结合使用记录

2011-07-28 13:34 453 查看
本来刚想从博客园搜集点Enterprise Library Security的资料记录,发现博客园的网站又当机了(最近博客园经常当机呀)。看来还是自己手写下吧。以前使用过Enterprise LibraryLogging Validation Cache 感觉还不错、当然这方面的选择还有的,比如日志记录的NlogLog4之类的,验证方面也有Fluent Validation 这种成熟的项目了。但推荐还是用微软的,毕竟用官方出的工具更容易集成一点,而且风险比较小。使用得当对开发那是相当的便利,闲话不多说了这次我们用到的是微软的 Enterprise Library 5.0 先安装EL,安装之后启动 Enterprise Library Configuration 工具,工具很简单就不介绍了这次我们是主要用到的Security,所以我们添加一个SecurityBlocks



添加成功之后,我们要Setting一个

[b]Authorization [/b]Providers,(注意这个地方Providers的Name为)


Authorition Rule Provider面板上右键,点击Add Authorization Rule,我们将新建的Rule名称设置为Authorization Rule



添加一个Rule Expression,这个地方大家可以自行配置



然后Add Security Cache,通过Security Setting把它们关联起来



保存为一个config文件

在项目中使用的时候先添加Enterprise Library的相关引用,然后把刚才保存的config文件配置到当前项目的默认config文件中,添加如下代码:

//创建一个新的用户
GenericIdentity gID = new GenericIdentity("Vis");

IAuthorizationProvider ruleProvider = AuthorizationFactory.GetAuthorizationProvider("Authorization Rule Provider");

//设置该用户隶属于Manage中
IPrincipal principal = new GenericPrincipal(gID, new string[] { "Manage" });

//验证
bool authorized = ruleProvider.Authorize(principal, "Authorization Rule");

//保存用户至缓存中
ISecurityCacheProvider secCache = SecurityCacheFactory.GetSecurityCacheProvider("Security Cache");

//保存,并获取一个凭证
IToken token = secCache.SaveIdentity(gID);

//通过凭证获取缓存中的用户
IIdentity savedIdentity = secCache.GetIdentity(token);

//获取用户信息 string userName = savedIdentity.Name;

在你需要验证的方法上添加声明,如下:

[PrincipalPermission(SecurityAction.Demand, Role = "Manage")]
[PrincipalPermission(SecurityAction.Demand, Role = "Dev")]
public UserDTO AddNewUser(UserDTO UserDTO)
{
if (UserDTO == null)
{
LogFactory.CreateLog().LogWarning(Messages.warning_CannotAddUserWithNullInformation);

return null;
}
User tempObject = new User();
if (UserDTO.UserId == null || UserDTO.UserId == Guid.Empty)
tempObject.UserId = IdentityGenerator.NewSequentialGuid();
else
tempObject.UserId = UserDTO.UserId;
tempObject.UserName = UserDTO.UserName;
tempObject.PassWord = UserDTO.PassWord;
tempObject.FirstName = UserDTO.FirstName;
tempObject.LastName = UserDTO.LastName;
tempObject.Gender = UserDTO.Gender;
tempObject.Birth = UserDTO.Birth;
tempObject.Phone = UserDTO.Phone;
tempObject.MobilePhone = UserDTO.MobilePhone;
tempObject.JobStatus = UserDTO.JobStatus;
tempObject.Email = UserDTO.Email;
tempObject.Hometown = UserDTO.Hometown;
tempObject.Address = UserDTO.Address;
tempObject.OrganizationId = UserDTO.OrganizationId;
tempObject.IsDeleted = false;
SaveUser(tempObject);
return _typesAdapter.Adapt<User, UserDTO>(tempObject);
}

这个时候我们的认证将不会通过,因为在第一段代码中只添加了为"Manage"的权限,而第二部分代码中的声明是需要"Manage"和"Dev"两种权限认证。


当然,我们再在数组中再添加一个Dev的角色就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: