ASP. NET MVC uses FORMSAUTHENTICATION,MVC and Web APIs to share identity authentication (reprint)

Source: Internet
Author: User

In the actual application of the project, many times need to ensure the security and reliability of data, how to ensure the security of data? There are many ways to do this, and the most common is authentication. Authentication is passed, and the corresponding access rights are given based on the authenticated identity. How do you implement identity authentication in the Web API? The next section describes the use of ASP. FormsAuthentication to do both MVC and Web API authentication.

First, extend custom authentication
Add Class CustomAuthorizeAttribute.cs
This class inherits from the System.Web.Http.AuthorizeAttribute (Identity authentication Class) by overriding its identity authentication core method to achieve the effect of Web API identity authentication.
Full code:

 Public classCustomAuthorizeAttribute:System.Web.Http.AuthorizeAttribute { Public Override voidonauthorization (System.Web.Http.Controllers.HttpActionContext actioncontext) {//determine if the user is logged on            if(!HttpContext.Current.User.Identity.IsAuthenticated) handleunauthorizedrequest (Actioncontext); }        protected Override voidhandleunauthorizedrequest (System.Web.Http.Controllers.HttpActionContext actioncontext) {varChallengemessage =NewSystem.Net.Http.HttpResponseMessage (System.Net.HttpStatusCode.Unauthorized); CHALLENGEMESSAGE.HEADERS.ADD ("www-authenticate","Basic"); Throw NewSystem.Web.Http.HttpResponseException (challengemessage); }            }

Add authentication (you must log in for queries, etc.) add attributes to the controller and can be sensed directly from the VS shortcut key

Full code

PS: Written on the controller class is to indicate that each action of this controller is authenticated, and if you want to write for an action directly on the action, do not write on the class.

Next, write the login method

 PublicActionResult Login () {returnView (); } [HttpPost] PublicActionResult Login (formcollection fol) {///here to demonstrate simplified login process///you can expand here to verify that the user name or password is correctSystem.Web.Security.FormsAuthentication.SetAuthCookie (fol["username"],false); returnRedirect ("/htmlpage5.htm"); }

With the back-end approach, the last page of the previous section is left.
By right-clicking in the login method you can quickly generate the page (vs gives us a more efficient tool, not much to do with the introduction)

Write the following login code in the generated login.cshtml

@using (Html.BeginForm ()) {<fieldset>    <label>Account:</label><inputtype= "text"name= "username" /><BR/>    <label>Password:</label><inputtype= "text"name= "Password" /><BR/>    <inputtype= "Submit"value= "Login" />    </fieldset>}

This time there are two small places to do the configuration.
The first one is the Web. config configuration form authentication

<mode= "Forms">      <loginurl= "~/home/login"  timeout= "2880"/>    </  Authentication>

The second is to modify the htmlpage5.html JS (htmlpage5.html can be copied directly htmlpage4.html)
Modify the code that gets the data to jump with authentication
Original JS

function (data) {            //  from the API            //  Get the returned data,                         update the Knockout model and bind to the page UI template             Viewmodel.userinfos (data);        });

The modified JS

$.ajax ({            '/api/userinfo ',            ' GET ',            ' Application/json; Charset=utf-8 ',            StatusCode: {/*Created* *function  (data) {                    Viewmodel.userinfos (data)                function  (JQXHR, Textstatus, Errorthrown) {                    = '/ Home/login ';                }            }        );

Ok here, the code is almost ready to be written, to test
Test first step direct access to/api/userinfo

Test step two to access htmlpage5.html

Meet the requirements of identity authentication
Test the third step to enter the user name password test function can be used?
The answer is yes.

So in the Mvccontroller, The HttpContext.Current.Request.IsAuthenticated property in Mvccontroller and Apicontroller will be true after the Formsauthentication.setauthcookie method is called. , the controller that achieves MVC and the controller of the Web API are all through the purpose of ASP. However, this article discusses the establishment of the ASP. NET project as Forms authentication mode, can do both Mvccontroller and Apicontroller authentication, the other authentication method does not guarantee the Both the controller of MVC and the controller of the Web API take effect at the same time.

ASP. NET MVC uses FORMSAUTHENTICATION,MVC and Web APIs to share identity authentication (reprint)

Related Article

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.