在强制WebRequest的基本身份验证 [英] Forcing Basic Authentication in WebRequest

查看:260
本文介绍了在强制WebRequest的基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这将使用

我是集成Web服务 HTTP-POST请求和检索数据。远程服务器 需要基本身份验证按照RFC 2617

我的验证尝试失败了。

据失败的,尽管我附上'的NetworkCredential对象为HttpWebRequest的'对象'证书'的财产,不进行身份验证信息在标头中发送, 即使我设置'preAuthenticate'=真。

我在想什么?

//使用的组块

 的NetworkCredential netCredential =新的NetworkCredential(UID,PWD);

开放的我们的uri =新的URI(HTTP://地址服务);

ICredentials凭证= netCredential.GetCredential(URI,基本法);

objRegistration.Credentials =凭证;

objRegistration preAuthenticate = TRUE。
 

解决方案

我刚刚发现这非常方便的小<一href="http://blog.kowalczyk.info/article/Forcing-basic-http-authentication-for-HttpWebReq.html">chunk code 做正是你需要的。它添加了授权头到code手动无需等待服务器的挑战。

 公共无效SetBasicAuthHeader(WebRequest的要求,字符串username,字符串的userPassword)
{
    字符串AUTHINFO =用户名+:+的userPassword;
    AUTHINFO = Convert.ToBase64String(Encoding.Default.GetBytes(AUTHINFO));
    request.Headers [授权] =基本+ AUTHINFO;
}
 

使用像这样

  VAR请求= WebRequest.Create(http://myserver.com/service);
SetBasicAuthHeader(请求,用户名,密码);

变种响应= request.GetResponse();
 

I am integrating web service that will use an HTTP-POST to request and retrieve data. The remote server requires basic authentication as per RFC 2617

My attempts to authenticate are failing.

It fails in that, even though I attach a 'NetworkCredential' object to the 'Credentials' property of a 'HttpWebRequest' object, no authentication information is sent in the header, even if I set 'PreAuthenticate' = true.

What am I missing?

//chunk used

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;

解决方案

I've just found this very handy little chunk of code to do exactly what you need. It adds the authorization header to the code manually without waiting for the server's challenge.

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

Use it like this

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

var response = request.GetResponse();

这篇关于在强制WebRequest的基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