&#34; Store未实现IUserLockoutStore <tuser>。&#34; ExternalLoginCallBack()

时间:2018-01-03 09:22:00

标签: c# .net asp.net-mvc-5 asp.net-identity facebook-login

在ExternalLoginCallBack()调试到达此行时,它会分手:

 var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);

here is the pic of throwing the Exception

错误消息

 Message = "Store does not implement IUserLockoutStore."
 Source = "Microsoft.AspNet.Identity.Core"
StackTrace = "   at Microsoft.AspNet.Identity.UserManager`2.GetUserLockoutStore()\r\n   at Microsoft.AspNet.Identity.UserManager`2.d__134.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime...

TargetSite = {Microsoft.AspNet.Identity.IUserLockoutStore`2[TUser,TKey] GetUserLockoutStore()}

IdentityModel Calss:

// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
    public string Email { get; set; }
    public bool ConfirmedEmail { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base(DB_Management.DB_Manager.ConnectionString)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

这个RegistrationController:

 public class RegistrationController : BaseController
{
    private ApplicationUserManager _userManager;
    private ApplicationSignInManager _signInManager;

    public UserManager<ApplicationUser> UserManager { get; private set; }

    public RegistrationController()
        : this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
    {
    }

    public RegistrationController(UserManager<ApplicationUser> userManager, ApplicationSignInManager signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public RegistrationController(UserManager<ApplicationUser> userManager)
    {
        UserManager = userManager;
    }

    public ApplicationSignInManager SignInManager
    {
        get
        {
            return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
        }
        private set
        {
            _signInManager = value;
        }
    }

    public ApplicationUserManager UserManager2
    {
        get
        {
            return UserManager2 ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

  //
    // GET: /Account/ExternalLoginCallback
    [AllowAnonymous]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if (loginInfo == null)
        {
            return RedirectToAction("Login");
        }
        if (loginInfo != null)
        {
            var firstName = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "first_name").Value;
            var lastName = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "last_name").Value;
        }

        // Sign in the user with this external login provider if the user already has a login
        try
        {
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);


            ViewBag.ReturnUrl = returnUrl;
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);

                case SignInStatus.LockedOut:
                    return View("Lockout");

                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });

                case SignInStatus.Failure:
                default:
                    // If the user does not have an account, then prompt the user to create an account
                    ViewBag.ReturnUrl = returnUrl;
                    ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                    return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
            }
        }
        catch (Exception ex)
        {
            String innerMessage = (ex.InnerException != null)
                  ? ex.InnerException.Message
                  : "";
            throw ex;
        }
    }

IdentityConfig:

 public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager)
    {
    }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 8,
            RequireNonLetterOrDigit = false,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();

        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

1 个答案:

答案 0 :(得分:1)

安装参考

      `Microsoft.AspNet.Identity.EntityFramework`

来自引用,ManageNuget包

错误已完全消失(: