Monday, March 31, 2014

The simple way to add Google login (OpenID) into ASP.NET MVC project

Step 1: Add DotnetOpenAuth lib from http://www.dotnetopenauth.net/ into ASP.NET MVC project reference
Step 2: Add following section into web.config file:

    

Step 3: Add an action for Authentication
protected static OpenIdRelyingParty openid = new OpenIdRelyingParty();
        [ValidateInput(false)]
        public ActionResult LoginByGoogle(string returnUrl)
        {
            var response = openid.GetResponse();
            if (response == null)
            {
                string openidUrl = "https://www.google.com/accounts/o8/id";
                Identifier id;
                if (Identifier.TryParse(openidUrl, out id))
                {
                    try
                    {
                        var req = openid.CreateRequest(openidUrl);
                        var fetch = new FetchRequest();
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
                        req.AddExtension(fetch);
                        return req.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        ViewData["Message"] = ex.Message;
                        return View("LogOn");
                    }
                }

                ViewData["Message"] = "Invalid identifier";
                return View("LogOn");
            }
            switch (response.Status)
            {
                case AuthenticationStatus.Authenticated:
                    Session["FriendlyIdentifier"] = response.ClaimedIdentifier;
                    var sreg = response.GetExtension();
                    if (sreg != null)
                    {
                        var model = new RegisterModel()
                        {
                            Email = sreg.Email,
                        };
                        FormsAuthentication.SetAuthCookie(model.Email, true /* createPersistentCookie */);
                        return RedirectToAction("Home", "Index");
                    }
                    return View("LogOn");
                case AuthenticationStatus.Canceled:
                    ViewData["Message"] = "Canceled at provider";
                    return View("LogOn");
                case AuthenticationStatus.Failed:
                    ViewData["Message"] = response.Exception.Message;
                    return View("LogOn");
            }

            return new EmptyResult();
        }

Step 4: Add a link to point to this Action
@Html.ActionLink("Log in using Google", "LoginByGoogle")

No comments:

Post a Comment