Header Ads

ASP.NET MVC: OAuth 2.0 REST Web API Authorization using Database First Approach

REST Web API is light weighted essential component of web development in order to share data across multiple client machines or devices e.g. mobile devices, desktop applications or any website. Authorization of REST Web API is equally important part for sharing data across multiple client machines and devices in order to protect data sensitivity from any outside breaches and to authenticate the utilization of the target REST Web API.

Authorization of REST Web API can be done via specific username/password with the combination of a secret key, but, wait for this type to authorization scheme, REST Web API access needs to be authenticated per call to the hosting server. Also, we as the owner of the server have no way to verify the fact that who is utilizing our REST Web API whether it's the clients that we have allowed access to or some malicious user is also using our API(s) without our knowledge. Finally, since the username/password is packed to a base64 format automatically by the browser this means if  any malicious user traces my browser activity and get the hold of my REST Web API calls they can easily decrypt base64 format and could use my REST Web API for malicious activities. Hmmmmm.....scary stuff not to mention that despite the fact that I have authorize my REST Web API, it is still opened for malicious users to utilize without even my knowledge. So, what to do? To answer that a new authorization scheme is introduced which can also be utilized in Login flow of any web application as well, but, I will be focusing on it from REST Web API perspective. So, this new scheme of authorization is OAuth 2.0 which is a token base authorization scheme.

Let's compare OAuth 2.0 authorization scheme to the traditional username/password authorization scheme from REST Web API perspective i.e.


Username/Password REST Web API Authorization
VS
OAuth 2.0 REST Web API Authorization
1.  
Access Authorization to same or different REST Web API(s) on same server is authenticated on each call with provided username/password.
Access Authorization is authenticated only once base on the system’s existing user credential, then on successful authorization an access token is provided for specific period of time. REST Web API(s) call can utilize the access token which server will not authenticate again and again.
2.  
REST Web API(s) call cannot track the user who is consuming the REST Web API(s). Its utilization is based on mutual trust between Producer and consumer.
Only local system users can consume the REST Web API(s), so, REST Web API call can track the user who is consuming the REST Web API.
3.  
Username/Password is encrypted in base64 format. So, hackers can easily decrypt the request headers.
Access Token is encrypted in a special format. So, hackers cannot easily decrypt it even with access to request header.
4.  
All client machines or devices code needs to be updated in case of change in username/password for malicious activities.
Access token is activated for specific time period. Change in system user’s credential will not require change of code in target consumer client machines and devices. Update credential generated new access token.
5.  
Username/Password is fixed.
Access token is generated automatically based on system user’s credential.

Today, I shall demonstrate OAuth 2.0 mechanism to authorize a REST Web API which will also give us benefit of [Authorize] attribute via OWIN security layer.



Following are few prerequisites before you proceed any further:
  1. Knowledge of OAuth 2.0.
  2. Knowledge of ASP.NET MVC5.  
  3. Knowledge of C# programming.  
  4. Knowledge of REST Web API.
You can download the complete source code or you can follow step by step discussion below. The sample code is developed in Microsoft Visual Studio 2015 Enterprise.

Download Link

Let's begin now:  

1) Create a new Web API project and name it "WebApiOauth2".
2) Install the following Nuget packages into your project  i.e.
  1.  Microsoft.Owin.Security.OAuth
  2.  Microsoft.Owin.Cors
  3. Microsoft.AspNet.WebApi.Core
  4. Microsoft.AspNet.WebApi.Owin
3) Create "DB_Oauth_API" database into your SQL server and execute the following script on it i.e.

