How to remember the login in MVC5 when an external

2019-02-13 17:49发布

问题:

In our MVC5-application with OWIN, we use additional to the local accounts also external logins (google). When the user logs in with its local account, he can activate the option to remember him, so he has not to log-in every time newly. When he logs in with his Google-account, he every time must click newly on the external login-button for google.

Is there a built-in option to activate the “remember me”-option also for external logins? Or is there a secure way to add this feature?

回答1:

You just need to set IsPersistent to true to accomplish this when you sign in the user identity (you would want to also add some kind of remember me checkbox for the external flow probably as well)

        AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = <rememberMe> }, <userIdentity>);


回答2:

To follow up on what Hao Kung suggested.

You will find the line of code in question in the accountController.cs file. The default function is:

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent}, identity);
    }

To enable the remember me functionality with all external providers, change the line:

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent}, identity);

by changing the isPersistent varible to the constant true:

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = <b>true</b>}, identity);


回答3:

using the external sign-in method:

public async Task<ActionResult> ExternalConfirm(EnumLoginProviders loginProvider, string returnUrl)
{
  var loginInfo = await MyAuthenticationManager.GetExternalLoginInfoAsync();
  ...
  // Sign in the user with this external login provider if already logged in
  var result = await SignInManager
                      .ExternalSignInAsync(loginInfo, isPersistent: <remember-me>);
  if (result == SignInStatus.Success)
  {
  ...
}
  • see Microsoft.AspNet.Identity.Owin.SignInManager::ExternalSignInAsync()

  • I usualy use "isPersist = true" in my web sites - most users expect to be logged in automatically when reentering a site requiring identification.