ASP.NET MVC "SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);" return failure all the time - asp.net-mvc

I've made some changes in my ExternalLogin actions. I added a new field to my user table, for the first name, and I added code as to request the first name from facebook. It could be the reason why I am getting the error. I will not post the app secret for facebook external login here, but you know it is present in my code. When I register a new user with facebook it works and keeps the user logged in, and adds the user to the database, also gets the correct first name. However When I log off and attempt to log in with facebook, it forces me to register instead of logging me in (it redirects to the register with facebook page, saying "you have successfully authenticated with facebook. Please enter a user name for this site below and click the Register button to finish logging in.")
Here is the code with the changes I made:
Inside the Startup.Auth class:
app.UseFacebookAuthentication(new FacebookAuthenticationOptions()
{
AppId = "2737863089761791",
AppSecret = "",
BackchannelHttpHandler = new HttpClientHandler(),
UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
Scope = { "email" },
Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = async context =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
foreach (var claim in context.User)
{
var claimType = string.Format("urn:facebook:{0}", claim.Key);
string claimValue = claim.Value.ToString();
if (!context.Identity.HasClaim(claimType, claimValue))
context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
}
}
}
});
Inside my ExternalLoginCallback action in AccountController:
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
var firstName = loginInfo.ExternalIdentity.Claims.First(c => c.Type == "urn:facebook:first_name").Value;
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
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, Name = firstName });
}
I figured it redirects me to the register page, because the line
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
returns failure inside ExternalLoginCallback and I don't know why. It must return success to get to the case:
case SignInStatus.Success
I had an error in my ExternalLoginConfirmation action, so i put some code in a try-catch block. It solved my problem, but I still don't know where the error was coming from:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Name, Email = model.Email , Name = model.Name};
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
try
{
var useraux = await UserManager.FindByEmailAsync(model.Email);
result = await UserManager.AddLoginAsync(useraux.Id, info.Login);
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
Response.Write("Object: " + eve.Entry.Entity.ToString());
Response.Write(" " +
"");
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
Response.Write(ve.ErrorMessage + "" +
"");
}
}
//throw;
}
if (result.Succeeded)
{
//--
//await StoreFacebookAuthToken(user);
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}

Related

Token generated outside controller is too long and it's rejected by ConfirmEmail on Controller in MVC C#

