.net - 在 WebRequest 中强制进行基本身份验证

标签 .net web-services authentication webrequest

我正在集成将使用 HTTP-POST 用于请求和检索数据。远程服务器 需要根据 RFC 2617 进行基本身份验证

我的身份验证尝试失败。

它失败了,即使我将“NetworkCredential”对象附加到“HttpWebRequest”对象的“Credentials”属性, header 中也不会发送任何身份验证信息, 即使我设置 'PreAuthenticate' = true。

我错过了什么?

//使用的 block

NetworkCredential netCredential = new NetworkCredential(" uid", "pwd");

Uri uri = new Uri("http://address of services");

ICredentials credentials = netCredential.GetCredential(uri, "Basic");

objRegistration.Credentials = credentials;

objRegistration.PreAuthenticate = true;

最佳答案

我刚刚发现这个非常方便的小chunk of code准确地做您需要的事情。它手动将授权 header 添加到代码中,而不等待服务器的质询。

public void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
    string authInfo = userName + ":" + userPassword;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
    request.Headers["Authorization"] = "Basic " + authInfo;
}

像这样使用

var request = WebRequest.Create("http://myserver.com/service");
SetBasicAuthHeader(request, userName, password);

var response = request.GetResponse();

关于.net - 在 WebRequest 中强制进行基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2764577/

相关文章:

c# - 如何在 f# 中将整数设置为 null?

c# - 无法将 Json 字符串反序列化为包含对象数组的对象

java - 如何在亚马逊应用商店发布 Firebase 登录应用程序?

android - Firebase 身份验证 - 开源 Android 应用程序

c# - 使用 gmail 地址通过 Postal 发送电子邮件

.net - 防止 XmlTextReader 扩展实体

iphone - 如何从 iPhone 应用程序调用 Web 服务

java - Spring-WS SecurityInterceptor操作级别

authentication - 在 NextJs getInitialProps 中获取 localStorage

.net - 使用.net 3.5框架快速排序