Implementation of OAuth 2.0 using Authorization code grant flow

Kumar Shivam
6 min readJan 7, 2018

Introduction

Today, we are going to implement JSON web token based Authentication and Authorization for web applications using OpenID Connect and OAuth2.0 as protocol and Microsoft Azure Active Directory as the IDP server.

Scenario: — Create a simple MVC web application. Implement resource access with authentication and authorization Or Web application wants to access web api’s resources by passing JWT .

To implement above scenario, we just need a few lines of code and some configuration on azure portal.

Let’s dive into the implementation now :-

I’m using Asp.net MVC4 to implement this flow. But you can use any language, as the underlying concepts and steps will be the same. Since we are using a web application, we will go for Authorization code grant flow.

Step 1 : Click on Create new project in visual studio and select project as “ASP.NET Web Application”

Step 2: Select the template as MVC and click on OK

Step 3: After opening the web application navigate to Edit → Properties window ,change SSL Enabled to True and copy SSL URL.

Step 4 : Open project properties, navigate to web and paste SSL URL into Project URL.

Step 5: Open Web.config file and add keys as shown below . We will set these keys later after registering this application on Azure portal and getting the values.

<add key="ida:ClientId" value="[Enter client ID as obtained from Azure Portal, e.g. 82692da5-a86f-44c9-9d53-2f88d52b478b]" /><add key="ida:ClientSecret" value="[Enter client Secret as obtained from Azure Portal, e.g. a86f82692da5-a86f-9d53-2f88d52b478b]" /><add key="ida:Tenant" value="[Enter tenant name, e.g. crazyDeveloper2.onmicrosoft.com]" /><add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" /><add key="ida:PostLogoutRedirectUri" value="https://localhost:44369/" /><add key="ida:ServiceResourceID"  value="https://crazyDeveloper2.onmicrosoft.com/crazyDeveloper2_WebApplication" />
<!--address of the client application when we will register on azure-->

Step 5 : Add the following Nuget packages

1) Microsoft.Owin.Security.OpenIdConnect

2) Microsoft.IdentityModel.Clients.ActiveDirectory

Step 6: Open Startup.auth.cs and do the following changes

a) In this class we will fetch the value of keys specified in web.config file and put them in some variable.

//The Client ID is used by the application to uniquely identify //itself to Azure AD.ClientID we will get after   registering this //application on Azure ADprivate static string clientId =  ConfigurationManager.AppSettings["ida:ClientId"];//The clientSecret is used by the   application to uniquely //identify itself to Azure AD.private static string clientSecret = ConfigurationManager.AppSettings["ida:ClientSecret"];//The AAD Instance is the instance of   Azure, for example public //Azure or Azure US.private static string addInstance = ConfigurationManager.AppSettings["ida:AADInstance"];private static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];//The Post Logout Redirect Uri is the URL where the user will be //redirected after they sign out.private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];//ServerResourceID is the path where we have registered on azure AD.private static string serviceResourceID = ConfigurationManager.AppSettings["ida:ServiceResourceID"];// The Authority is the sign-in URL of the   tenant.string authority = String.Format(CultureInfo.InvariantCulture,   aadInstance, tenant);//ResourceBaseUrl could be anything (e.g. same web //application //resource or web api as well but for that we have   to again get //the access token and then pass for it )private static string ResourceBaseUrl = "https://localhost:44369/";

b) In ConfigureAuth () method set the default authentication type that will be used by external middle-ware when browser navigates to the URL.

c) Add cookie based authentication middleware in Owin pipeline.

d) Use OPenIDConnect for authentication and set the required parameters as shown below.

e) In Notification we should always implement the code based on the flow .As we are using AuthzrisationCode grant flow , we need the code before creating ClientCredential object.

We have to create the AuthenticationContext passing authority (i.e. sign-in URL of the tenant.) and TokenCache object so that we can cache the tokens in our cookie, local storage or in a DB .If we want to write some custom logic, then we have to inherit TokenCache class. AuthenticationContext has a method “AcquireTokenByAuthorizationCodeAsync”, which acquires security token from the authority using an authorization code previously received. This method does not lookup token cache, but stores the result in it. The method accepts 3 parameters code,ResourceURL and credential.

f) After invoking this method we will get ID_Token, Access_Token, Expiration Time etc.

Let’s configure our MVC application application on Azure portal now

Step 1: Navigate to below link and login

Step 2: In the left navigation pane, Click on Azure Active Directory.

Step 3 :Click on App Registrations àClick on “ADD” button.

Step 4 : select “Add an application my organization is developing”.

Step 5: Enter application Name and select the type of application you are going to register. I’m selecting web application and click on next.

Step 6 : Pass the hosted URL of the application (I would recommend to enable SSl for the application and use https instead of http). Pass same url for Sign in URL and APP ID URL as https://[TenantID]/[ApplicationNameOnAzure] and click on Done .

Step 7: Open your Application and Click on Configure Tab, Get Client ID, AppKey as client secret,TenantID and AADInstance will be https://login.microsoftonline.com/{0}

PostLogoutRedirectUri will be application signURl. You can also configure others applications which you want to access using this application. However other applications must be registered on this portal and permissions needs to be provided using First application.

Step 8: By default the flow will be Implicit Flow grant. We can change the flow after downloading this manifest file. For implementing other grant flows, download this manifest file, search for implicit, make it “false” and then upload this file. Click on Save.

[NOTE: Steps 3 to 7 needs to be repeated for all the applications, which we want to register on azure portal and integrate with SSO mechanism using First application]

Step 9: Launch the application and try to access the resources.

Step 10: Now try to access the resources which you are authorize to access.

I’ve shared a sample application on my Git repository( https://github.com/CrazyDeveloper2/OpenID_OAuth2.0_Implementation) .Please feel free to download ,share and comment for better understanding of AuthorizationCode Grant flow using OpenID connect and OAuth 2.0 protocol.

--

--

Kumar Shivam

Technical Consultant | Passionate about exploring new Technology | Cyber Security Enthusiast | Technical Blogger | Problem Solver