Implementing Third Party Logins for Umbraco Membership

Implementing Third Party Logins for Umbraco Membership

In this article, we have some small agenda to implement in the Umbraco Application. These agendas are following

  • Installing Umbraco Identity
  • Simple Login Forms for Users
  • Third Party Login
  • Simple Registration for the Umbraco Members
  • Email Authorization 

For implementing Umbraco Authentication we should have to install Umbraco NuGet package on the website project. After Installing Umbraco then install the package Umbraco Identity. After installing you will see the controllers that you have a new controller name “UmbracoIdentityAccount”. You will see ASP.NET Account controller type code in it. Now you have to make more code in it according to your scenarios.


[HttpPost]

[AllowAnonymous]

publicasyncTask<ActionResult> HandleRegisterMember([Bind(Prefix = "registerModel")]RegisterModel model)

        {

 

            if (ModelState.IsValid == false)

            {

                return CurrentUmbracoPage();

            }

 

            var user = newUmbracoApplicationMember()

            {

                UserName = model.UsernameIsEmail || model.Username == null ? model.Email : model.Username,

                Name=model.Name,

                Email = model.Email,

                MemberProperties = model.MemberProperties,

                MemberTypeAlias = model.MemberTypeAlias

            };

           

            var result = await UserManager.CreateAsync(user, model.Password);

           

            if (result.Succeeded)

            {

                var memberservice = Services.MemberService;

                var member = memberservice.GetByEmail(model.Email);

                member.IsApproved = false;

                memberservice.Save(member);

 

                // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771

                // Send an email with this link

                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                IdentityMessage Message = newIdentityMessage();

                Message.Destination = user.Email;

                var callbackUrl = Url.Action("ConfirmEmail", "UmbracoIdentityAccount", new { userId = user.Id, code = code, Email = user.Email }, protocol: Request.Url.Scheme);

                Message.Subject = "Confirm your account";

                Message.Body = "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>";

                SendEmail(Message);

 

                if (model.RedirectUrl.IsNullOrWhiteSpace() == false)

                {

                    return Redirect(model.RedirectUrl);

                }

                //redirect to current page by default               

                return RedirectToCurrentUmbracoPage();

            }

            else

            {

                AddModelErrors(result, "registerModel");

            }

 

            return CurrentUmbracoPage();

        }



The above code is RegisterHandle Action. In this method, we use a method SendEmail to Email the user about activation code. The code of SendEmail is following



privatevoid SendEmail(IdentityMessage message)

        {

            var myMessage = newSendGridMessage();

            myMessage.AddTo(message.Destination);

            myMessage.From = new System.Net.Mail.MailAddress(

                                "[email protected]", "Subject Your Choice");

            myMessage.Subject = message.Subject;

            myMessage.Text = message.Body;

            myMessage.Html = message.Body;

 

            var credentials = newNetworkCredential(

                       ConfigurationManager.AppSettings["mailAccount"],

                       ConfigurationManager.AppSettings["mailPassword"]

                       );

 

            // Create a Web transport for sending email.

            var transportWeb = newWeb(credentials);

 

            // Send the email.

            if (transportWeb != null)

            {

                 transportWeb.DeliverAsync(myMessage);

 

            }

            else

            {

                 Task.FromResult(0);

            }

        }



For Implementing this Email code we use SendGrid a third party tool to send Emails to users. Users will get Email activation code and after getting the email it is redirecting to back its website.



[AllowAnonymous]

        publicActionResult ConfirmEmail(string userId, string code, string Email)

        {

            if (userId == null || code == null)

            {

                return View();

            }

            var memberservice = Services.MemberService;

            var member = memberservice.GetById(Int32.Parse(userId));

            if(member!=null)

            {

                member.IsApproved = true;

                memberservice.Save(member);

            }

            return View();

        }


This method will ConfirmEmail Email through these lines


  member.IsApproved = true;

                memberservice.Save(member);

 

Now moving towards Login Method. It can only Login when there is an Approved account.


[HttpPost]

        [AllowAnonymous]

        publicasyncTask<ActionResult> HandleLogin([Bind(Prefix = "loginModel")] LoginModel model)

        {

            if (ModelState.IsValid)

            {

                var user = await UserManager.FindAsync(model.Username, model.Password);

               

                if (user != null)

                {

                    var memberservice = Services.MemberService;

                    var member = memberservice.GetByEmail(model.Username);

                    if (member.IsApproved==false)

                    {

                        ModelState.AddModelError("loginModel", "Email not Confirmed");

                        return CurrentUmbracoPage();

                    }

                    else

                    {

                        await SignInAsync(user, true);

                        return RedirectToCurrentUmbracoPage();

                    }

                   

                }

                ModelState.AddModelError("loginModel", "Invalid username or password");

            }

 

            return CurrentUmbracoPage();

        }



For Implementing Third Party Logins you have to install package UmbracoCms.IdentityExtensions.Facebook After that open the file UmbracoStandardOwinStartup.cs from App_Start folder and then add the code like this



app.ConfigureBackOfficeFacebookAuth(

                appId: "You App Id Code",

              appSecret: "Your App Secret Code");



After all these processes you are able to achieve all agendas which we decided at the start.


Comments