ASP. NET Web API 2 Token-based authentication

Source: Internet
Author: User
Tags oauth

Token-based authentication

We know that the authentication of the Web site is usually done through a session or cookie, and any requests sent by the client after successful login are brought with a cookie, and the server identifies the user based on the cookie sent by the client.

The WEB API uses this method is not very suitable, so there is a token-based authentication, the use of token authentication has several advantages: scalability, loose coupling, mobile terminal calls are relatively simple, and others are used, you have reason not to use it?

Let's take a 20-minute time to implement a simple Web API token certification:

Step 1: Create a new empty Web API project with the project name set to Webapi

Step 2: Create a new Product class in the models directory:

Using system;using system.collections.generic;using system.linq;using system.web;namespace WebApi.Models{    public class Product    {public        int Id {get; set;}        public string Name {get; set;}        public string Category {get; set;}        Public decimal price {get; set;}}    }

Step 3: Create a new ProductsController class in the Controllers directory

Using system;using system.collections.generic;using system.linq;using system.net;using System.Web.Http;using Webapi.models;namespace webapi.controllers{[Routeprefix ("Api/products")] public class Productscontroller:apicontr Oller {product[] products = new product[] {new Product {Id = 1, Name = "Tomato Soup", C               Ategory = "groceries", Price = 1}, new Product {Id = 2, Name = "Yo-Yo", Category = "Toys", Price = 3.75M},        New Product {Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M}};        Public ienumerable<product> getallproducts () {return products; Public Product Getproductbyid (int id) {var product = products.            FirstOrDefault (p) = P.id = = Id);            if (product = null) {throw new httpresponseexception (Httpstatuscode.notfound);        } return product; } public IenumerabLe<product> getproductsbycategory (String category) {return products. Where (p = = string.        Equals (P.category, Category, stringcomparison.ordinalignorecase)); }    }}

F5 can use this simple webapi after running, the test API can use the Postman tool:

Get all data http://localhost:1234/api/products

Get data in the code of 1 HTTP://LOCALHOST:1234/API/PRODUCTS/1

Querying the category= data http://localhost:1234/api/products?category=Groceries

You can see that the API for this product is publicly accessible, without any validation, so it's not very secure, and next I'll add token validation.

Step 4: Install the required NuGet packages:

Open the NuGet Package Manager console and enter the following instructions:

Install-package microsoft.aspnet.webapi.owin-version 5.1.2install-package microsoft.owin.host.systemweb-version 2.1.0install-package Microsoft.aspnet.identity.owin-version 2.0.1
Install-package microsoft.owin.cors-version 2.1.0

Step 5: Add the Owin "Startup" class under the project root directory

Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.Http;using Owin; Using microsoft.owin;using Microsoft.Owin.Security.OAuth; [Assembly:owinstartup (typeof (Webapi.startup))]namespace webapi{public class Startup {public void Configura            tion (Iappbuilder app) {httpconfiguration config = new httpconfiguration ();            Configureoauth (APP);            Webapiconfig.register (config); App.            Usecors (MICROSOFT.OWIN.CORS.CORSOPTIONS.ALLOWALL); App.        Usewebapi (config); } public void Configureoauth (Iappbuilder app) {oauthauthorizationserveroptions oauthserveroption s = new Oauthauthorizationserveroptions () {allowinsecurehttp = True, Tokenendpoi Ntpath = new PathString ("/token"), Accesstokenexpiretimespan = Timespan.fromdays (1), provide         R = new Simpleauthorizationserverprovider ()};   App.            Useoauthauthorizationserver (oauthserveroptions); App.        Useoauthbearerauthentication (New Oauthbearerauthenticationoptions ()); }    }}

Step 6: Delete Global.asax

We have set up the Setup class, we do not need global, delete clean;

Step 7: Add the Validation class Simpleauthorizationserverprovider under the project root, for the verification part of the simple user we omit;