USE [DB_Oauth_API]
GO
/****** Object:  StoredProcedure [dbo].[LoginByUsernamePassword]    Script Date: 5/10/2018 2:37:02 PM ******/
DROP PROCEDURE [dbo].[LoginByUsernamePassword]
GO
/****** Object:  Table [dbo].[Login]    Script Date: 5/10/2018 2:37:02 PM ******/
DROP TABLE [dbo].[Login]
GO
/****** Object:  Table [dbo].[Login]    Script Date: 5/10/2018 2:37:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Login](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[username] [varchar](50) NOT NULL,
	[password] [varchar](50) NOT NULL,
 CONSTRAINT [PK_Login] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Login] ON 

INSERT [dbo].[Login] ([id], [username], [password]) VALUES (1, N'admin', N'adminpass')
SET IDENTITY_INSERT [dbo].[Login] OFF
/****** Object:  StoredProcedure [dbo].[LoginByUsernamePassword]    Script Date: 5/10/2018 2:37:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Asma Khalid>
-- Create date: <Create Date,,15-Mar-2016>
-- Description:	<Description,,You are Allow to Distribute this Code>
-- =============================================
CREATE PROCEDURE [dbo].[LoginByUsernamePassword] 
	@username varchar(50),
	@password varchar(50)
AS
BEGIN
	SELECT id, username, password
	FROM Login
	WHERE username = @username
	AND password = @password
END

GO
 
In the above script, I have created a simple login table and a store procedure to retrieve the specific login. I am using entity framework database first approach for database connection for this asp.net mvc web api application. Do also update your SQL server connection string in the project "Web.config" file if you have downloaded the project i.e.


4) Rename "Controllers/ValueController.cs" file to "Controllers/WebApiController.cs".
5) Open, "Controllers/WebApiController.cs" file replace following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApiOauth2.Controllers
{
    [Authorize]
    public class WebApiController : ApiController
    {
        // GET api/WebApi
        public IEnumerable<string> Get()
        {
            return new string[] { "Hello REST API", "I am Authorized" };
        }

        // GET api/WebApi/5
        public string Get(int id)
        {
            return "Hello Authorized API with ID = " + id;
        }

        // POST api/WebApi
        public void Post([FromBody]string value)
        {
        }

        // PUT api/WebApi/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/WebApi/5
        public void Delete(int id)
        {
        }
    }
}

In above code, I have created very simple and basic REST Web API(s). Notice [Authorize] attribute is already placed at the top of the controller to make the REST Web API(s) access secure. 

6) Now open "App_Start/WebApiConfig.cs" file and replace following code in it i.e.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;

namespace WebApiOauth2
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // WebAPI when dealing with JSON & JavaScript!
            // Setup json serialization to serialize classes to camel (std. Json format)
            var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            formatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

            // Adding JSON type web api formatting.
            config.Formatters.Clear();
            config.Formatters.Add(formatter);
        }
    }
}

In the above code following two line of code will add authentication filter for Oauth 2.0 authorization scheme and surpass any existing authorization scheme i.e.

            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

7) Now, open "App_Start/Startup.Auth.cs" file and replace following code in it i.e.

using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Owin;
using WebApiOauth2.Models;
using Microsoft.Owin.Security.OAuth;
using WebApiOauth2.Helper_Code.OAuth2;

namespace WebApiOauth2
{
    public partial class Startup
    {
        #region Public /Protected Properties.

        /// <summary>
        /// OAUTH options property.
        /// </summary>
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        /// <summary>
        /// Public client ID property.
        /// </summary>
        public static string PublicClientId { get; private set; }

        #endregion

        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                LogoutPath = new PathString("/Account/LogOff"),
                ExpireTimeSpan = TimeSpan.FromMinutes(5.0),
            }); 
                       
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new AppOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(4),
                AllowInsecureHttp = true //Don't do this in production ONLY FOR DEVELOPING: ALLOW INSECURE HTTP!
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
    }
}

In the above piece of code, "PublicClientId" is used when "AuthorizeEndpointPath" is utilize for unique instantiate from client side. Following lines of code will enable the OAuth 2.0 authorization scheme i.e.

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new AppOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromHours(4),
                AllowInsecureHttp = true //Don't do this in production ONLY FOR DEVELOPING: ALLOW INSECURE HTTP!
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

OAuthAuthorizationOptions are explained as follow i.e.

TokenEndpointPath -> This is the path which will be called in order to authorize the user credentials and in return it will return the generated access token.

Provider -> You need to implement this class (which I have in this tutorial) where you will verify the user credential and create identity claims in order to return the generated access token.

AuthorizeEndpointPath -> In this tutorial I am not using this property as I am not taking consent of external logins. So, if you are using external logins then you can update this path to get user consent then require access token will be generated.

AccessTokenExpireTimeSpan -> This is the time period you want your access token to be accessible. Shorter time span is recommended for sensitive api(s).

AllowInsecureHttp -> Use this property for developer environment.

More properties can be studied here.

8) Now, create "Helper_Code/OAuth2/AppOAuthProvider.cs" file and replace following code in it i.e.

//-----------------------------------------------------------------------
// <copyright file="AppOAuthProvider.cs" company="None">
//     Copyright (c) Allow to distribute this code.
// </copyright>
// <author>Asma Khalid</author>
//-----------------------------------------------------------------------

namespace WebApiOauth2.Helper_Code.OAuth2
{
    using Microsoft.Owin.Security;
    using Microsoft.Owin.Security.Cookies;
    using Microsoft.Owin.Security.OAuth;
    using Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Web;

    /// <summary>
    /// Application OAUTH Provider class.
    /// </summary>
    public class AppOAuthProvider : OAuthAuthorizationServerProvider
    {
        #region Private Properties

        /// <summary>
        /// Public client ID property.
        /// </summary>
        private readonly string _publicClientId;

        /// <summary>
        /// Database Store property.
        /// </summary>
        private Oauth_APIEntities databaseManager = new Oauth_APIEntities();

        #endregion

        #region Default Constructor method.

        /// <summary>
        /// Default Constructor method.
        /// </summary>
        /// <param name="publicClientId">Public client ID parameter</param>
        public AppOAuthProvider(string publicClientId)
        {
            //TODO: Pull from configuration
            if (publicClientId == null)
            {
                throw new ArgumentNullException(nameof(publicClientId));
            }

            // Settings.
            _publicClientId = publicClientId;
        }

        #endregion

        #region Grant resource owner credentials override method.

        /// <summary>
        /// Grant resource owner credentials overload method.
        /// </summary>
        /// <param name="context">Context parameter</param>
        /// <returns>Returns when task is completed</returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Initialization.
            string usernameVal = context.UserName;
            string passwordVal = context.Password;
            var user = this.databaseManager.LoginByUsernamePassword(usernameVal, passwordVal).ToList();

            // Verification.
            if (user == null || user.Count() <= 0)
            {
                // Settings.
                context.SetError("invalid_grant", "The user name or password is incorrect.");

                // Retuen info.
                return;
            }

            // Initialization.
            var claims = new List<Claim>();
            var userInfo = user.FirstOrDefault();

            // Setting
            claims.Add(new Claim(ClaimTypes.Name, userInfo.username));

            // Setting Claim Identities for OAUTH 2 protocol.
            ClaimsIdentity oAuthClaimIdentity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesClaimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);

            // Setting user authentication.
            AuthenticationProperties properties = CreateProperties(userInfo.username);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthClaimIdentity, properties);

            // Grant access to authorize user.
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesClaimIdentity);
        }

        #endregion

        #region Token endpoint override method.

        /// <summary>
        /// Token endpoint override method
        /// </summary>
        /// <param name="context">Context parameter</param>
        /// <returns>Returns when task is completed</returns>
        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                // Adding.
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

            // Return info.
            return Task.FromResult<object>(null);
        }

        #endregion

        #region Validate Client authntication override method

        /// <summary>
        /// Validate Client authntication override method
        /// </summary>
        /// <param name="context">Contect parameter</param>
        /// <returns>Returns validation of client authentication</returns>
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // Resource owner password credentials does not provide a client ID.
            if (context.ClientId == null)
            {
                // Validate Authoorization.
                context.Validated();
            }

            // Return info.
            return Task.FromResult<object>(null);
        }

        #endregion

        #region Validate client redirect URI override method

        /// <summary>
        /// Validate client redirect URI override method
        /// </summary>
        /// <param name="context">Context parmeter</param>
        /// <returns>Returns validation of client redirect URI</returns>
        public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
        {
            // Verification.
            if (context.ClientId == _publicClientId)
            {
                // Initialization.
                Uri expectedRootUri = new Uri(context.Request.Uri, "/");

                // Verification.
                if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                {
                    // Validating.
                    context.Validated();
                }
            }

            // Return info.
            return Task.FromResult<object>(null);
        }

        #endregion

        #region Create Authentication properties method.

        /// <summary>
        /// Create Authentication properties method.
        /// </summary>
        /// <param name="userName">User name parameter</param>
        /// <returns>Returns authenticated properties.</returns>
        public static AuthenticationProperties CreateProperties(string userName)
        {
            // Settings.
            IDictionary<string, string> data = new Dictionary<string, string>
                                               {
                                                   { "userName", userName }
                                               };

            // Return info.
            return new AuthenticationProperties(data);
        }

        #endregion
    }
}

In above code, "GrantResourceOwnerCredentials(...)" method is the key method which is called when TokenEndpointPath is called. Notice that "GrantResourceOwnerCredentials(...)" method is used by "grant_type=password" scheme. If you are using "grant_type=client_credentials" scheme than you need to override "GrantClientCredentials(...)" method. Other methods are part of "OAuthAuthorizationServerProvider" class, use them as it is. In "GrantResourceOwnerCredentials(...)" method we are verifying the system login user and then create the require identities claims and then generate the returning access token ticket i.e.

        #region Grant resource owner credentials override method.

        /// <summary>
        /// Grant resource owner credentials overload method.
        /// </summary>
        /// <param name="context">Context parameter</param>
        /// <returns>Returns when task is completed</returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Initialization.
            string usernameVal = context.UserName;
            string passwordVal = context.Password;
            var user = this.databaseManager.LoginByUsernamePassword(usernameVal, passwordVal).ToList();

            // Verification.
            if (user == null || user.Count() <= 0)
            {
                // Settings.
                context.SetError("invalid_grant", "The user name or password is incorrect.");

                // Retuen info.
                return;
            }

            // Initialization.
            var claims = new List<Claim>();
            var userInfo = user.FirstOrDefault();

            // Setting
            claims.Add(new Claim(ClaimTypes.Name, userInfo.username));

            // Setting Claim Identities for OAUTH 2 protocol.
            ClaimsIdentity oAuthClaimIdentity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesClaimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationType);

            // Setting user authentication.
            AuthenticationProperties properties = CreateProperties(userInfo.username);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthClaimIdentity, properties);

            // Grant access to authorize user.
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesClaimIdentity);
        }

        #endregion

9) Now, execute the project and use following link in the browser to see your newly created REST Web API method in action as follow:

 yourlink:port/api/WebApi 

In the above snippet, you will notice that since, now our REST Web API has been authorized, therefore, we cannot directly execute the REST Web API URL in the browser.  

10) Lets, test out REST Web API in REST Web API client. I am using fire fox plugin i.e. "RESTED". At, first, I simply try to hit the REST Web API without any authorization details and I will get following response i.e.


11) Now, I will provide the system user authorization to get access token and then use that access token as header in the REST Web API and try to his the REST Web API which will return following response i.e.


Notice in above snippets that access token is provided as "Authorization" header with "Bearer access_token" scheme in order to call the REST Web API. Also, notice the path when token is being generated i.e. "{your_site_url}/Token".

Conclusion

In this article, you will learn about OAuth 2.0 authorization scheme integration with ASP.NET MVC REST Web API. You will also learn about short comparison between user/password base authorization and OAuth 2.0 token base authorization. You will also learn about OAuth 2.0 scheme authentication mechanism for system local users with entity framework database first approach.

No comments