我有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);
}
}
}
除此之外,您还需要将serviceAuthorizationManagerType
元素的serviceAuthorization
属性设置为web.config文件中的自定义类。
与此类似的东西:
<serviceAuthorization serviceAuthorizationManagerType="YourNameSpace.CustomAuthorizationManager, YourAssemblyName"/>
在客户端,您还需要将凭据添加到请求标头。
HttpRequestMessageProperty httpReqProp = new HttpRequestMessageProperty();
httpReqProp.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("username"+ ":" + "p@ssw0rd"));
安全说明:
请记住,在基本身份验证中,用户名和密码将作为非加密文本发送到请求标头中。您应该只使用SSL实现此功能。