gpt4 book ai didi

c# - 使用请求 header 对 BasicHttpBinding 进行身份验证

转载 作者:行者123 更新时间:2023-11-30 23:04:55 25 4
gpt4 key购买 nike

我有一个 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 创建自定义授权类类并从请求 header 中提取凭据。

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

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);
}
}
}

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

类似的东西:

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

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

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

安全说明:

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

关于c# - 使用请求 header 对 BasicHttpBinding 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49104516/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com