CustomAuthorizationPolicy.Evaluate()方法从不会在wcf webhttpbinding中触发 [英] CustomAuthorizationPolicy.Evaluate() method never fires in wcf webhttpbinding

查看:94
本文介绍了CustomAuthorizationPolicy.Evaluate()方法从不会在wcf webhttpbinding中触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所见,我创建了一个wcf服务:

I create a wcf service as you can see :

[OperationContract]
[PrincipalPermission(SecurityAction.Demand, Role = "Admin")]
[WebInvoke(Method = "GET", UriTemplate = "/Data/{data}")]

string GetData(string data);

所以我创建了一个自定义授权,如您所见:

So I create a custom authorize as you can see :

public class AuthorizationPolicy : IAuthorizationPolicy
{
    string id = Guid.NewGuid().ToString();

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

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

    // this method gets called after the authentication stage
    public bool Evaluate(EvaluationContext evaluationContext, ref object state)
    {
        // get the authenticated client identity
        IIdentity client = HttpContext.Current.User.Identity;

        // set the custom principal
        evaluationContext.Properties["Principal"] = new CustomPrincipal(client);

        return true;
    }
}

public class CustomPrincipal : IPrincipal
{
    private IIdentity _identity;
    public IIdentity Identity
    {
        get
        {
            return _identity;
        }
    }

    public CustomPrincipal(IIdentity identity)
    {
        _identity = identity;
    }

    public bool IsInRole(string role)
    {
        //my code 
        return true;

       // return Roles.IsUserInRole(role);
    }
}

和身份验证:

  public class RestAuthorizationManager: ServiceAuthorizationManager
    {
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            //Extract the Authorization header, and parse out the credentials converting the Base64 string:  
            var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];
            if ((authHeader != null) && (authHeader != string.Empty))
            {
                var svcCredentials = System.Text.ASCIIEncoding.ASCII
                    .GetString(Convert.FromBase64String(authHeader.Substring(6)))
                    .Split(':');
                var user = new
                {
                    Name = svcCredentials[0],
                    Password = svcCredentials[1]
                };
                if ((user.Name == "1" && user.Password == "1"))
                {
                    //here i get the role of my user from the database
                    // return Admin role 
                    //User is authrized and originating call will proceed  
                    return true;
                }
                else
                {
                    //not authorized  
                    return false;
                }
            }
            else
            {
                //No authorization header was provided, so challenge the client to provide before proceeding:  
                WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm=\"MyWCFService\"");
                //Throw an exception with the associated HTTP status code equivalent to HTTP status 401  
                throw new WebFaultException(HttpStatusCode.Unauthorized);
            }
        }
    }

因此我在IIS中创建并托管了https,然后上传了服务,我的身份验证类正在运行,但是我的授权不起作用.为什么?我在Web配置中定义了我的身份验证.知道如何在Web配置中定义我的授权.

So I create and https hosting in my IIS and I upload the service, my authentication class is working but my authorize doesn't .why?I define my authentication in my web config as you can see.But I don't know how can I define my authorize in my web config.

<?xml version="1.0"?>
<configuration>

<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.serviceModel>
<client />

<bindings>
  <webHttpBinding>
    <binding>
      <security mode="Transport" />
    </binding>
  </webHttpBinding>
</bindings>

<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">

      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
      <serviceAuthorization
        serviceAuthorizationManagerType  
    ="wcfrestauth.RestAuthorizationManager, wcfrestauth"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="webHttpServiceBehavior">
      <!-- Important this is the behavior that makes a normal WCF service to REST based service-->
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
  <service name="wcfrestauth.Service1" behaviorConfiguration="ServiceBehavior">
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost/WCFRestAuthentication/api/" />
      </baseAddresses>
    </host>
    <endpoint binding="webHttpBinding" contract="wcfrestauth.IService1" behaviorConfiguration="webHttpServiceBehavior" />
  </service>
</services>

<protocolMapping>
  <add binding="webHttpBinding" scheme="https"/>

</protocolMapping>

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>

</configuration>

我的意思是当我在客户端中调用服务时,该服务不检查授权功能.我应该在webconfig内定义我的自定义授权类,但我不知道如何?

I mean when I call my service in client .the service doesn't check the authorize function.i should define my custom authorize class inside the webconfig but i don't know how ?

public bool IsInRole(string role)
{
    //my code 
    return true;

    // return Roles.IsUserInRole(role);
}

推荐答案

您可能需要在web config文件中设置serviceCredentials:

You might need to set serviceCredentials in your web config file:

<serviceCredentials type="YourString">
     <YourTagsHere>
     </YourTagsHere>
</serviceCredentials>

这里是指向有关serviceCredentials的更多信息的链接: https://docs.microsoft.com/zh-cn/dotnet/framework/configure-apps/file-schema/wcf/servicecredentials

Here's a link to more information about serviceCredentials: https://docs.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/wcf/servicecredentials

这篇关于CustomAuthorizationPolicy.Evaluate()方法从不会在wcf webhttpbinding中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