Implementing OAuth Features in ASP.Net MVC 4


Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame

Asp.Net 4.5 comes with the support for Open Standards for Authorization, which is known in short as OAuth. In this article I will be explaining about the OAuth mechanism and working with implementing OAuth in an Asp.Net MVC 4 application.

Explanation of OAuth

OAuth is an authentication protocol that allows the client application’s user to authenticate through an OAuth service provider along with appropriate authorization.

Basically the OAuth mechanism involves three parties and they are the user, client application and the OAuth services provider. The workflow mentioned below will explain things easily.

  • 1. An OAuth client makes a request to the OAuth service provider using a request token (plain and secret).
  • 2. The service provider then prompts the user to provide the authentication credentials.
  • 3. Once the authentication is successful the service provider generates an Access Token (this access token is defined with specific authorization) and provided to the client.
  • 4. The client can then make use of the access token to query for the service providers resources, which it is entitled to.
  • 5. The access token expires after a time span.

Advantage of using OAuth in Asp.Net MVC

As I said that Asp.Net MVC 4 is provided with the OAuth feature, it is also important for me to explain the advantage of enabling it. Following are the advantages of enabling OAuth in an Asp.Net MVC 4 application.

  • 1. No need to implement your application level authentication and can be delegated to the OAuth service provider.
  • 2. Your application users can use their pre-existing OAuth service provider (Facebook, Twitter, etc.) credentials instead of creating a separate one for your application.
  • 3. Your Asp.Net MVC application can access the resources of the OAuth service providers (Facebook, Twitter, etc.) using the access token issued to it at any point of time before expiry.
  • 4. In case if you are striving to bring a single sign on for all the applications in your enterprise architecture.

Enabling OAuth in Asp.Net MVC 4 Application

The OAuth clients that come out of the box with Asp.Net MVC 4 are Facebook, Google, Microsoft, Linked in, Twitter, etc.

Getting the RequestToken and RequestTokenSecret

A few OAuth service providers like Facebook, Twitter, etc. demand the client applications to pass a RequestToken and RequestTokenSecret in order to identify who is making the AccessToken request. This can be obtained from the service providers as mentioned in the below link.


OAuth Registration

In order to enable an OAuth service provider in an Asp.Net MVC application the respective client has to be registered using the OAuthWebSecurity class. In the Asp.Net MVC project under the App_Start folder there is a file named AuthConfig.cs. Following is the OAuth client registration code for enabling the OAuth service providers Microsoft, Twitter, Facebook, Yahoo and Google.

namespace MvcOAuthDemo
    public static class AuthConfig
        public static void RegisterAuth()
            //The clients which are registered here will get enabled for OAuth in the application
            //Dummy tokens are passed
                clientSecret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
                consumerSecret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            //These service providers does not require any token

Once the application is run, the login screen will display the buttons for each registered OAuth client clicking on which the user will be taken to that service provider site itself. Fig 1.0 shows the login screen displaying the buttons for all the registered clients through the above mentioned code.

The login screen displaying the buttons for all the registered clients
Fig 1.0: The login screen displaying the buttons for all the registered clients

Creating Custom OAuth Clients

As we discussed in the previous section that Asp.Net MVC 4 comes with a set of built-in OAuth clients, what do you do in case you want to register to a different OAuth Service Provider, which is not a part of the predefined ones.  Asp.Net MVC allows you to create custom OAuth clients and register them using the RegisterClient method. There is an assembly named DotNetOpenAuth.dll included in your Asp.Net MVC application and you can use the classes inside it to create custom clients as well as custom service providers. Following is a sample Custom OAuth client class inheriting for the class OAuthClient.

namespace MvcOAuthDemo
    public class MyOAuthClient : OAuthClient
        public static readonly ServiceProviderDescription MyServiceDescription = new ServiceProviderDescription
            RequestTokenEndpoint = new MessageReceivingEndpoint("https:sampleapiendpoint", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
            UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://sampleapiauthorizationendpoint", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
            AccessTokenEndpoint = new MessageReceivingEndpoint("https://sampleapiaccesstokenendpoint", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest),
            TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new PlaintextSigningBindingElement() }
        public MyOAuthClient(string consumerKey, string consumerSecret) :
            this(consumerKey, consumerSecret, new AuthenticationOnlyCookieOAuthTokenManager())
        public MyOAuthClient(string consumerKey, string consumerSecret, IOAuthTokenManager tokenManager) :
            base("dropbox", MyServiceDescription, new SimpleConsumerTokenManager(consumerKey, consumerSecret, tokenManager))
        protected override DotNetOpenAuth.AspNet.AuthenticationResult VerifyAuthenticationCore(DotNetOpenAuth.OAuth.Messages.AuthorizedTokenResponse response)
            //Perform the verification process
            return new AuthenticationResult(true);

The same class can be registered using the below code.

namespace MvcOAuthDemo
    public static class AuthConfig
        public static void RegisterAuth()
            OAuthWebSecurity.RegisterClient(new MyOAuthClient("XXXXXXXXXXXXX", "XXXXXXXXXXX"), "MyCustomClient", null);

I hope this article gave you a good insight into implementing OAuth in an Asp.Net MVC 4 application. Happy reading!

Related Articles


  • Same, but for MOBILE and w/ my server auth

    Posted by Chris Bordeman on 02/20/2015 01:48pm

    I've been searching and reading for weeks now, and I just can't figure out how this scenario is supposed to work! I have a mobile app (WinRT) and I need to allow my users to log into my NON-WEB mobile app using Oauth (MS perhaps using Live for now, Google and Facebook later). I interact _directly_ with an oauth server via the bearer tokens route, but then how on earth do I let my server know who is logged in (on every request), and how can it know that that identity true? I think I read something a while back about sending some kind of token as an HTTP header on each request, decrypting the token on the server and somehow getting a username that way, but that sounds insecure and that's a vague memory. I tried just doing the standard MVC project (like you demonstrate here) and enabling Microsoft w/ my client id and secret, but that appears to not use bearer tokens and is highly web-centric, involving displaying an MS web page on the client and a callback url. That is clearly not the right route. Please help me, I'm SO frustrated! Remember: 1) The client is MOBILE, not web based. 2) My server's REST endpoints need secure authentication. 3) Once the user gets authenticated, I'd like to automatically create a user on my server so I can attach my own metadata onto him/her.

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date