Welcome to the CodeSmith Community!

OAuth 2.0 for MVC, Two Legged Implementation

CodeSmith Community

A description has not yet been added to this group.

OAuth 2.0 for MVC, Two Legged Implementation

  • Comments 14

OAuth 1.0 was one complicated beast. The OAuth 2.0 spec greatly simplified things, but that also had the wonderful side effect of rending all of our old OAuth 1.0 code obsolete. They say that "the only thing a pioneer gets is an arrow in the back," I disagree, I say "the thing that only a pioneer gets to have is an adventure."

For example, I got to help write this wonderful, cutting edge, open source, OAuth 2.0 implementation for MVC!

OAuth 2.0 Overview

OAuth is all about tokens. You start by getting a Request Token from the server, and then using that to secure your login information. When you have successfully logged in you will be given a role/permission specific Access Token, you will then submit this token with all of your future requests. You will also get a Refresh Token with your Access Token. Once your Access Token has expired, you can then submit your Refresh Token to get a new pair of Access and Request Tokens.

Two Legged vs Three Legged

A two legged implementation is rather straight forward, you log into the server you are trying to access. A three legged implementation allows you to gain access to a resource by authentication with a third party server.  For the time being this project only supports two legged authentication.

Implementation

You must implement four classes to use this library:

  1. OAuthIdentityBase
  2. OAuthPrincipalBase
  3. OAuthProviderBase
  4. OAuthServiceBase

The first three are very small classes, requiring only a few short lines of code. The Service is the work horse where most of your code will go, but even then it only requires the implementation of four methods.

public abstract class OAuthServiceBase : ProviderBase, IOAuthService
{
    public static IOAuthService Instance { get; set; }
    public abstract OAuthResponse RequestToken();
    public abstract OAuthResponse AccessToken(string requestToken, string grantType, string userName, string password, bool persistent);
    public abstract OAuthResponse RefreshToken(string refreshToken);
    public abstract bool UnauthorizeToken(string token);
}

Then of course you will need to update your Web.config:

<configuration>
  <configSections>
    <section name="oauth" type="OAuth2.Mvc.Configuration.OAuthSection, OAuth2.Mvc, Version=1.0.0.0, Culture=neutral"/>
  </configSections>
  <oauth defaultProvider="DemoProvider" defaultService="DemoService">
    <providers>
      <add name="DemoProvider" type="OAuth2.Demo.OAuth.DemoProvider, OAuth2.Demo" />
    </providers>
    <services>
      <add name="DemoService" type="OAuth2.Demo.OAuth.DemoService, OAuth2.Demo" />
    </services>
  </oauth>
  <system.web>
    <httpModules>
      <add name="OAuthAuthentication" type="OAuth2.Mvc.Module.OAuthAuthenticationModule, OAuth2.Mvc, Version=1.0.0.0, Culture=neutral"/>
    </httpModules>
  </system.web>
</configuration>

Securing Your Pages

That's the easy part, just add the MVC Authorize Attribute to any actions or controllers that you want to secure.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [Authorize]
    public ActionResult Secure()
    {
        return View();
    }
}

The Demo Project in Action

1.  2. 

3.  4. 

The Demo API in Action

  • /oauth/requesttoken
    • Request Params
      • None
    • Result
      • RequestToken = a028f1895cc548af9de744f63d283f6e
      • Expires = 300
      • Success = true
  • /oauth/accesstoken
    • Request Params
      • oauth_token = a028f1895cc548af9de744f63d283f6e
      • username = tom
      • password = c4e5995d4cb8b26970336b956054ac1be9cc50b3
    • Result
      • AccessToken = 3b23ee5f128a45c88e657ecc74c41bbc
      • Expires = 300
      • RefreshToken = 85126a53bca940f1ae7c9d797f63a274
      • Success = true
  • /oauth/refreshtoken
    • Request Params
      • refreshToken = 85126a53bca940f1ae7c9d797f63a274
    • Result
      • AccessToken = 8cfc317af6ed45b2b065a8fa5da3ba81
      • Expires = 300
      • RefreshToken = d0b4a8898d974e939ca83b55cfeabcac
      • Success = true
  • /oauth/unauthorize
    • Request Params
      • oauth_token = 8cfc317af6ed45b2b065a8fa5da3ba81
    • Result
      • Success = true

Additional Resources

Happy authenticating!
~ Tom

Shout it

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • * Please enter your name
  • * Please enter a comment
  • Post
  • Thank you for submitting this cool story - Trackback from DotNetShoutout

  • You've been kicked (a good thing) - Trackback from DotNetKicks.com

  • What license is this code under?

  • Hello,

    All of our code that we release on Google code or our blogs is open sourced under no specific license. But in many cases where we had to pick one (for Google code it is listed as "GNU Lesser GPL"). Please use the code as you wish as we believe that this information should be free for everyone for any use.

    Thanks

    -Blake Niemyjski

  • Where is the current source code for this?  The links in the article go to a .zip file.  I can't find it under Subversion anywhere.

    Thanks!

  • Hello,

    The source code can be found inside of the Zip under the Source folder. This code is not currently in our public repository as it was a sample application. I'll see if we can put this up on a branch someplace.

    Thanks

    -Blake Niemyjski

  • Hi there. Excellent blog post. Which version OAuth 2.0 draft this version supports ?

    Do you plan to implement 3 legged implementation ?

  • Just GPL!!!

  • @Interested, we had to pick a license for google code.. This code is completely license free.

  • how can i get the password param value that needed when request the oauth/accesstoken ?

    Thanks.

  • sorry just ignore my question before. i've already find the answer. password value is combination of oauth_token and password (encrypt with javascript sha1)

    Thanks.

  • Hi,

    Great project! I'm trying to understand the implementation - I'm using MVC4 Web Api. I'm trying to mimic the code in the OAuth Controller in the sample project, but when I make this call:

    var requestToken = OAuthServiceBase.Instance.RequestToken();

    I get a NULL reference exception at runtime. This is working in the sample project, and I can't figure out what I'm doing differently. I've imported the OAuth2.MVC namespace and everything builds fine. Any tips?

    thanks!

  • Hello,

    I haven't taken a look at this with WebAPI but a few things change under the hood even when compared to MVC 4. I'd recommend stepping through the debugger and compare the exact differences between the two. Please let me know what you find.

    We recently used this for http://www.dotnetopenauth.net/ for one of our projects. It's easy to use and frequently updated.

  • For everyone who is trying to implement this tutorial in an mvc4 web api project and getting NULL reference exception at runtime each time you call OAuthServiceBase.Instance. The solution is as simple as adding a line in the a web.config file..

    You should add this

    <system.webServer>

       <modules>

         <add name="OAuthAuthentication" type="OAuth2.Mvc.Module.OAuthAuthenticationModule, OAuth2.Mvc"/>

       </modules>

      ...........

    </system.webServer>

    Thank you Tom

Page 1 of 1 (14 items)
Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • * Please enter your name
  • * Please enter a comment
  • Post