[ASP] implements OAuth with the Web API under Owin

Source: Internet
Author: User
Tags oauth ticket

OAuth (Open Authorization)

Provides a secure, open, and easy standard for the authorization of user resources. Unlike previous licensing methods, OAuth's authorization does not allow a third party to touch the user's account information (such as a user name and password), which means that the third party can request authorization for the user's resources without using the user's username and password, so OAuth is secure.

This program is recorded:

    • Owin under Webapi selfhost
    • Create Accesstoken
    • Using Accesstoken

Owin under Webapi selfhost

1. Create a console project (in fact, the class library can) Apiserver

NuGet References:

Install-package Microsoft.AspNet.WebApi.OwinSelfHost

or refer to the following three

Install-package Microsoft.AspNet.WebApi.Owin (let WebApi as middleware)
Install-package Microsoft.Owin.Hosting (Hosting interface uses HttpListener as server by default)
Install-package Microsoft.Owin.Host.HttpListener (default server implementation)

2. Add Startup class

        public void configuration (Iappbuilder app)        {            //For more information on how to configure an application, visit http://go.microsoft.com/fwlink/? linkid=316888            apiconfig (APP);        }        private static void Apiconfig (Iappbuilder app)        {            var config = new httpconfiguration ();            Config. Routes.maphttproute (                name: "Defaultapi",                routetemplate: "Api/{controller}/{action}/{id}",                defaults : new {id = routeparameter.optional, action = routeparameter.optional}                );            App. Usewebapi (config);        }

How to get Owin associated to the Startup class method, you can see my blog:

[ASP] Next generation asp: OWIN

3. Create an API controller

    public class Valuescontroller:apicontroller    {public        string Get ()        {            return ' never, C ';        }    }

4.Main method Start

        static void Main (string[] args)        {            const string url = "http://localhost:1234/";            using (webapp.start<startup> (URL))            {                Console.WriteLine ("Open Successfully");                Console.ReadLine ();            }        }

5. Browser access

Create Accesstoken

On the basis of the Owin Web API above, OAuth is started to be implemented.

Nuget:

Install-package Microsoft.Owin.Security.OAuth (Implementation of OAuth for Owin)

Using OAuth will require Owin to use Useoauthbearertokens authentication, so reference

Install-package Microsoft.AspNet.Identity.Owin

1. Add a middleware configuration to startup

    private static void Oauthconfig (Iappbuilder app)        {            var oauthoptions = new Oauthauthorizationserveroptions            {                Tokenendpointpath = new PathString ("/token"),                Provider = new Otwauthorizationserverprovider (),                Accesstokenexpiretimespan = Timespan.fromdays (+),                Allowinsecurehttp = true,            };            App. Useoauthbearertokens (oauthoptions);        }

and set the Web API to use OAuth

            Config. Filters.add (New Hostauthenticationfilter (Oauthdefaults.authenticationtype)); Add the configuration            app. Usewebapi (config);

  

2. Custom Provider

public class Otwauthorizationserverprovider:oauthauthorizationserverprovider {//1. Verify customer public override Task validateclientauthentication (Oauthvalidateclientauthenticationcontext context) {
Here you can judge the client and user
This. ClientId = ClientId; This. Isvalidated = true; This. Haserror = false; Context. Validated ("Custom ClientID"); Return base. Validateclientauthentication (context); }//Authorized client public override Task Grantclientcredentials (Oauthgrantclientcredentialscontext context) { var ticket = new Authenticationticket (new Claimsidentity (new[] {new Claim (Claimtypes.name, "Never, C")}, Context . Options.authenticationtype), NULL); This. Ticket = Ticket; This. Isvalidated = true; This. Haserror = false; Context. Validated (ticket); Return base. Grantclientcredentials (context); } }

3. Call us using the client (do not recommend unit testing, create a new console project here)

        static void Main (string[] args)        {            const string url = "http://localhost:1234/";            var client = new HttpClient ();            var rst = client. Postasync (URL + "token", New Stringcontent ("Grant_type=client_credentials")). Result.Content.ReadAsStringAsync (). Result;            Console.WriteLine (RST);        }

  

4. Start the server first and then start the client

Using Accesstoken

1.ValuesController Add feature Authorize

    [Authorize]    public class Valuescontroller:apicontroller    {public        string Get ()        {            return user.identity.name;< c15/>}    }

Access will return

{"Response status code does not indicate success:401 (unauthorized)."}

2. Client References

Install-package newtonsoft.json-version 7.0.1

3. Modify the Main method and bring the token

    Class program    {        static void Main (string[] args)        {            const string url = "http://localhost:1234/";            var client = new HttpClient ();            var rst = client. Postasync (URL + "token", New Stringcontent ("Grant_type=client_credentials")). Result.Content.ReadAsStringAsync (). Result;            var obj = jsonconvert.deserializeobject<token> (rst);            Client. Defaultrequestheaders.authorization = new Authenticationheadervalue ("Bearer", obj. Accesstoken);            RST = client. Getstringasync (url + "Api/values"). Result;            Console.WriteLine (RST);            Console.ReadLine ();        }    }    public class Token    {        [Jsonproperty (' Access_token ')] public        string Accesstoken {get; set;}    }

  

4. Start the server first and then start the client

Extended

In fact, OAuth itself can be achieved, the essence is to generate an encrypted unique string

The implementation of OAuth also has Dotnetopenauth, Thinktecture identityserver

Reference:

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

Http://www.cnblogs.com/dudu/p/4569857.html

[ASP] implements OAuth with the Web API under Owin

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.