使用基本身份验证的 HttpWebRequest [英] HttpWebRequest using Basic authentication

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

问题描述

我正在尝试通过一个身份验证请求来模拟我们在为此行为设置 IIS 时看到的基本身份验证请求".

I'm trying to go through an authentication request that mimics the "basic auth request" we're used to seeing when setting up IIS for this behavior.

网址为:https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2
(警告:https!)

The URL is: https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2
(warning: https!)

此服务器在 UNIX 和 Java 下作为应用程序服务器运行.

This server is running under UNIX and Java as application server.

这是我用来连接到此服务器的代码:

This is the code I use to connect to this server:

CookieContainer myContainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2");
request.Credentials = new NetworkCredential(xxx,xxx);
request.CookieContainer = myContainer;
request.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

(我从本网站的另一篇文章中复制了此内容).但是我从服务器收到了这个答案:

(I copied this from another post on this site). But I receive this answer from the server:

底层连接已关闭:发生意外错误发送.

The underlying connection was closed: An unexpected error occurred on a send.

我想我尝试了我的 C# 知识所能提供的所有可能的任务,但什么都没有......

I think I tried every possible task my knowledge on C# has to offer me, but nothing...

推荐答案

您也可以自己添加授权标头.

You can also just add the authorization header yourself.

只需将名称命名为授权"即可和值Basic BASE64({USERNAME:PASSWORD})"

Just make the name "Authorization" and the value "Basic BASE64({USERNAME:PASSWORD})"

var username   = "abc";
var password   = "123";
string encoded = System.Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1")
                               .GetBytes(username + ":" + password));
httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);

编辑

根据 我应该为 HTTP 基本身份验证使用什么编码? 和 Jeroen 的评论.

Edit

Switched the encoding from UTF-8 to ISO 8859-1 per What encoding should I use for HTTP Basic Authentication? and Jeroen's comment.

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

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