Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Introduction to OAuth in ASP.NET MVC

14 Apr 2013 1  
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.

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.

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.

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.

Select the Internet Application as the project template

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.

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.

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.

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

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.

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.

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. 


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.

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.

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.

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

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

 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:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here