Search code examples
entity-frameworkasp.net-mvc-4oauthfacebook-oauth

MembershipCreateUserException: The username supplied is invalid


Im trying to use Facebook registration on my MVC 4 application, but I keep getting this cryptic error System.Web.Security.MembershipCreateUserException: The username supplied is invalid. when OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName); is run

provider = "facebook"
providerUserId = "token-key"
model.Username = "bobsaget"

Everything is basically set back to a default MVC 4 application at this point. Here is the code I am running.

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
        {
            string provider = null;
            string providerUserId = null;
            if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Insert a new user into the database
                using (UsersContext db = new UsersContext())
                {
                    UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
                    // Check if user already exists
                    if (user == null)
                    {
                        // Insert name into the profile table
                        db.UserProfiles.Add(new UserProfile { UserName = model.UserName});
                        db.SaveChanges();
                        db.SaveChanges();


                        OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
                        OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);

                        return RedirectToLocal(returnUrl);
                    }
                    else
                    {
                        ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
                    }
                }
            }

            ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }

The MembershipAttribute have always been default, except its getting information from web.config.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        private static SimpleMembershipInitializer _initializer;
        private static object _initializerLock = new object();
        private static bool _isInitialized;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Ensure ASP.NET Simple Membership is initialized only once per app start
            LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
        }

        private class SimpleMembershipInitializer
        {
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer<UsersContext>(null);

                try
                {
                    using (var context = new UsersContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // Create the SimpleMembership database without Entity Framework migration schema
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                        }
                    }
                    var i = Config.ConnectionStringName;
                    WebSecurity.InitializeDatabaseConnection(
                        Config.ConnectionStringName, 
                        Config.UserTableName, 
                        Config.UsersPrimaryKeyColumnName,
                        Config.UsersUserNameColumnName, 
                        autoCreateTables: true);
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        }
    }

I have browsed the web, Stackoverflow and even tried to decompile the dll without getting to the root of the problem. Thanks in advance for your input.


Solution

  • I am not sure but i think you need to make to sure that an entry of user is properly inserted into userprofile table and also the other tables which are required for membership.