Authentication for the REST APIs

时间:2022-02-11 09:03:20

HTTP基本认证原理

在HTTP协议进行通信的过程中,HTTP协议定义了基本认证过程以允许HTTP服务器对WEB浏览器进行用户身份认证的方法,当一个客户端向HTTP服务器进行数据请求时,如果客户端未被认证,则HTTP服务器将通过基本认证过程对客户端的用户名及密码进行验证,以决定用户是否合法。

其基本的实现方式是:

客户端在用户输入用户名及密码后,将用户名及密码以BASE64加密,加密后的密文将附加于请求信息中,如当用户名为Parry,密码为123456时,客户端将用户名和密码用":"合并,并将合并后的字符串用BASE64加密,并于每次请求数据时,将密文附加于请求头(Request Header)中。

HTTP服务器在每次收到请求包后,根据协议取得客户端附加的用户信息(BASE64加密的用户名和密码),解开请求包,对用户名及密码进行验证,如果用户名及密码正确,则根据客户端请求,返回客户端所需要的数据;否则,返回错误代码或重新要求客户端提供用户名及密码。

Authentication for the REST APIs

摘自:http://www.cnblogs.com/parry/archive/2012/11/09/ASPNET_MVC_Web_API_HTTP_Basic_Authorize.html

继承System.Web.Http.AuthorizeAttribute

 public class HTTPBasicAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization != null)
{
string userInfo = Encoding.Default.GetString(Convert.FromBase64String(actionContext.Request.Headers.Authorization.Parameter)); if (string.Equals(userInfo, string.Format("{0}:{1}", "admin", "aadmin")))
{
IsAuthorized(actionContext);
}
else
{
HandleUnauthorizedRequest(actionContext);
}
}
else
{
HandleUnauthorizedRequest(actionContext);
}
}
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var challengeMessage = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
challengeMessage.Headers.Add("WWW-Authenticate", "Basic");
throw new System.Web.Http.HttpResponseException(challengeMessage);
}
}Authentication for the REST APIs 客户端2种不同方式调用:
  public static string GetPersonsByRequest()
{
try
{
var userName = "admin";
var passWord = "aadmin";
string url = "http://localhost:4067/api/persons";
string ResultJson = "";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";//设置请求方式
request.ContentType = "application/x-www-form-urlencoded";
//request.ContentType = "text/xml; charset=utf-8";//设置返回xml
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = * ;//设置超时时间
//设置户名密码的Base64编码,添加Authorization到HTTP头
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, passWord))));
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
System.IO.StreamReader str = new System.IO.StreamReader(responseStream, System.Text.Encoding.GetEncoding("UTF-8"));//设置编码
ResultJson = str.ReadToEnd();
response.Close();
str.Close();
}
return ResultJson;
}
catch (Exception ex)
{
return ex.ToString();
}
}
//推荐使用,需要net4.0以上版本支持
public static async Task<string> GetPersonsByClient()
{
try
{
string responseBody = "";
var userName = "admin";
var passWord = "aadmin";
using (HttpClient client = new HttpClient())
{
//绑定请求地址
client.BaseAddress = new Uri("http://localhost:4067/");
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
//设置Http请求验证信息
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, passWord))));
using (HttpResponseMessage response = client.GetAsync("api/persons").Result)
{
if (response.IsSuccessStatusCode)//判断响应是否成功!
{
responseBody = await response.Content.ReadAsStringAsync();
}
}
}
return responseBody;
}
catch (Exception ex)
{
return ex.ToString();
}
}
private static string RequestResult(TypeMethods tppe)
{
string Result = "";
switch (tppe)
{
case TypeMethods.HttpClient:
Result = GetPersonsByClient().Result;
break;
case TypeMethods.HttpWebRequest:
Result = GetPersonsByRequest();
break;
default:
break;
}
return Result; }
[Flags]
public enum TypeMethods
{
HttpClient = ,
HttpWebRequest = ,
}
static void Main(string[] args)
{
string json1 = RequestResult(TypeMethods.HttpClient);
string json2 = RequestResult(TypeMethods.HttpWebRequest); }
}