Click here to Skip to main content
15,881,173 members
Articles / Web Development / ASP.NET

Introduction to OAuth in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.86/5 (33 votes)
14 Apr 2013CPOL9 min read 179.5K   74   19
OAuth authorization is an open standard for authorization using third party applications

Introduction

OAuth or Open standard for Auhtorization has become a standard which is used nowdays in most of the applications. Here we will discuss what is OAuth and how we can implement it using ASP.NET MVC.

Background

What is OAuth?

Before discussing anything else let us first understand what is OAuth. Suppose user has some resources stored on the server and there is a third party application which wants’ to access these user resources. This is a scenario which we might have encountered many times in our lives. Let’s say we have got some really cool pictures in Flickr that we want to share with our Facebook friends. We go to Facebook which redirects us to Flickr where we provide our authentication details and we are done. The great thing in all this is that we never need to share our Flickr details with Facebook.This is an example of OAuth authorization.

Image 1

In the step 1 above the Client logins to his Facebook account by providing a userid and a password. If user wants to share his Flickr images with his Facebook account he selects the appropriate option in Facebook. Facebook redirects him to Flickr where he provides his credentials (step 2 above). Once the user is logged in to his Flickr account he can chose to share his Flickr images with his Facebook account.

So unlike normal authentication process as in a typical web application there is two step authentication involved here. So we can formally define OAuth as: OAuth is a protocol that allows end users to give access to third party applications to access their resources stored on a server.

We can retrieve user account information from Facebook so that we can use it in our application.We can use this information for different purposes like creating customized experience for every user depending on his personal preferences .OAuth 2.0 is the latest version of OAuth and it is not backward compatible with OAuth 1.0. Different providers use different versions of OAuth.For example Facebook and Twitter uses OAuth version 2.0 . 

Advantages of using OAuth

Giving the third party application access to the users resources on a website has an advantage for the end user since he can easily share his already existing resources with another application instead of duplicating the resources in a new website.

Today most of the internet users have multiple accounts with different sites like Google,Microsoft, Facebook etc. .Imagine the situation when the poor user is asked to register again on another website. I am sure you might have had this feeling since registering with a new site consumes time.

Using OAuth the application can allow the user to login using his existing credentials(on another website).So user does not have to create and remember another credentials on a new web site . It has an advantage for you as a developer since you can delegate the authorization to another trusted website. These trusted websites that authorize users on other applications behalf are called Identity providers.

Using Open Authentication the user can give limited access to the third party applications to their resources stored on some other website. And the user never need to share his credentials with these third party
applications.Instead of userid and password  the applications use the access token to fetch the users data. 

How OAuth works 

In a normal scenario user has some resources stored on the server that he can access using his userid and password. User provides the credentials namely userid and password and is granted access to his resources. This is mandatory so that the user’s resources ,which could be images or any other documents are safe.

Here the main entities involved in this transaction are

  • Client
  • Server 
  • User accessing his resources stored on the server
  • Resources of the user stored on the server that he is trying to access. 

This can be depicted by the following flowchart.

Image 2

In the above flowchart user is allowed access to his resources using authorization which is a step that depends upon authentication.But the main point here is that all of the above process is mostly performed by a single application.

As the userid and password validation occurs in the same application the user is accessing, so the password of the user is stored in the database of the application most likely in an encrypted format. Since the password is encrypted user can be sure that his credentials are known only to him(ignoring the case that his account is hacked J) so it is very less likely that his credentials are misused.

The above scenario represents typical user authentication process performed by an application. In the case of applications using OAuth authentication the process works a bit differently. Instead of the user directly signing in to an application the user is rather redirected to another web site where he needs to enter his credentials.

Following steps are common no matter which provider we are using.

  • Register our application with the provider and receive a key and a secret
  • Once the user shows his intention to authenticate using the provider our application sends a request to the provider for a request token(which is just another set of credentials)
  • In the final step our application asks the provider for the access token. Once our application receives the access token it has access to the users data.

Following diagram illustrates what we have discussed above.

Image 3

In the last step the authentication provider sends back an access token to the application.It is the access token using which our application can access users data.

Using the code

Now let us build a simple MVC application that allows the user to login using his facebook credentials. We will be implementing the application that uses Facebook as an identity provider but since the basic steps for all the providers are the same we can use any other provider as well such as Twitter with very minor changes in our application.

The above steps will be clear once we implement a simple application using OAuth.

Visual studio 2012 provides OAuth support out of the box for different types of ASP.NET applications such as Web forms and MVC.

Following are the steps to create an MVC application that uses OAuth to authenticate the user using his Facebook account.

In the new project dialog select the ASP.NET MVC 4 application in the templates list.

Image 4

Select the Internet Application as the project template

Image 5

Once you click on the create button a new project should be created and you could find an AuthConfig.cs file in the App_Start folder which contains some commented code.

Image 6

If we run the application now we will see that Under use another service to login no providers are displayed.This is because we have not yet enabled external providers yet. We will see how to do that next.

Image 7

Registering website with facebook

Since we will be using Facebook as an identity provider we need to register our application with Facebook before we can do anything else. When we register our site with Facebook we receive id and a secret. To register our application with Facebook we browse to the url https://developers.facebook.com/apps and login.

Once we login we click on Create New App in the upper right side.

Image 8

In the Create New App dialog enter the name of the Application you want to create.Here we enter OAuthApp and Click on continue.

Image 9

In the next window enter the application URL. You can give the URL as http://localhost/ if you are using your development URL. Also you will be able to see the AppId and App Secret(not visible below).Note the AppId and AppSecret we will need it in our application.

Image 10

Click on save changes.

Go back to the visual studio and open AuthConfig.cs in the App_Start Folder. Locate the below line in AuthConfig.cs.

C#
OAuthWebSecurity.RegisterFacebookClient( appId: "",appSecret: "");  

Pass the appID and appSecret values to the RegisterFacebookClient method as noted above.

Now when we run the application and click on the login button we will see the below screen.When we put the appID and AppSecret in the AuthConfig.cs ,the application recognizes that we want to enable Facebook authentication and places a button for the same. 

Image 11


This is all we need to do for authenticating the user using facebook. Now we will go ahead and click on the Facebook button.We will be redirected to the Facebook login page.

Image 12

Once we login we will get an alert whether we want to login to Facebook through our Application . We click on Go to App button. This will redirect us back to our application.

Image 13

We are redirected back to our application where we are asked to associate our Facebook account with a username in our application.Enter the username you want to associate with your Facebook account.

Image 14

Once we click on register we are able to see our user name ,so we are logged-in now using our Facebook credentials.

Image 15

Now that our Facebook authentication is working fine let’s see how we can retrieve some of the facebook details in our application. Open the AccountController.cs file in the controllers directory and go to the ExternalLoginCallback method. ExternalLogin method is called when we login to the application using external provider. ExternalLoginCallback is a callback method that is called once the provider authenticates.

The first line in the ExternalLoginCallback method is

C#
 AuthenticationResult AuthenticationResult  result
= OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl =
returnUrl })); 

The result variable contains a dictionary called ExtraData which contains the following keys.

  • id
  • name
  • link
  • gender
  • accesstoken

Note that we need accesstoken to access the user account.So if we want any further details about the user we will need to use the accesstoken.

These values are Facebook specific and a different provider may return slightly different values.

Retrieving more information from the facebook account

Now if we want to retrieve extra data apart from the data retrieved above we can use the facebook client. Since it is available as a NuGet package we can install it as:

PM>Install-Package Facebook

Once it is installed we can very easily retrieve the detailed information about the user using the below code:

C#
var client = new FacebookClient(HttpContext.Session["accesstoken"].ToString());
dynamic fbresult = client.Get("me");
var data = fbresult["data"].ToString();
The HttpContext.Session["accesstoken"] is the access token that is assigned to the user.Using Facebook client we are able to retrieve detailed information about the user that we can use in our application. We are able to retrieve the following details about the user.

  • id
  • name
  • first_name 
  • last_name
  • link
  • username
  • gender
  • timezone
  • locale
  • verified
  • updated_time

Points of Interest

OAuth allows client applications to access user resource in another application.

Visual Studio 2012 ships with DotNetOpenAuth for OAuth authorization which is available in ASP.NET applications

DotNetOpenAuth is a open source library to add OpenID and OAuth capabilities to the Microsoft .NET Framework.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I have a keen interest in technology and software development.I have worked in C#,ASP.NET WebForms,MVC,HTML5 and SQL Server.I try to keep myself updated and learn and implement new technologies.
Please vote if you like my article ,also I would appreciate your suggestions.For more please visit Code Compiled

Comments and Discussions

 
QuestionResourceful article! Pin
Asif Iftekhar25-Jul-19 18:50
professionalAsif Iftekhar25-Jul-19 18:50 
QuestionHow do you restrict which users can register Pin
prankster62427-Oct-15 5:28
prankster62427-Oct-15 5:28 
GeneralMy vote of 5 Pin
D V L20-Aug-15 0:30
professionalD V L20-Aug-15 0:30 
QuestionNice Article Pin
Aniket Babar26-Feb-15 20:48
Aniket Babar26-Feb-15 20:48 
GeneralGood Article Pin
Malhotra Sameer29-Jan-15 8:37
professionalMalhotra Sameer29-Jan-15 8:37 
Nice & Easy to follow
GeneralRe: Good Article Pin
ashish__shukla1-Feb-15 2:02
ashish__shukla1-Feb-15 2:02 
Generalneed a help Pin
Member 112820772-Dec-14 20:35
Member 112820772-Dec-14 20:35 
Questiongood Pin
ashishkumar00816-Sep-14 0:33
ashishkumar00816-Sep-14 0:33 
GeneralMy vote of 4 Pin
Akiii_Lethal12-May-14 19:52
Akiii_Lethal12-May-14 19:52 
GeneralHow to implement OAuth in ASP.NET MVC 3? Pin
Member 1058805221-Feb-14 2:08
Member 1058805221-Feb-14 2:08 
GeneralMessage Closed Pin
8-Jul-18 12:33
Member 139032008-Jul-18 12:33 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun2-Jan-14 20:07
Humayun Kabir Mamun2-Jan-14 20:07 
GeneralMy vote of 5 Pin
sfspacov11-Aug-13 13:17
sfspacov11-Aug-13 13:17 
QuestionHow can we get access token ? Pin
Ravi Kadam22-Jul-13 0:53
professionalRavi Kadam22-Jul-13 0:53 
QuestionNeed some info Pin
Tridip Bhattacharjee17-Apr-13 3:58
professionalTridip Bhattacharjee17-Apr-13 3:58 
AnswerRe: Need some info Pin
Ricardo Lynch17-Apr-13 5:19
Ricardo Lynch17-Apr-13 5:19 
GeneralRe: Need some info Pin
Tridip Bhattacharjee17-Apr-13 8:47
professionalTridip Bhattacharjee17-Apr-13 8:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.