What is OAuth? Secure Your ASP.NET Core App with OAuth 2.0
What is OAuth? And Why OAuth?
These days whenever you visit any website or application to create/login, you would see many options other than the regular register/login screen which will do the same work for you.
Let’s take the example of dotnettricks.com. When you click on the Login button in their application, the below pop-up comes in front of you. You can Login using your Email Id/password OR Facebook Account OR Google Account. Right?
So, what happens when you click on the ‘Sign in with Google’ button? Dotnettricks.com redirects you to the google sign in page (image below), where you can use you already existing credentials OR create new account using google, to sign in to dotnettricks.com.
Isn’t that amazing? No hussle-bussle to have a Login form with all sort of validations & on top take the user information and then also check if the authentication/authorization of the user & what not. Phew !!!
But then you must be thinking how does this user gets validated, if your application is not supposed to worry. Right? It’s the OAuth service provider look out. The OAuth service provider is responsible to do all the ground work from authenticating the user to protecting user data. How? Again you are not the one to bother. OAuth service provider have their own grounds and logics to manage the same (uses cryptography standard to protect the data).
Example Using OAuth 2.0
User Authentication Application
Creating Login Application
For this article, we will be using the default authentication scaffolding provided by .Net Core using Visual Studio 2019. For details, you can refer this article.
Please note: While selecting the new scaffolding, select ‘Account/Login’
After your application is ready, run the application. You would see the below page,
Surprises !! We have a readymade HTML which we will be updating further. Now, let us see how to bind OAuth service to our application.
In this article, we will be seeing how to integrate OAuth in your application using Google+ (Google plus) authentication service.
Creating OAuth Credentials
To enable Google+ authentication service, we first need to register our application with Google. This step will give us the Google+ credentials like ClientId and SecretKey, which we would need to bind the service in our application.
Step 1: Navigate to Developer console
- Navigate to https://console.developers.google.com and login with your gmail credentials which you want to use to manage your application with Google authentication service.
Step 2: Create a new project
- Click on ‘Select a project’. A new window will open.
- Click on ‘New project’
- Give a meaningful name to your project. I gave it as ‘Authentication Management’.
- Click on create
Step 3: Enable Google+ API
- Click on either ‘Library’ menu or ‘Enable APIs and services’. This will launch Google API Library page.
- Search for ‘Google Plus’.
- After search, you will get many options to choose from. Select the appropriate one. For this article, I will click on ‘Google+ API’ option.
- This will load the Google+ API page. Click ‘Enable’ button.
Step 4: Configure OAuth Consent Screen
- Click on header logo to load the required menu
- Select ‘OAuth consent screen’
- Here you will get two options to select from,
- This option is used if you want your application to be accessed by users in your organization only.
- The user will be verified with the organization G suite users
- The default google verification will be ignored in such case
- In short, if your application is a private application
- Your application is accessible to any user with a google account
- Please note, if your application is requesting for some sensitive user data, then in such cases verification of your application needs to be done by Google which would take 4-6 weeks approx.
- Also if you have selected some scope which would include extra security check, then that would cost you in your pocket.
Let’s select ‘External’, as my account is not a registered G Suite account. Click on Create. Now you can see a form, which contains the below configuration options:
OAuth Consent Screen
- App Information
- Here you have two mandatory fields,
- App Name: this name will come into picture when a user logs in using the OAuth Service. We will see this name in action soon.
- User support email: Id where users can contact you for any information related to their consent.
- Apart from this, you can also specify a logo (optional).
- Here you have two mandatory fields,
- App Domain and Authorize domain
- This are optional fields
- In these sections, you can give links of your website privacy policies, terms and conditions so that when user is login using the OAuth service, this links will be provided in the screen for their go-through.
- Apart, you can also attach your registered domain details.
- Developer contact information
- This email id is used by google to inform you about any changes related to your service.
- It is a mandatory field.
- Click ‘Save and Continue’.
- This decides the type of user data which can be shared with your application by Google.
- Divided into 3 types:
- The user data which are public
- Eg: email id or any profile data which you have set as public
- The user data which are private
- Eg: your phone number
- The user data which are very sensitive data
- Eg: your upi details which you use to transact in play store
- We will be using Non-Sensitive data for our article. To do so, click on ‘Add/Remove scope’ button and click on all the three checkboxes (figure 1 below)
- Note: If a data is of type sensitive or restrictive, a lock will be displayed in ‘Lock type’ column for the particular data row (figure 2 below). In our case, we are not configuration any sensitive or restrictive data with our project, hence we can’t see any lock symbol.
- Scroll down and click on update button.
- Click on ‘Save and Continue’
Here you can give more details about your app which would help google for verification. I left the fields blank and clicked on ‘Save and Continue’
You can anytime go and edit the consent as per your application need. Once the OAuth Consent is ready, let’s now create the credentials.
Step 5: Create client credentials
This is the last step to configure the OAuth Service which will be used by your application J (finally !!)
- Click on ‘Credentials’ menu
- Click on ‘Create Credentials’
- Select ‘OAuth client ID’
- A form gets loaded which has certain fields which needs to be configured. They are,
- Application Type : We will be selecting ‘Web Application’
- Give a meaningful name to the web client. I gave something similar to the app name which was given in consent (step 4), ie.‘DotNetTricks Authentication Client’
- The URI where your application is hosted.
- But as our application is still running in local, we will give our localhost URI.
- Right click on the project in visual studio
- Select properties
- Select debug option
- Scroll down. You will see APP URL with Enable SSL checkbox.
- Check the Enable SSL option if not checked. It will generate an https URL.
- Copy and paste the URL in the APP URL textbox and save the setting.
- We will see this URI in action once we bind the OAuth Service with our application.
- Authorized Redirect URIs
- This is the URI where the user will be redirected after being authenticated by google.
- Click on ‘Add URI’ and paste the same APP URL suffixed with ‘/signin-google.
- Eg: https://localhost/ signin-google
- We will see this URI in action once we bind the OAuth Service with our application.
- Click on save.
- At this stage, if you see the credentials page, an entry is created under ‘OAuth 2.0 Client IDs’ table.
Binding OAuth Service In Application
Step 1: Install NuGet Package
- Right click on the project and select Manage Nuget Packages.
- Search and install Microsoft.AspNetCore.Authentication.Google
- Once installed, the package should be available under dependencies.
Step 2: Configure ClientId and SecretKey in StartUp.cs
- We need to configure the IServiceCollection to support Google Authentication.
- For this, open StartUp.cs file and add the below code in ConfigureServices method
- AddAuthentication() tells the IServiceCollection that we are adding an Authentication mode
- AddGoogle() tells the type of mode. In our case, its google authentication
- GetSection("Authentication:Google") fetches the credentials required for Authentication using Google OAuth
- ClientId and options.ClientSecret are the parameters which will be used by Google OAuth to verify the user
Note: I have used ‘Secret Manager’ provided by .Net Core to store the sensitive data like ClientId and ClientSecret.
Step 3: Create and bind properties in model
In my Login.cshtml.cs file, I already have properties to hold data for login, like username, password. We need to create properties which will be responsible to hold data when user opts for OAuth service.
We need to declare two properties,
This property will be responsible to hold the URL which the user is trying to access. Once the user is successfully authenticated by the OAuth service, in our case, by Google, the user can be redirected to the same URL.
Now with in the orange block in above image, we need to show a button or image to let the users login using OAuth service. In our example, we are using Google OAuth service, but there can be chances where you may use multiple services like Facebook, Twitter or Microsoft accounts.
This property will be responsible to hold the list of such services which we declared in Step2. This property will be a IList of AuthenticationSchema.
Now we need to bind the properties to show the OAuth services with in the orange block (image above).
Below is the screen print of the method we need to add in Login.cshtml.cs file. This method will be called when user loads the Login page.
- returnUrl is the URL from where user came to Login page. Once the user authentication is successful, we will redirect the user to the same URL.
- GetExternalAuthenticationSchemesAsync() gives us the list of OAuth services we have bind to the configuration service in StartUp.cs
Step 4: The html code to show the buttons/images for the external login(s)
Because we have declared the ExternalLogin property as a IList in Step 3, so there can be two possibilities, either the list is empty (we didn’t bind any OAuth service) or the list has data. Our code should be sufficient enough to handle either of the cases.
- Empty list – we will add a count check. If the count is 0, then we will show the same message you can see in the orange block of Figure 3.
- List is not empty – In this case, we need to create write down the logic to iterate through the list.
Let’ see how we can satisfy both our above conditions.
- The action method to be called when user clicks on any of the external login buttons. We will be creating this method as we proceed further.
- The ReturnURL will be passed as parameter to the ExternalLogin method.
- As we are seding the parameter, we would need a Post method
- The ExternalLogins property in the model, which we are using to iterate
- It’s always preferred to add an unique Id to your elements
- @provider.name contains the name of the OAuth service you are binding
- @provider.DisplayName contains the name of the OAuth service which you want to show to the user.
DOM STRUCTURE OF THE FORM
Note: If you have a closer look, you would see action and parameter got combined to form a single URL in the DOM.
Step 5: Create the submit action method when clicked on the external login
This action will require two types of parameter,
- Provider details
- Return URL
- This parameter will be derived from the ‘name’ attribute we have declared in the HTML (figure 4, point 6).
- It is case-sensitive and hence the parameter should match exactly what’s been declared in HTML.
- If it doesn’t match, .Net Core will not be able to bind it, resulting in sending an empty string.
- This parameter will be derived from the ‘asp-route-returnUrl’ attribute we have declared in the HTML (figure 4, point 2).
- After user authentication is successful, we need to redirect the user to our application. In our case, it will be the Home page of the application.
- This method configures the provider and the redirectURL
- ChallengeResult is used to perform authentication whereabouts for external providers. You can know more about ChallengeResults from MSDN documents.
After Step 5, once u re-run your application and Click on the Google button, you will be redirected to the Google Authentication page (image below).
Do you remember the name with the blue box in above image somewhere? Yes, you are right !! J The ‘app name’ we have given to our project while creating the consent screen.
Every service comes with Pros and Cons. Let us see one by one.
- OAuth 2.0 is a good and useful approach when you wish to refrain from User Authentication and managing their data.
- Basically your application is carefree to protect the user details. The OAuth 2.0 Service will be reliable to do all the ground work to make sure user info is safe.
- OAuth 2.0 plug and play approach is quite feasible. It only gives out the data which has been requested by you, making sure the mode of transfer is also safe.
- Your application will get access to user data without actually bothering about username/password. OAuth 2.0 uses token based functionality.
- Nevertheless, implementation is easy.
- If the OAuth service database is hacked where its maintaining its data, then all the application using the service will be at stake.