I am updating my question as I have made some progress.
Thanks in advance for your support.
Question:
I am using GenerateEmailConfirmationTokenAsync to create a token outside the Controller (it's working fine), but somehow my token is longer than the ones created within the Controller using the GenerateEmailConfirmationTokenAsync and therefore the ConfirmEmail action rejects the token. (Error: Invalid Token).
I have tried Machinekey on webconfig, HttpUtility.UrlEncode, but I am still stuck. How to sort out the Invalid Token error on Controller ConfirmEmail?
Guys, can you help me please!
Thanks.
Here is my Code:
RegisterUser (outside Controller)
public async Task RegisterUserAsync()
{
var store = new UserStore<ApplicationUser>(db);
var UserManager = new ApplicationUserManager(store);
var query = from c in db.Customer
where !(from o in db.Users
select o.customer_pk)
.Contains(c.customer_pk)
select c;
var model = query.ToList();
if (query != null)
{
foreach (var item in model)
{
var user = new ApplicationUser { UserName = item.email, Email = item.email, customerId = item.customerId};
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id);
SmtpClient client = new SmtpClient();
MailMessage message = new MailMessage
{
IsBodyHtml = true
};
message.Subject = "Confirm Email";
message.To.Add(item.email1);
message.Body = "Please confirm your account by clicking here";
client.SendAsync(message, "userToken");
//Assign Role User Here
await UserManager.AddToRoleAsync(user.Id, "Client");
}
}
}
}
SendEmailConfirmation method (outside Controller)
public async Task<string> SendEmailConfirmationTokenAsync(string userID)
{
var store = new UserStore<ApplicationUser>(db);
var UserManager = new ApplicationUserManager(store);
var url = new UrlHelper();
var provider = new DpapiDataProtectionProvider("MyApp");
UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(
provider.Create("EmailConfirmation"));
string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID);
string encodedCode = HttpUtility.UrlEncode(code);
string callbackUrl = "http://localhost/Accounts/ConfirmEmail?userId=" + userID + "&code=" + encodedCode;
return callbackUrl;
}
where db is
ApplicationdDbContext db = new ApplicationdDbContext();
ConfirmEmail within the Identity Controller (Accounts Controller) - I've created Accounts instead of Account controller but it's working fine.
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var confirmed = await UserManager.IsEmailConfirmedAsync(userId);
if (confirmed)
{
return RedirectToLocal(userId);
}
var result = await UserManager.ConfirmEmailAsync(userId, code); //Here I get the error (Token Invlaid, despite the token and userId being displayed)
if (result.Succeeded)
{
ViewBag.userId = userId;
ViewBag.code = code;
}
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
[HttpPost]
[ValidateAntiForgeryToken]
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(SetPasswordViewModel model, string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.AddPasswordAsync(userId, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(userId);
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToLocal(userId);
}
ViewBag.userId = userId;
ViewBag.code = code;
AddErrors(result);
return View(model);
}
I have worked for hours in this code but until now I can't sort it out.
Thanks for any comments or solution. The reason for this approach is that I have to use task scheduler(I'm using fluentscheduler, which is working fine).

Owin OAuth Providers Twitter and Microsoft

I am having issues with the below line returning null for twitter and microsoft:
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
this is in the account controller like below:
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await
AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
var result = await SignInManager.ExternalSignInAsync(loginInfo, false);
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 AccountExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
In the startup.auth.cs the current configuration is:
app.UseTwitterAuthentication(
new TwitterAuthenticationOptions()
{
ConsumerKey = ConfigurationManager.AppSettings["TwitterAPIKey"],
ConsumerSecret = ConfigurationManager.AppSettings["TwitterAPISecret"],
Provider = new TwitterAuthenticationProvider()
{
OnAuthenticated = context =>
{
context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstoken", context.AccessToken));
context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstokensecret",
context.AccessTokenSecret));
return Task.FromResult(true);
}
}
});
app.UseMicrosoftAccountAuthentication(new MicrosoftAccountAuthenticationOptions()
{
ClientId = ConfigurationManager.AppSettings["MicrosoftAPIKey"],
ClientSecret = ConfigurationManager.AppSettings["MicrosoftAPISecret"],
// Scope = { "wl.basic", "wl.emails" },
Provider = new MicrosoftAccountAuthenticationProvider()
{
OnAuthenticated = context =>
{
context.Identity.AddClaim(new Claim("urn:microsoftaccount:access_token", context.AccessToken, "Microsoft"));
context.Identity.AddClaim(new Claim("urn:microsoft:email", context.Email));
return Task.FromResult(true);
}
}
});
It has been suggested including Scope = { "wl.basic", "wl.emails" } in MicrosoftAccountAuthenticationOptions. This returns a bad request however. Any ideas on the way to resolve this issue with twitter and microsoft login.
My urls I am using for microsoft are
Redirect Url: https://localhost/signin-microsoft
Logout Url: https://localhost/account/logout
Homepage: https://localhost
Twitter
Website: https://127.0.0.1
Call Back url: https://127.0.0.1/signin-twitter
I have tried with live urls on live also and am still getting null on
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
Try this:
var options = new TwitterAuthenticationOptions
{
SignInAsAuthenticationType = signInAsType,
ConsumerKey = "...",
ConsumerSecret = "...",
Provider = new TwitterAuthenticationProvider()
{
OnAuthenticated = async ctx =>
{
var manager = new OAuth.Manager(
"-your-twitter-access-token-",
"-your-twitter-access-token-secret-",
ctx.AccessToken,
ctx.AccessTokenSecret);
var url = "https://api.twitter.com/1.1/account/verify_credentials.json";
var authzHeader = manager.GenerateAuthzHeader(url, "GET");
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception("NOK");
var responseStream = response.GetResponseStream();
var reader = new System.IO.StreamReader(responseStream);
var res = reader.ReadToEnd();
Newtonsoft.Json.Linq.JObject data = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(res);
var claims = new List<Claim>();
claims.Add(new Claim(Core.Constants.ClaimTypes.RawData, ctx.Identity.Claims.ToJsonString()));
claims.Add(new Claim(Core.Constants.ClaimTypes.AccessToken, ctx.AccessToken));
claims.Add(new Claim(Core.Constants.ClaimTypes.AccessTokenSecret, ctx.AccessTokenSecret));
claims.Add(new Claim(Core.Constants.ClaimTypes.Subject, ctx.UserId));
claims.Add(new Claim(Core.Constants.ClaimTypes.Name, data["name"].TokenString()));
claims.Add(new Claim(Core.Constants.ClaimTypes.Locale, GenerateLocale(data["lang"].TokenString())));
claims.Add(new Claim(Core.Constants.ClaimTypes.ZoneInfo, GenerateZone(data["location"].TokenString(), data["time_zone"].TokenString())));
claims.Add(new Claim(Core.Constants.ClaimTypes.WebSite, data["url"].TokenString()));
claims.Add(new Claim(Core.Constants.ClaimTypes.ProfileUrl, "https://twitter.com/" + ctx.ScreenName));
claims.Add(new Claim(Core.Constants.ClaimTypes.Picture, data["profile_image_url"].TokenString()));
await PrepClaims(ctx.Identity, claims);
}
}
}

UserManager.FindByNameAsync slow in ASP.NET MVC

I have a site based on ASP.NET MVC framework. Although i am using async method to login the user, i have found that it takes forever to get user logged in into the site. I have used Visual Studio's diagnostic tools and found that this line takes most of the time during the code execution.
var user = await UserManager.FindByNameAsync(model.Email);
Full Code:
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user != null)
{
var getPasswordResult = UserManager.CheckPassword(user, model.Password);
if (getPasswordResult)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
var identity = await UserManager.CreateIdentityAsync(
user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe }, identity);
if (model.RememberMe == true)
{
HttpCookie cookie = new HttpCookie("UsersLogin");
cookie.Values.Add("UserName", model.Email);
cookie.Expires = DateTime.Now.AddDays(15);
Response.Cookies.Add(cookie);
}
return RedirectToAction("NavigateAuthUser", "Home", new { ReturnUrl = returnUrl });
}
else
{
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
return new EmptyResult();
}
Any suggestion to improve the performance?
Thanks
Sanjeev
For workaround I use:
_db.Users.First(x => x.UserName == User.Identity.Name);
But I'm sure this is not the best way
Develop my own method FindByEmail, this way I greatly improve the perfomance
public AspNetUsers FindByEmail(string Email)
{
try
{
var _modelo = new SIGMAEntities();
return _modelo.AspNetUsers.FirstOrDefault(x => x.Email.Trim().ToLower() == Email);
}
catch (Exception)
{
throw;
}
}

Mix OAuth ("Individual Accounts") and Azure Active Directory ("Organizational Accounts") authentication in MVC5 [duplicate]

I am kind of successful by doing this in the Startup.Auth.cs file
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.Properties["Microsoft.Owin.Security.Constants.DefaultSignInAsAuthenticationType"] = "ExternalCookie";
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri
});
The challenge I have is, when a user is signed out,and tries to hit a non-login page like say http://mywebsite/users/management rather than http://mywebsite/account/login the application redirects to the Azure AD sign-in page automatically, which is not right. Because there could be users who do not have account on Azure AD at all. Even if we give a proper userid and password in the AD sign in page and click sign-in, it keeps redirecting between different urls within http://login.windows.net and never goes to our website at all.
Here is the logout code -
AuthenticationManager.SignOut(new string[] { DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.ApplicationCookie, OpenIdConnectAuthenticationDefaults.AuthenticationType });
return RedirectToAction("Login", "Account");
I am not sure what I'm doing wrong here.
Edit 1
My ExternalLoginCallback method
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Sid, "Office365"));
// Sign in the user with this external login provider if the user already has a login
var user = await UserManager.FindByEmailAsync(loginInfo.ExternalIdentity.Name);
if (user != null && user.IsActive == true && user.EmailConfirmed == true)
{
var result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
if (result.Succeeded)
{
if (claims != null)
{
var userIdentity = await user.GenerateUserIdentityAsync(UserManager);
userIdentity.AddClaims(claims);
}
}
await SignInAsync(user, isPersistent: true);
Session[AppConstants.General.UserID] = user.Id;
string fullName = string.Format("{0} {1}",user.FirstName,user.LastName);
Session[AppConstants.General.UserFullName] = fullName;
return RedirectToLocal(returnUrl);
}
else
{
// If the user does not have an account, tell that to the user.
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
Try this
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = ClientId,
Authority = Authority,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
RedirectToIdentityProvider = (context) =>
{
if (context.Request.Path.Value == "/Account/ExternalLogin" || (context.Request.Path.Value == "/Account/LogOff" && context.Request.User.Identity.IsExternalUser()))
{
// This ensures that the address used for sign in and sign out is picked up dynamically from the request
// this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
// Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;
}
else
{
//This is to avoid being redirected to the microsoft login page when deep linking and not logged in
context.State = Microsoft.Owin.Security.Notifications.NotificationResultState.Skipped;
context.HandleResponse();
}
return Task.FromResult(0);
},
}
});
EDIT:
Forgot this extension method
public static class IdentityExtensions
{
public static bool IsExternalUser(this IIdentity identity)
{
ClaimsIdentity ci = identity as ClaimsIdentity;
if (ci != null && ci.IsAuthenticated == true)
{
var value = ci.FindFirstValue(ClaimTypes.Sid);
if (value != null && value == "Office365")
{
return true;
}
}
return false;
}
}
EDIT 2:
You have to have some custom logic in the ExternalLoginCallback (AccountController) e.g. add the Sid claim. In this case there is also logic to check if the user allows external login.
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl, string urlHash)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Sid, "Office365"));
// Sign in the user with this external login provider if the user already has a login
var user = await UserManager.FindAsync(loginInfo.Login);
if (user == null)
{
user = await UserManager.FindByNameAsync(loginInfo.DefaultUserName);
if (user != null)
{
if(user.AllowExternalLogin == false)
{
ModelState.AddModelError("", String.Format("User {0} not allowed to authenticate with Office 365.", loginInfo.DefaultUserName));
return View("Login");
}
var result = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
if (result.Succeeded)
{
if (claims != null)
{
var userIdentity = await user.GenerateUserIdentityAsync(UserManager);
userIdentity.AddClaims(claims);
}
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", String.Format("User {0} not found.", loginInfo.DefaultUserName));
return View("Login");
}
}
else
{
if (user.AllowExternalLogin == false)
{
ModelState.AddModelError("", String.Format("User {0} not allowed to authenticate with Office 365.", loginInfo.DefaultUserName));
return View("Login");
}
if (claims != null)
{
var userIdentity = await user.GenerateUserIdentityAsync(UserManager);
userIdentity.AddClaims(claims);
}
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}

ASP.net MVC Authentication Cookie is dismissed after closing browser [duplicate]

I am using asp.net identity 2.0 to manage user logins.
I am following the sample for Identity 2.0 and cannot get the cookie to persist after the whole browser is closed. This is happening on all browsers.
Code:
Account Controller
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await SignInHelper.PasswordSignIn(model.Email, model.Password, isPersistent: true, shouldLockout: true);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
SignInHelper
public async Task<SignInStatus> PasswordSignIn(string userName, string password, bool isPersistent, bool shouldLockout)
{
var user = await UserManager.FindByNameAsync(userName);
if (user == null)
{
return SignInStatus.Failure;
}
if (await UserManager.IsLockedOutAsync(user.ID))
{
return SignInStatus.LockedOut;
}
if (await UserManager.CheckPasswordAsync(user, password))
{
// password verified, proceed to login
return await SignIn(user, isPersistent);
}
if (shouldLockout)
{
await UserManager.AccessFailedAsync(user.ID);
if (await UserManager.IsLockedOutAsync(user.ID))
{
return SignInStatus.LockedOut;
}
}
return SignInStatus.Failure;
}
-
private async Task<SignInStatus> SignIn(User user, bool isPersistent)
{
await SignInAsync(user, isPersistent);
return SignInStatus.Success;
}
-
public async Task SignInAsync(User user, bool isPersistent)
{
var userIdentity = await user.GenerateUserIdentityAsync(UserManager);
AuthenticationManager.SignIn(
new AuthenticationProperties
{
IsPersistent = isPersistent
},
userIdentity
);
}
Startup.Auth
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
CookieName = "ApplicationCookie",
LoginPath = new PathString("/Account/Login"),
ExpireTimeSpan = System.TimeSpan.FromMinutes(180), // 3 hours
SlidingExpiration = true,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(
validateInterval: TimeSpan.FromMinutes(0),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
getUserIdCallback: (user) => (user.GetGuidUserId()))
}
});
Sorry for the wall of code, but I can't see what I am doing wrong, that the cookie wouldn't be persisted for the 3 hours, when the browser was closed without manually logging off?
The issue is with a bug in the OnValidateIdentity which when regenerating the cookie currently always sets IsPersistent to false (even if the original cookie was persistent). So because you set validateInterval to 0 (always validate every request), you effectively never will get a persistent cookie.

Resources