OpenID Authentication in ASP.NET MVC
You’ve probably see on the wild on websites such as StackOverflow, but if you don’t know what it is, it is a single sign-on mechanism that allows user of your website to use his existing profile on an provider, such as Gmail, Yahoo, Wordpress, etc. so by providing this service on your website, you allow the user to login without gooing through all the hoops of creating and validating an account which is usable on a single website only.
The way it functions is that you are forwarded to the provider of your choice, authenticate with your existing account there, and from there you’ll be forwarded back to the website you originated the request from. An authentication token is also sent from the provider which uniquely identifies that user. Let’s see how we can add support to our ToBeSeen website.
To start, go grab latest version of -selector library which is a JS library that contains the look and feel similar to StackOverflow. Open the “LogOn.cshtml” file in you asp.net mvc project and change it to this:
1 | @using (Html.BeginForm("Authenticate", "Account", FormMethod.Post, new { id = "_form" })) |
Also you need to include the .css and .js files of “-selector” on your master page and then call the init function using jQuery:
1 | <head> |
Now firing up your website and switching to /Account/LogOn
you can see the nice user interface that allows you to login to a bunch of providers.
Now back to coding parts. To speak to providers, the best bet is to use DotNetOpenAuth library. Grab it and add the assembly named DotNetOpenAuth to your project. We need to create an action on AccountController named “Authenticate”, so create that as well. The authentication is a two part mechanism, first you create a request and call the provider and then when provider authenticates (or fails to do so) he will call you back on the same action method, and you can get the response and check if the status was success or not. It all boils down to this function:
1 | public virtual ActionResult Authenticate(string _provider) |
The providers can do more than just authentication. They can provide you profile information given they support sending the profile information you request. For this example, let’s just grab the user’s email address which we may later use to display on the master page, but mind you that specs. contain much more than just email address information.
Some prodivers do not disclose some part of their uses’s profile data.
To request profile information, which are called Claims, you need to add the information you need to the initial request.
1 | var request = .CreateRequest(_provider); |
and when processing the response, you can easily read the claims information:
1 | var fetch = response.GetExtension<ClaimsResponse>(); |
Hope this clarifies how easy it is to plug into your existing web applications.