ServiceAuthorizationManager中的授权标头在第二次调用

时间:2016-12-13 11:25:23

标签: rest wcf basic-authentication

我有WCF REST服务,它接受xml数据作为输入并返回一些数据。要实现基本身份验证,请使用ServiceAuthorizationManager。 CheckAccessCore方法调用两次。首先,当我在RequestStream中写入我的xml数据时,第二次我调用GetResponse来获取我的服务返回数据。在第一次调用时,CheckAccessCore中的Authorization标头是正确的,但是当它第二次调用时(在GetResponse期间),授权标头为空。

ServiceAuthorizationManager CheckAccessCore方法

protected override bool CheckAccessCore(OperationContext operationContext)
    {
        var authHeader = WebOperationContext.Current.IncomingRequest.Headers["Authorization"];

        if (!string.IsNullOrEmpty(authHeader))
        {
            var credentials = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(authHeader.Substring(6))).Split(':');
            var user = new
            {
                Name = credentials[0],
                Password = credentials[1]
            };

            if (user.Name == "test" && user.Password == "pass")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            WebOperationContext.Current.OutgoingResponse.Headers.Add("WWW-Authenticate: Basic realm =\"CreditData\"");
            throw new WebFaultException(HttpStatusCode.Unauthorized);
        }
    }

WCF Web.config

<system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="RestBehavior">
          <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Xml"/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceAuthorization serviceAuthorizationManagerType="CreditDataService.Authorization.CreditDataAuthorizationManager, CreditDataService" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="CreditDataService.Services.CreditData" behaviorConfiguration="">
        <endpoint name="REST" behaviorConfiguration="RestBehavior" binding="webHttpBinding" contract="CreditDataService.Contracts.ICreditData"/>
      </service>
    </services>
    <protocolMapping>
      <add binding="webHttpBinding" scheme="https"/>
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
</system.serviceModel>

客户端

private void button4_Click(object sender, EventArgs e)
    {
        try
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:33016/Services/CreditData.svc");
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes("<Request><Firstname>John</Firstname><Lastname>Doe</Lastname><Pid>123456789</Pid></Request>");
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = bytes.Length;
            request.Method = "POST";

            string credentials = "test:pass";
            string enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
            string auth = string.Format("{0} {1}", "Basic", enc);

            request.Headers[HttpRequestHeader.Authorization] = auth;

            Stream reqStream = request.GetRequestStream();
            reqStream.Write(bytes, 0, bytes.Length);
            reqStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream respStream = response.GetResponseStream();
                string respStr = new StreamReader(respStream).ReadToEnd();
                MessageBox.Show(respStr);
            }
        }
        catch (WebException ex)
        {
            if (ex.Response != null)
            {
                var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                MessageBox.Show(resp);
            }

            MessageBox.Show(ex.Message);
        }
    }

没有ServiceAuthorizationManager,它可以正常工作。

1 个答案:

答案 0 :(得分:0)

问题是webservice的方法的UriTemplate。它是空的,当我在呼叫服务时,发生了重定向到只有斜线的同一个URL。例如当我向&#34; http://localhost/myservice.svc&#34;发送请求时它被重定向到&#34; http://localhost/myservice.svc/&#34;。这产生了第二个请求,而第二个请求正好具有Authorization标头null。当我添加UriTemplate问题解决了。