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

One thought on “A JQuery plugin for OpenID selector & DotNetOpenAuth integration in MVC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s