Problem using custom principal and identity with WCF services

北城以北 提交于 2019-12-03 09:01:23

WCF has a more standard way of achieving the same goal, via a ServiceAuthorizationBehavior.

If you set its PrincipalPermissionMode property to "Custom", it allows you to provide a custom IAuthorizationPolicy via which you can make a custom IPrincipal available to the WCF ServiceSecurityContext. The DispatchRuntime will assign this (your custom) IPrincipal to Thread.CurrentPrincipal - which is what you're after, right?

This is a sample IAuthorizationPolicy implementation:

public class DemoAuthorizationPolicy : IAuthorizationPolicy
{
    private readonly string id = Guid.NewGuid().ToString();

    public string Id { get { return this.id; } }

    public ClaimSet Issuer { get { return ClaimSet.System; } }

    public bool Evaluate(EvaluationContext context, ref object state)
    {
        // Here, create your custom principal
        IIdentity customIdentity = new GenericIdentity("myUserName", "myCustomAuthenticationType");
        IPrincipal customPrincipal = new GenericPrincipal(customIdentity, new[] { "user", "powerUser" });

        // Set EvaluationContext properties
        context.Properties["Identities"] = new List<IIdentity> { customIdentity };
        context.Properties["Principal"] = customPrincipal;

        return true;
    }
}

And this is how you declare the ServiceAuthorizationBehavior in the Web.config:

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceAuthorization principalPermissionMode="Custom" >
            <authorizationPolicies>
              <add policyType="PrincipalPermissionModeDemo.DemoAuthorizationPolicy, YourAssemblyName"/>
            </authorizationPolicies>
          </serviceAuthorization>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

Inside your service you can then leverage declarative security via the [PrincipalPermission] attribute, you can get the custom IPrincipal from Thread.CurrentPrincipal, and (alternatively) you can also get the custom IIdentity from ServiceSecurityContext.Current.PrimaryIdentity.

Hope that solves your issue!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!