基本上,我創建了我的第一個WCF Web服務,並且正在尋求實現自定義身份驗證和授權。身份驗證似乎運行良好,但我希望能夠使用自定義授權來存儲角色和權限。WCF自定義授權
我的驗證是通過覆蓋UserNamePasswordValidator
並使用Validate
方法完成的。
Validate(string UserName, string password)
現在,我已經嘗試使用IAuthorizationPolicy
接口
public class AuthorizationPolicy : IAuthorizationPolicy
{
private string _id;
public string Id
{
get { return this._id; }
}
public ClaimSet Issuer
{
get { return ClaimSet.System; }
}
public AuthorizationPolicy()
{
_id = Guid.NewGuid().ToString();
}
public bool Evaluate(EvaluationContext context, ref object state)
{
IIdentity client = GetClientIdentity(context);
context.Properties["Principal"] = new CustomPrincipal(client);
return true;
}
private IIdentity GetClientIdentity(EvaluationContext evaluationContext)
{
object obj;
if (!evaluationContext.Properties.TryGetValue("Identities", out obj))
throw new Exception("No Identity found");
IList<IIdentity> identities = obj as IList<IIdentity>;
if (identities == null || identities.Count <= 0)
throw new Exception("No Identity found");
return identities[0];
}
}
實施的授權,我已經使用IPrincipal
接口也實現了CustomPrincipal
。
public class CustomPrincipal : IPrincipal
{
IIdentity _identity;
string[] _roles;
public CustomPrincipal(IIdentity identity)
{
_identity = identity;
}
public static CustomPrincipal Current
{
get
{
return Thread.CurrentPrincipal as CustomPrincipal;
}
}
public IIdentity Identity
{
get { return _identity; }
}
public string[] Roles
{
get
{
if (_roles == null)
{
EnsureRoles();
}
return _roles;
}
}
public bool IsInRole(string role)
{
EnsureRoles();
return _roles.Contains(role);
}
protected virtual void EnsureRoles()
{
UserManager userManager = new UserManager();
int userPermissions = userManager.UserPermissions(_identity.Name);
if (userPermissions == 1)
_roles = new string[1] { "ADMIN" };
else
_roles = new string[1] { "USER" };
}
}
我App.Config中按要求進行了更新,並在AuthorizationPolicy
的Evaluate
方法有望被調用。
但是,這是我卡住的地方。我如何去實現這裏的角色和權限?