Reputation: 167
I am using clientCredentailType as Username under security mode under Message. I have created a Custom username and password validator class to verify the username and password.
I want to use these credentials (username,password) for authorization to different operations within the service. I want to know whats the best way to store the username and password for reuse. Should I use my custom validator class to store these in static variables so that they are accessible everywhere ?
Why can't I use System.Threading.Thread.CurrentPrincipal.Identity.Name, I tried to get the username but it does not show me anything and how can I get Password ?
Thanks Adnan
Upvotes: 1
Views: 1979
Reputation: 10296
Only process and use the credentials in your custom validator. If the credentials are valid, use a custom authorization policy to prepare a custom principal with a set of roles for that user and decorate your service methods with PrincipalPermission attributes.
[PrincipalPermission(SecurityAction.Demand, Authenticated = true, Role = "ClearedForUsingFoo")]
public void Foo(string bar)
{
...
class AuthorizationPolicy : IAuthorizationPolicy
{
public bool Evaluate(EvaluationContext evaluationContext, ref object state)
{
// get the authenticated client identity
IIdentity identity = GetClientIdentity(evaluationContext);
// set the custom principal
evaluationContext.Properties["Principal"] = new CustomPrincipal(identity);
return true;
}
public ClaimSet Issuer
{
get { throw new NotImplementedException(); }
}
public string Id
{
get { return "FooBarApp.AuthorizationPolicy"; }
}
private static 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];
}
}
Upvotes: 1
Reputation: 12680
The CurrentPrincipal property of the thread is the Windows identity the service is running under. Your service is receiving the client identity in the form of a user name/password and it has no relationship to the service identity. WCF supports impersonation and delegation but not using a custom identity scheme like your service is using.
The accepted answer to this question may be what you are looking for. If that doesn't work, it gets pretty ugly pretty quickly to do this manually in code.
Upvotes: 0