HTTP Basic 验证客户端的原理: 把HTTP头重的ContentType设置为:application/x-www-form-urlencoded 如果HTTP头没有Authorization,那么添加,并把这个设置为“Basic 用户名:密码”字符串组合的Base64编码。
代码片段:
request.Method ="GET"; request.ContentType ="application/x-www-form-urlencoded"; request.Credentials = CredentialCache.DefaultCredentials;
//获得用户名密码的Base64编码string code= Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "username", "password")));
//添加Authorization到HTTP头request.Headers.Add("Authorization", "Basic "+ code);
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader =new StreamReader(response.GetResponseStream());
string content= reader.ReadToEnd();
-----------------------------------------------------------
访问需要HTTP Basic Authentication认证的资源的C#实现
要在发送请求的时候添加HTTP Basic Authentication认证信息到请求中,有两种方法:
- 一是在请求头中添加Authorization: Authorization: "Basic 用户名和密码的base64加密字符串"
- 二是在url中添加用户名和密码: http://userName:password@api.minicloud.com.cn/statuses/friends_timeline.xml
下面来看下对于第一种在请求中添加Authorization头部的各种语言的实现代码。
先看.NET的吧:
WebResponse wr = myReq.GetResponse(); Stream receiveStream = wr.GetResponseStream(); StreamReader reader =new StreamReader(receiveStream, Encoding.UTF8); string content = reader.ReadToEnd();
-----------------------------------------------------
using System; using System.Web.Http;
using System.Net.Http;
publicclassAuthAttribute:AuthorizeAttribute
{
publicoverridevoidOnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
HandleUnauthorizedRequest(actionContext);
}
protectedoverridevoidHandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Redirect);
response.Headers.Add("Location","http://www.google.com");
actionContext.Response= response;
}
}