繁体   English   中英

使用请求侦听器对 BasicHttpBinding 进行身份验证

[英]Authentication for BasicHttpBinding using Request Hearder

我有一个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();

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

谢谢

您可以通过继承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 来实现这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM