A JQuery plugin for OpenID selector & DotNetOpenAuth integration in MVC

JQuery OpenId selector can be downloaded here http://code.google.com/p/openid-selector/

DotNetOpenAuth can be downloaded here http://www.dotnetopenauth.net/ or install using Nuget  http://nuget.org/packages/DotNetOpenAuth/3.4.7.11121

PM> Install-Package DotNetOpenAuth -Version 3.4.7.11121

Here is what the JQuery openId selector looks, and there are two files you can configure: openId-en.js & openid-jquery.js

OpenID selector

To modify the UI, in openid-en.js, change the variable of “providers_large” and “providers_small” to make your own look and feel.

To modify the settings of this plugin, such as image path, cookie name, etc. Open openid-jquery.js, it is in the openid definition section.

openid = {
	version : '1.3', // version constant
	demo : false,
	demo_text : null,
	cookie_expires : 6 * 30, // 6 months.
	cookie_name : 'openid_provider',
	cookie_path : '/',

	img_path : '../openid/images/',
	locale : null, // is set in openid-.js
	sprite : null, // usually equals to locale, is set in
	// openid-.js
	signin_text : null, // text on submit button on the form
	all_small : false, // output large providers w/ small icons
	no_sprite : false, // don't use sprite image
	image_title : '{provider}', // for image title

	input_id : null,
	provider_url : null,
	provider_id : null,

In the MVC View, you need to have


    $(document).ready(function () {
        openid.init('openid_identifier');
    });

    function facebook_click() {
        alert("wwaaa");
    }


@using (Html.BeginForm("Login", "Account", new {ReturnUrl = Request.QueryString["ReturnUrl"] },FormMethod.Post, new { id = "openid_form" }))
{     <input type="hidden" name="action" value="verify" />
	<fieldset>
		<legend>Sign-in or Create New Account</legend>
		<div id="openid_choice">
			<p>Please click your account provider:</p>
			<div id="openid_btns"></div>
		</div>
		<div id="openid_input_area">
			<input id="openid_identifier" name="openid_identifier" type="text" value="http://" />
			<input id="openid_submit" type="submit" value="Sign-In"/>
		</div>
		<noscript>
			<p>OpenID is service that allows you to log-on to many different websites using a single indentity.
			Find out <a href="http://openid.net/what/">more about OpenID</a> and <a href="http://openid.net/get/">how to get an OpenID enabled account</a>.</p>
		</noscript>
	</fieldset>
}

In the controller, we need to have Login & Register action methods using DotNetOpenAuth to implement the authentication process.

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get), ValidateInput(false)]
        public ActionResult Login(string openid_identifier, string returnUrl)
        {
            var response = _openId.GetResponse();
            if (response == null)
            {
                if (string.IsNullOrEmpty(openid_identifier))
                    return View();
                return SendRequestToOpenIdProvider(openid_identifier);
            }
            else 
            {
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        string identifier = response.ClaimedIdentifier;

                        var user = _userRepo.GetUser(identifier);
                        if (user != null)
                        {
                            IssueFormsAuthenticationTicket(user);
                            if (string.IsNullOrEmpty(returnUrl))
                                return RedirectToAction("Index", "Home");
                            else
                                return Redirect(returnUrl);
                        }
                        else
                        {
                            var registrationModel = new RegistrationViewModel(identifier)
                            {
                                ReturnUrl = returnUrl
                            };
                            var simpleReg = response.GetExtension();
                            if (simpleReg != null)
                            {
                                if (!string.IsNullOrEmpty(simpleReg.Email))
                                    registrationModel.Email = simpleReg.Email;

                                if (!string.IsNullOrEmpty(simpleReg.FullName))
                                    registrationModel.FullName = simpleReg.FullName;

                                if (!string.IsNullOrEmpty(simpleReg.Nickname))
                                    registrationModel.Username = simpleReg.Nickname;
                            }
                            return View("Register", registrationModel);
                        }
                    case AuthenticationStatus.Canceled:
                        ModelState.AddModelError("openid_identifier", "Authetication canceled");
                        break;
                    case AuthenticationStatus.Failed:
                        ModelState.AddModelError("openid_identifier", "Authetication failed");
                        break;
                }
            }
            return View();
        }

        public ActionResult Register()
        {
            return RedirectToAction("Login");
        }

        [HttpPost]
        public ActionResult Register(User user, string identifier, string returnUrl)
        {
            //The registration form has been submitted
            try
            {
                if (ModelState.IsValid)
                {
                    var feed = _feedRepo.Create(new Feed(){
                        Id = Guid.NewGuid(),
                        Name = "Default"
                    });
                    user.OpenId = identifier;
                    user.ApiKey = Guid.NewGuid();
                    user.FeedUsers.Add(new FeedUser(){
                        IsOwner = true,
                        FeedId = feed.Id
                    });
                    _userRepo.Create(user);

                    // Now let's login out user to out application
                    IssueFormsAuthenticationTicket(user);

                    // We're done, let's get back to where we started from.
                    if (string.IsNullOrEmpty(returnUrl))
                        return RedirectToAction("Index", "Home");
                    else
                        return Redirect(returnUrl);
                }

                var registrationModel = new RegistrationViewModel(identifier)
                {
                    Username = user.Username,
                    Email = user.Email,
                    FullName = user.FullName,
                    ReturnUrl = returnUrl
                };

                return View(registrationModel);
            }
            catch
            {
                var registrationModel = new RegistrationViewModel(identifier)
                {
                    Username = user.Username,
                    Email = user.Email,
                    FullName = user.FullName,
                    ReturnUrl = returnUrl
                };

                return View(registrationModel);
            }
        }

A complete example can be downloaded at https://github.com/gligoran/mvcopenid

Advertisements

Integrate openID, oAuth to your site using JanRain

Integrate openID to your site using JanRain. It is definitely a time saver. My site is built in mvc3 and here are the steps how to do it.

1. You need to setup the widget and copy the generated js code to your site and update the “tokenUrl”.

<script type="text/javascript">(function() {    if (typeof window.janrain !== 'object') window.janrain = {};    window.janrain.settings = {};

    janrain.settings.tokenUrl = '__REPLACE_WITH_YOUR_TOKEN_URL__';

    function isReady() { janrain.ready = true; };    if (document.addEventListener) {      document.addEventListener("DOMContentLoaded", isReady, false);    } else {      window.attachEvent('onload', isReady);    }

    var e = document.createElement('script');    e.type = 'text/javascript';    e.id = 'janrainAuthWidget';

    if (document.location.protocol === 'https:') {      e.src = 'https://rpxnow.com/js/lib/itsharp/engage.js';    } else {      e.src = 'http://widget-cdn.rpxnow.com/js/lib/itsharp/engage.js';    }

    var s = document.getElementsByTagName('script')[0];    s.parentNode.insertBefore(e, s);})();</script>

2. Add your site url to the whitelist, here I put “itsharp.com.au”

itsharp.com.au JanRain Integration
itsharp.com.au JanRain Integration

3. I created a JanRainHelper to make the “auth_info” API call, and a class “JanRainData” for the de-serialization of the response data. (please forgive the naming conversions, I just copied all the return data fields from JanRain)

Don’t forget to copy your own “apiKey” and paste in the code below.

public class JanRainHelper{public static string AuthInfo(string token){string apiKey = "***************************";

WebRequest req = WebRequest.Create("https://rpxnow.com/api/v2/auth_info");

((HttpWebRequest)req).UserAgent = "JanRainProServ/1.0(Automated)";req.Method = "POST";

string postData = "token=";postData += token;postData += "&apiKey=";postData += apiKey;

byte[] byteArray = Encoding.UTF8.GetBytes(postData);// Set the ContentType property of the WebRequest.req.ContentType = "application/x-www-form-urlencoded";// Set the ContentLength property of the WebRequest.req.ContentLength = byteArray.Length;// Get the request stream.Stream dataStream = req.GetRequestStream();// Write the data to the request stream.dataStream.Write(byteArray, 0, byteArray.Length);// Close the Stream object.dataStream.Close();

// Send the data to the webserverHttpWebResponse rsp = (HttpWebResponse)req.GetResponse();string content = "";using (StreamReader sr = new StreamReader(rsp.GetResponseStream())){content = sr.ReadToEnd();}return content;}}

 

[Serializable]public class JanRainData{public Profile profile { get; set; }public string stat { get; set; }}

[Serializable]public class Profile{public string identifier { get; set; }

public string providerName { get; set; }

public string displayName { get; set; }

public Name name { get; set; }

public string gender { get; set; }

public bool? genderBool{get{if (string.IsNullOrEmpty(gender))return null;else{if (gender.Equals("male")){return true;}else if (gender.Equals("female")){return false;}else{return null;}}}}

public string birthday { get; set; }

public DateTime? birthdayDateTime{get{DateTime dt;if (!string.IsNullOrEmpty(birthday) && DateTime.TryParse(birthday, out dt)){return dt;}else{return null;}}}

public string email { get; set; }

public string verifiedEmail { get; set; }

public string phoneNumber { get; set; }

public string photo { get; set; }

public Address address { get; set; }}

[Serializable]public class Name{public string givenName { get; set; }public string familyName { get; set; }public string formatted { get; set; }}

[Serializable]public class Address{public string formatted { get; set; }public string streetAddress { get; set; }public string locality { get; set; }public string region { get; set; }public string postalCode { get; set; }public string country { get; set; }}

4. Create an Action method for the “tokenUrl”, JanRain post back with a token, and you will need to use that token to call the auth_info API to retrieve the user info.

I am using the JavascriptSerializer to deserialize the response to a JanRainData object. Then you can do whatever you need to do, such as create a user in your database and authentication cookie, etc.


public ActionResult JanRainPostBack(string token){if (!string.IsNullOrEmpty(token)){string content = JanRainHelper.AuthInfo(token);JavaScriptSerializer s = new JavaScriptSerializer();

var data = s.Deserialize<JanRainData>(content);if (data.stat.Equals("ok") && !string.IsNullOrEmpty(data.profile.providerName) &&       !string.IsNullOrEmpty(data.profile.identifier)){var user = new User(){Email = data.profile.email};_repository.Save(user);return View();}elsethrow new Exception("response failed");}elsethrow new Exception("token is invalid");}

5. It is all done now. Please be aware you might only retrieve limited user information from different openID providers. Eg, twitter will not return an email address which I think it’s pretty lame. If email is required in your dbo.User table, you will need to enforce users to complete the registration.