[ASP.NET] Implementing OAuth under OWIN with Web API

OAuth(Open Authorization)

It provides a secure, open and simple standard for authorization of user resources. Unlike previous authorization methods, OAuth authorization does not allow third parties to touch user account information (such as username and password), that is, third parties can apply for authorization of user resources without using user's username and password, so OAuth is secure.

 

This program catalogue:

 

Web API SelfHost under Owin

1. Create a console project (its class libraries are all available) ApiServer

Nuget quote:

Install-Package Microsoft.AspNet.WebApi.OwinSelfHost

Or cite the following three

Install-Package Microsoft.AspNet.WebApi.Owin (Let WebApi be the middleware)
Install-Package Microsoft.Owin.Hosting (default HttpListener as Server for the Hosting interface)
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 the 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 associate Owin with Startup classes can be seen in my blog:

[ASP.NET] Next Generation ASP.NET Development Specification: OWIN

 

3. Create an Api controller

    public class ValuesController : ApiController
    {
        public string Get()
        {
            return "Never,C";
        }
    }

 

4.Main method startup

        static void Main(string[] args)
        {
            const string url = "http://localhost:1234/";
            using (WebApp.Start<Startup>(url))
            {
                Console.WriteLine("Successful opening");
                Console.ReadLine();
            }
        }

 

5. Browser access

 

 

 

Create AccessToken

On the basis of the Owin Web API above, we begin to implement OAuth.

Nuget:

Install-Package Microsoft. Owin. Security. OAuth (realization of owin's oauth)

 

Using OAuth requires Owin to use UseOAuth Bearer Tokens 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(14),
                AllowInsecureHttp = true,
            };
            app.UseOAuthBearerTokens(OAuthOptions);
        }

 

And set up the Web API to use OAuth

            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); //Additional configuration
            app.UseWebApi(config);

  

 

2. Custom provider

    public class OTWAuthorizationServerProvider : OAuthAuthorizationServerProvider
    {
        //1. Validation of customers
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
       //Here you can judge client and user
//this.ClientId = clientId; //this.IsValidated = true; //this.HasError = false; context.Validated("Self defined clientId"); return base.ValidateClientAuthentication(context); } //Authorized customer 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. Use the client to call us. (It is recommended not to use unit testing, but to 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, then the client

 

Using AccessToken

1.ValuesController adds feature Authorize

    [Authorize]
    public class ValuesController : ApiController
    {
        public string Get()
        {
            return User.Identity.Name;
        }
    }

Access will return

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

 

2. Client Reference

Install-Package Newtonsoft.Json -Version 7.0.1

 

3. Modify the Main method with 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, then the client

 

 

Extension

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

The implementation of OAuth includes DotNet OpenAuth, Thinktecture Identity Server

 

This article address: http://neverc.cnblogs.com/p/4970996.html

 

Reference resources:

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

http://www.cnblogs.com/xizz/p/5038923.html

Reference page: http://qingqingquege.cnblogs.com/p/5933752.html

Tags: ASP.NET Java JSON

Posted on Fri, 28 Dec 2018 08:15:07 -0800 by joma