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

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

    Posted by Chris Bordeman on 02/20/2015 05:48am

    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.

    Reply
  • 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

  • Lenovo recommends Windows 8 Pro. "I dropped my laptop getting out of the taxi." This probably sounds familiar to most IT professionals. If your employees are traveling, you know their devices are in for a rough go. Whether it's a trip to the conference room or a convention out of town, any time equipment leaves a user's desk it is at risk of being put into harm's way. Stay connected at all times, whether at the office or on the go, with agile, durable, and flexible devices like the Lenovo® …

  • When individual departments procure cloud service for their own use, they usually don't consider the hazardous organization-wide implications. Read this paper to learn best practices for setting up an internal, IT-based cloud brokerage function that service the entire organization. Find out how this approach enables you to retain top-down visibility and control of network security and manage the impact of cloud traffic on your WAN.

Most Popular Programming Stories

More for Developers

RSS Feeds

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