我使用C#在.Net 4.5中有一个WCF Web服务。我正在尝试使用PrincipalPermission进行授权,但始终未通过授权检查。因此,对于调试,我切换到调用Roles.IsUserInRole(“SystemAdministrator”)。 Roles.IsUserInRole始终返回false。主体在我的AuthorizationManager类中设置:
protected override bool CheckAccessCore(OperationContext operationContext)
{
...
if (! MembershipProvider.ValidateUser(credentials.UserName, credentials.Password))
{
return false;
}
var user = MembershipProvider.GetUser(credentials.UserName, true);
var claims = new List<Claim>().InjectInstanceClaims()
.InjectUserClaims(user)
.InjectAuthenticationClaims("CustomAuth");
var roles = RolesProvider.GetRolesForUser(user.Name);
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "CustomAuth"));
Thread.CurrentPrincipal = authenticatedUser;
return user.IsApproved && ! user.IsLockedOut;
}
然后在我的AuthorizationPolicy中,我将evaluateContext.Properties [“Principal”]设置为Thread.CurrentPrincipal。
public class AuthorizationPolicy : IAuthorizationPolicy
{
public AuthorizationPolicy ()
{
Id = Guid.NewGuid().ToString("N");
}
public string Id { get; private set;
}
public bool Evaluate(EvaluationContext evaluationContext, ref object state)
{
evaluationContext.Properties["Principal"] = Thread.CurrentPrincipal;
return true;
}
public ClaimSet Issuer
{
get { return ClaimSet.System; }
}
}
当我到达我的WCF方法时,我可以在调试器中验证我有上面创建的用户,并且它在Identity.Claims中声明了ClaimTypes.Role /“SystemAdministrator”,但我的调用是IsUserInRole总是错误的。
public IEnumerable<Credentials> GetAllCredentials()
{
if (!Roles.IsUserInRole("SystemAdministrator"))
{
throw new HttpException(401, "Not authorized");
}
return CredentialData.GetAll();
}
如何使用自定义AuthorizationManager和自定义AuthorizationPolicy使Roles.IsUserInRole返回true?