WEBAPI client or server-side security control for ASP. NET Mvc4

Source: Internet
Author: User

First, the Webapi way of working

How WEBAPI works: HTTP requests are first passed to host, and if Webapi is hosted on IIS, the host is IIS and host is not capable or required to process the request. The request was forwarded via host to Httpserver at this time has entered the WEBAPI processing range, Httpserver is a class in System.Net.HTTP, through Httpserver, the request is encapsulated into the webapi of the request bearer Class: Httprequestmessage, this encapsulated request can be processed by a series of custom handler that are concatenated into a pipeline, and the final request is passed to Httpcontroldispather, This class determines the action in the specific controller that the request will be forwarded to by retrieving the routing table.

As we can see earlier, to solve the second problem, can be directly in the handler pipeline, this AOP-style filter (Interceptor) in the rest of the WebService security verification of the application is very wide, generally people are more happy in the HTTP header or in the The URL of the HTTP request is authenticated with the authentication field, and here is a small example of adding authentication information to the HTTP header:

Ii. description

The example used in this section is only slightly modified in the example "ASP. NET MVC4 WEBAPI application Client Access server side", before reading this article, please read the document "ASP. MVC4 WEBAPI Application Client Access server side"

Iii. modification of the example

The solution "MyTest" in the document "WEBAPI application Client Access server side. docx" is opened first, and the following describes our changes to the server side and the client respectively.

1. Server-side

(1), first add a folder, named: Handlerlib

(2), in the folder Handlerlib add a class, and named: Securityhandler, the code is as follows

Using System;

Using System.Collections.Generic;

Using System.Linq;

Using System.Net;

Using System.Net.Http;

Using System.Threading.Tasks;

Using System.Web;

Namespace Myserver.handlerlib

{

public class Securityhandler:delegatinghandler

{

protected override system.threading.tasks.task

CancellationToken)

{

int matchheadercount = Request. Headers.count (item) =

{

if ("keyword"). Equals (item. Key))

{

foreach (Var str in item. Value)

{

Wanli is the agreed server-side authentication password or authentication authentication information

if ("Wanli"). Equals (str))

{

return true;

}

}

}

return false;

});

if (Matchheadercount > 0)

{

Return base. SendAsync (Request, CancellationToken);

}

Return task.factory.startnew

}

}

}

(3), add

Note: The processing logic of the code is simple: If the authentication code matches successfully, it is through base. SendAsync continues to pass the request down, otherwise returns the delivery of the direct interrupt request, directly returning a response code of 403, indicating no permissions.
Note that because the return value of SendAsync needs to be encapsulated in a task, you need to use Task.Factory.StartNew to include the return value in the task

Inject the Securityhandler into the host
In this case, WEBAPI host is on IIS, so we just need to define our defined Securityhandler in Application_Start.

protected void Application_Start ()

{

Omit other logical code

GLOBALCONFIGURATION.CONFIGURATION.MESSAGEHANDLERS.ADD (New Securityhandler ());

}

Because Webapi host is on IIS, Httpserver and Httpcontrollerdispatcher do not have to handle it manually.

2, the client's modification

Add the class RequestCheckHandler.cs with the following code:

The client's Requestcheckhandler is used to add the authentication information into the header

Class Requestcheckhandler:delegatinghandler

{

Protected overridetask

{

Request. Headers.add ("keyword", "Wanli");

Return base. SendAsync (Request,cancellationtoken);

}

}

Note:
1. Requestcheckhandler inherits from the Delegatinghandler class, as mentioned above, Webapi's client and server are designed to correspond to two sets of structure, so whether in the client or the server, Requestcheckhandler are inherited from the Delegatinghandler class
The SendAsync method of 2.DelegatingHandler is the method that will be called when processing the request and accepting the request, the method return value is Httpresponsemessage, the value received is Httprequestmessage, In line with our general knowledge
3. At the end of the method, call base. SendAsync is to pass the request to the other requestcheckhandler of the pipeline and get its return value. Since the method does not contain response's processing logic, simply return the previous Requestcheckhandler return value directly

The backend code for the client's Form1.cs form is modified to

Using System;

Using System.Collections.Generic;

Using System.ComponentModel;

Using System.Data;

Using System.Drawing;

Using System.Linq;

Using System.Net.Http;

Using System.Text;

Using System.Threading.Tasks;

Using System.Windows.Forms;

Namespace MyClient

{

Publicpartial class Form1:form

{

PublicForm1 ()

{

InitializeComponent ();

}

Privatevoid btnSubmit_Click (object sender, EventArgs e)

{

String userName = TxName.Text.Trim ();

String PassWord = TxPwd.Text.Trim ();

String URL =@ "Http://localhost:8748/api/User/GetUserInfo?userName=" + userName + "&password=" +password;

HttpClient client = new HttpClient (new Requestcheckhandler () {Innerhandler = new Httpclienthandler ()});

Httpresponsemessage response = client. Getasync (URL). Result;

String str= Response. Content.readasstringasync (). Result;

MessageBox.Show (str);

}

}

}

The client's main program creates a httpclient,httpclient that can accept a parameter, which is Customhandler, where we embed our defined Requestuphandler, For the processing of embedded authentication codes for the request header, Customhandler embeds its built-in next Customhandler through the Innerhandler attribute, where, because there is no next customerhandler, We embed Httpclienthandler directly to convert Httprequestmessage to HTTP requests, to convert HTTP responses to Httpresponsemessage

WEBAPI client or server-side security control for ASP. NET Mvc4

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.