Implementing OAuth Features in ASP.Net MVC 4

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.

http://go.microsoft.com/fwlink/?LinkID=252166

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
            OAuthWebSecurity.RegisterMicrosoftClient(
                clientId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                clientSecret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
 
            OAuthWebSecurity.RegisterTwitterClient(
                consumerKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                consumerSecret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
 
            OAuthWebSecurity.RegisterFacebookClient(
                appId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                appSecret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
 
            //These service providers does not require any token
            OAuthWebSecurity.RegisterYahooClient();
            OAuthWebSecurity.RegisterGoogleClient();
        }
    }
}

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

Comments

  • Its always necessary keep your teeth clean

    Posted by tamrinnalon on 04/28/2013 02:18am

    A tooth (plural teeth) is a mignonne, calcified, whitish form initiate in the jaws (or mouths) of many vertebrates and occupied to sever down food. Some animals, explicitly carnivores, also use teeth for the purpose hunting or for defensive purposes. The roots of teeth are covered sooner than gums. Teeth are not made of bone, but rather of multiple tissues of varying density and hardness. The general systematize of teeth is similar across the vertebrates, although there is considerable variation in their form and position. The teeth of mammals drink serious roots, and this figure is also create in some fish, and in crocodilians. In most teleost fish, manner, the teeth are fastened to the outer outside of the bone, while in lizards they are fixed devoted to to the inner surface of the jaw by harmonious side. In cartilaginous fish, such as sharks, the teeth are seconded beside cold ligaments to the hoops of cartilage that type the jaw.

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

Top White Papers and Webcasts

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

Most Popular Programming Stories

More for Developers

RSS Feeds