【问题标题】:Authentication for BasicHttpBinding using Request Hearder使用请求标头对 BasicHttpBinding 进行身份验证
【发布时间】:2018-03-05 06:17:19
【问题描述】:

我有一个BasicHttpBinding WCF 服务。我想在请求标头中获取用户名和密码。我在互联网上搜索了这个,但我只看到WSHttpBinding。我想要这样的东西:

 //WCF client call
 WCFTestService.ServiceClient myService = new
 WCFTestService.ServiceClient();
 myService.ClientCredentials.UserName.UserName = "username";
 myService.ClientCredentials.UserName.Password = "p@ssw0rd";
 MessageBox.Show(myService.GetData(123));
 myService.Close();

但我不知道我应该为服务器端写什么?

谢谢

【问题讨论】:

标签: c# wcf c#-4.0 request-headers basichttpbinding


【解决方案1】:

您可以通过继承ServiceAuthorizationManager 类来创建自定义授权类,并从请求标头中提取凭据。

您的代码可能类似于以下内容:

public class CustomAuthorizationManager : 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.Encoding.ASCII
                .GetString(Convert.FromBase64String(authHeader.Substring(6)))
                .Split(':');
            var user = new
            {
                Name = svcCredentials[0],
                Password = svcCredentials[1]
            };
            if ((user.Name == "username" && user.Password == "p@ssw0rd"))
            {
                //User is authorized 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=\"YourNameSpace\"");
            //Throw an exception with the associated HTTP status code equivalent to HTTP status 401  
            throw new WebFaultException(HttpStatusCode.Unauthorized);
        }
    }
}

除此之外,您还需要在 web.config 文件中将serviceAuthorization 元素的serviceAuthorizationManagerType 属性设置为您的自定义类。

类似的东西:

<serviceAuthorization serviceAuthorizationManagerType="YourNameSpace.CustomAuthorizationManager, YourAssemblyName"/>

在客户端,您还需要将凭据添加到请求标头中。

HttpRequestMessageProperty httpReqProp = new HttpRequestMessageProperty();
httpReqProp.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("username"+ ":" + "p@ssw0rd"));

安全说明:

请记住,在基本身份验证中,用户名和密码将作为请求标头中的非加密文本发送。您应该只使用 SSL 来实现它。

【讨论】:

  • 谢谢,如何将最后一个代码添加到Request Header?
猜你喜欢
  • 2018-02-16
  • 1970-01-01
  • 2023-04-07
  • 2020-05-06
  • 1970-01-01
  • 2017-10-14
  • 1970-01-01
  • 1970-01-01
  • 2014-07-04
相关资源
最近更新 更多