In the previous article ASP.net Web API (i): Using preliminary, get and post data, we initially contacted Microsoft's Rest Api:web API.
We immediately discovered the need for security verification when we contacted the Web API, so this article discusses the simplest way to secure authentication: using HTTP Basic authentication.
HTTP Basic Authentication principle
In the process of communicating with the HTTP protocol, the HTTP protocol defines the Basic authentication process to allow the HTTP server to authenticate users to the Web browser, and when a client makes a data request to the HTTP server, if the client is not authenticated, The HTTP server authenticates the client's username and password through the Basic authentication process to determine whether the user is legitimate.
The basic way to achieve this is:
After the user enters the user name and password, the client the user name and password to BASE64 encryption, encrypted ciphertext will be appended to the request information, such as when the user name is Parry, the password is 123456, the client will username and password by ":" Merged, and the merged string with BASE64 encryption, And each time the data is requested, the redaction is appended to the request header.
HTTP server after each receive request package, according to the protocol to obtain client additional user information (BASE64 encrypted username and password), unlock the request package, the user name and password to verify, if the user name and password is correct, according to the client request, return the data required by the client; Returns an error code or requests the client to provide a username and password.
The Web API uses HTTP Basic authentication for security authentication
We're still testing it based on an example from the previous article.
First we implement an Http Basic authentication class based on the System.Web.Http.AuthorizeAttribute class and implement two methods: Onauthorization and Handleunauthorizedrequest.
Add a class Httpbasicauthorizeattribute, inherit from System.Web.Http.AuthorizeAttribute, first to implement Onauthorization.
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));
The user verifies the logical
if (string). Equals (UserInfo, String. Format ("{0}:{1}", "Parry", "123456")))
{
isauthorized (actioncontext);
}
else
{
handleunauthorizedrequest (actioncontext);
}
}
else
{
handleunauthorizedrequest (actioncontext);
}
}