public class CustomAuthorizationPolicy : IAuthorizationPolicy
{
string id;
public CustomAuthorizationPolicy()
{
id = Guid.NewGuid().ToString();
}
public bool Evaluate(EvaluationContext evaluationContext, ref object state)
{
bool bRet = false;
CustomAuthState customstate = null;
// If the state is null, then this has not been called before so
// set up a custom state.
if (state == null)
{
customstate = new CustomAuthState();
state = customstate;
}
else
customstate = (CustomAuthState)state;
// If claims have not been added yet...
if (!customstate.ClaimsAdded)
{
// Create an empty list of claims.
IList<Claim> claims = new List<Claim>();
// Iterate through each of the claim sets in the evaluation context.
foreach (ClaimSet cs in evaluationContext.ClaimSets)
// Look for Name claims in the current claimset.
foreach (Claim c in cs.FindClaims(ClaimTypes.Name, Rights.PossessProperty))
{
// Get the list of operations the given username is allowed to call.
foreach (Right right in DataProvider.GetUserRightList(c.Resource.ToString()))
{
Console.WriteLine("正在给用户(" + c.Resource + ")赋权限:" + right.OperationName);
claims.Add(new Claim(DataProvider.ClaimType,right.OperationName, Rights.PossessProperty));
//Console.WriteLine("Claim added {0}", s);
}
}
// Add claims to the evaluation context.
evaluationContext.AddClaimSet(this, new DefaultClaimSet(this.Issuer, claims));
// Record that claims were added.
customstate.ClaimsAdded = true;
// Return true, indicating that this method does not need to be called again.
bRet = true;
}
else
{
// Should never get here, but just in case, return true.
bRet = true;
}
return bRet;
}
public ClaimSet Issuer
{
get { return ClaimSet.System; }
}
public string Id
{
get { return id; }
}
// Internal class for keeping track of state.
class CustomAuthState
{
bool bClaimsAdded;
public CustomAuthState()
{
bClaimsAdded = false;
}
public bool ClaimsAdded
{
get { return bClaimsAdded; }
set { bClaimsAdded = value; }
}
}
}