Using system;using system.collections.generic;using system.linq;using system.web;using System.Threading;using System.threading.tasks;using microsoft.owin;using microsoft.owin.security.oauth;using System.Security.Claims; Namespace webapi{public class Simpleauthorizationserverprovider:oauthauthorizationserverprovider {public Override Async Task Validateclientauthentication (oauthvalidateclientauthenticationcontext context) {con Text.        Validated ();        } public override Async Task Grantresourceownercredentials (Oauthgrantresourceownercredentialscontext context) {context.            OWINCONTEXT.RESPONSE.HEADERS.ADD ("Access-control-allow-origin", new[] {"*"});                /* * Data check for username and password, we omit using (authrepository _repo = new Authrepository ()) { Identityuser user = await _repo. Finduser (context. UserName, context.                Password);                    if (user = = null) {Context.                    SetError ("Invalid_grant", "The user name or password is incorrect.");                Return }}*/var identity = new Claimsidentity (context.            Options.authenticationtype); Identity. Addclaim (New Claim ("sub", context.            UserName)); Identity.            Addclaim (New Claim ("Role", "user")); Context.        Validated (identity); }    }}

Step 7: Make cors work

access token validation with OAuth enabled in the ASP. NET Web API is simple, just add the [authorize] tag to the appropriate controller or action

Modifying the ProductsController class

Using system;using system.collections.generic;using system.linq;using system.net;using System.Web.Http;using Webapi.models;namespace webapi.controllers{public class Productscontroller:apicontroller {product[] Produ CTS = new product[] {new Product {Id = 1, Name = "Tomato Soup", Category = "groceries", Price = 1 }, new product {id = 2, Name = "Yo-Yo", Category = "Toys", Price = 3.75M}, new product {id =        3, Name = "Hammer", Category = "Hardware", Price = 16.99M};        [Authorize]        [Route ("")] public ienumerable<product> getallproducts () {return products; } [Authorize] public Product Getproductbyid (int id) {var product = products.            FirstOrDefault (p) = P.id = = Id);            if (product = null) {throw new httpresponseexception (Httpstatuscode.notfound);        } return product; }        [allowanonymous] public ienumerable<product> getproductsbycategory (string category) { return products. Where (p = = string.        Equals (P.category, Category, stringcomparison.ordinalignorecase)); }    }}

Now let's get http://localhost:23477/api/products/again directly returns a 401 error and the request is denied

Get token, POST Http://localhost:23477/token

Parameter Body x-www-form-urlencoded format:

Grant_type=password

Username=admin

password=123456

Returns the 200 status with the content:

{  "Access_token": "Eljau3alm2ywjjkxmx_ fly07p6vbizxasfeckdap3kie0ydp7ightgrzwltpdgrk46rfab-omjsg5c8bh-pkfg3xrgs0udea2kbxyowsr11evtgjiviyxny3ih2dkh04qh2t _ar4kijcangptunsevex26tv4qhirjcq5slkodfdaa9pnl98qvwyh47yo-zlc55bwmgpr2j4fqlynzwvhnzph3dbochq3yenemr6xhm ",  " Token_type ":" Bearer ",  " expires_in ": 86399}

Simply add Authorization:bearer token to the HTTP request header to successfully access the API:

GET http://localhost:23477/api/products/

Authorization:bearer eljau3alm2ywjjkxmx_ fly07p6vbizxasfeckdap3kie0ydp7ightgrzwltpdgrk46rfab-omjsg5c8bh-pkfg3xrgs0udea2kbxyowsr11evtgjiviyxny3ih2dkh04qh2t _ar4kijcangptunsevex26tv4qhirjcq5slkodfdaa9pnl98qvwyh47yo-zlc55bwmgpr2j4fqlynzwvhnzph3dbochq3yenemr6xhm

This allows us to complete the token verification of the simple Web API ~

However, this program has a problem, if Getproductbyid is also added to verify that the interface based on the ID to obtain product HTTP://LOCALHOST:23477/API/PRODUCTS/1 will be an error

Need to be modified into http://localhost:23477/api/products?id=1

I don't know where the problem is.

This article is code: Http://pan.baidu.com/s/1jGxZVKU

Postman Tool please visit here to see the introduction http://www.cnblogs.com/wade-xu/p/4228954.html

ASP. NET Web API 2 authentication based on tokens

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.