Introduction to OAuth in ASP.NET MVC

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 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.

License

Share

About the Author

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

This is a good tutorial, but it will allow anyone with a facebook account to register as a new user in the MVC app. How would you restrict which users can create an account, for example by the domain name in their email address?

ASP.NET MVC 3 uses Membership. Local works, but in server not works. The error:

Could not load file or assembly 'System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

i am not familiar with oAuth and never work with oAuth. here u said oAuth is mechanism by which people can login to my site using facebook or google etc credential. am i right?

so tell me what is OpenID mechanism. i heard that OpenID also did the same thing. if u know then please discuss what is the difference between oAuth & OpenID. also tell me when one should go for oAuth when one should go for OpenID. i will be glad if u share the knowledge. thanks

OpenId only provides authentication while oAuth provides authorization so you can access other functions/api. For example using facebook oAuth can give you access to the user's profile information etc.