这次我们是主要用到的Security,所以我们添加一个Security的Blocks
添加成功之后,我们要Setting一个

在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 = "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);
}