使用请求标头对 BasicHttpBinding 进行身份验证

Authentication for BasicHttpBinding using Request Hearder

我有 BasicHttpBinding WCF 服务。我想在请求 header 中获取用户名和密码。我在互联网上搜索了这个,但我只看到 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();

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

谢谢

您可以通过继承 ServiceAuthorizationManager class 并从请求 header 中提取凭据来创建自定义授权 Class。

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

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 属性设置为自定义 class。

与此类似的内容:

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

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

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

安全说明:

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