Implement "Remember me" in ASP.NET CORE 3.1 MVC - asp.net-core-mvc

I can't figure out how to add the functionality of "Remember me" while logging in the website ASP.NET CORE 3.1 MVC according to the code I have below. Where and how should I check if the session on server side has expired and, in this case, load the user info from the DB according to the cookie?
Practical example: A user logs in (with "Remember me" checked) and comes back on the website 1 week later. In the meantime, the session on the server has expired. I would like the user to be automatically logged in when the user comes back.
Code executed server side when logging with "Remember me" checked:
var userClaims = new List<Claim>()
{
new Claim("id", user.Id.ToString()),
new Claim("id_organisation", user.Id_organisation.ToString())
};
var grantMyIdentity = new ClaimsIdentity(userClaims, "User Identity");
var userPrincipal = new ClaimsPrincipal(new[] { grantMyIdentity });
await HttpContext.SignInAsync(userPrincipal, new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddMonths(1)
});
In the Startup.cs I have:
public void ConfigureServices(IServiceCollection services)
{
...
TimeSpan expiration_cookie_and_session = TimeSpan.FromHours(2);
services.AddAuthentication("CookieAuthentication")
.AddCookie("CookieAuthentication", config =>
{
config.Cookie.Name = "UserLoginCookie";
config.LoginPath = "/connexion";
config.SlidingExpiration = true;
config.ExpireTimeSpan = expiration_cookie_and_session;
config.EventsType = typeof(MyCookieAuthenticationEvents);
});
services.AddScoped<MyCookieAuthenticationEvents>();
services.AddSession(options => {
options.IdleTimeout = expiration_cookie_and_session;
});
...
}
public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{
//We are here in case of cookie expiration
public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> redirectContext)
{
...
}
}
My guess would be in the CookieAuthenticationEvents.OnSigningIn event. Can you help me to make it clear?
Thank you!!

You could get the cookie expire time by using:context.Properties.ExpiresUtc.
If you want to get the expire time in the other request after login successfully,you could add the expire time to HttpContext in ValidatePrincipal method.Once you sign in successfully and get into another action,it will hit the ValidatePrincipal method to add the expire time to HttpContext.
Custom CookieAuthenticationEvents:
public class MyCookieAuthenticationEvents : CookieAuthenticationEvents
{
public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
context.Request.HttpContext.Items.Add("ExpiresUTC", context.Properties.ExpiresUtc);
}
}
Get the expire time in the action:
public async Task<IActionResult> Index()
{
var expiretime = HttpContext.Items["ExpiresUTC"];
return View();
}
Result:
Update:
For how to judge the cookie expired:
public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
context.Request.HttpContext.Items.Add("ExpiresUTC", context.Properties.ExpiresUtc);
//Compare() method Return value Meaning
//Less than zero means first is earlier than second.
//Zero means first is equal to second.
//Greater than zero means first is later than second.
var calculte = DateTimeOffset.Compare((DateTimeOffset)context.Properties.ExpiresUtc, DateTimeOffset.Now);
if(calculte<0)
{
// the cookie has been expired
//do your stuff...
}
}

Related

ASP.NET Core 3.1 MVC redirect in a custom AuthorizationHandler

In a ASP.NET Core 2 MVC app, I had a custom AuthorizationHandler that redirected blocked users back to the home page.
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, IsAllowedIpAddressRequirement requirement)
{
// Cast the context resource
if (context.Resource is AuthorizationFilterContext cxt)
{
// Failed!
cxt.Result = new RedirectToActionResult("Index", "Home", new { msg = "Your auth has failed." });
context.Succeed(requirement);
}
...
}
Since migrating to ASP.NET Core 3.1, the context is an object of class Microsoft.AspNetCore.Routing.RouteEndpoint, which has no Result property.
How can I redirect the user to a specific page?
I had the same problem and to solve it I changed to Filter (IAsyncResourceFilter) instead of Policy.
You can wrap your authorization logic into a policy and then invoke the IAuthorizationService and redirect anywhere/anytime you need.
Example:
public class MySampleActionFilter: IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
//if failed
context.Result = new RedirectToRouteResult(new RouteValueDictonary(new
{
controller = "Your Controller",
action = "Your Action"
}));
}
}
By the way, this is for .net Core 3 and above
Documentation
if you want to user redirect to some page like login page, if user didn't has access, you could following below steps for fix it:
into HandleRequirementAsync method
if (Condition())
{
context.Succeed(requirement);
}
else {
context.Fail();
}
if user did has access, execute context.Succeed(requirement); and if user didn't has access, execute context.Fail();
into startup.cs => ConfigureServices method
services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromHours(12);
options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
options.SlidingExpiration = true;
});
in line that we write
options.LoginPath = "/Account/Login";
we appointment users after failing in HandleRequirementAsync method for checking access, being redirected to controller 'home' controller and 'login' actiion.
i'll hope my answer be useful for friends.

How to redirect from Identity Area to Admin in ASP.NET CORE 2

I cant redirect from Identity Area:
if (role=="Admin")
{
return RedirectToAction("Index","Home",new { Area=Input.Role ,id=9});
}
To Admin Area Controller-Home,Action-Index.Always redirect me to Index in the Identity Area;
looking at your code I am still scratching my head as to the reason that someone would specify the Role at login. Can you articulate the reasoning behind this?
Simplest answer is inline with the code within the OnPostAsync(); that resides in
//this because of the routes you have in StartUp.cs
[Authorize(Roles ="Admin")]
[Area("admin")]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Login.cs Page...
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Username, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
var user = await userManager.GetUserAsync(User); // Claims Principle
if (await userManager.IsInRoleAsync(user, "Admin"))
{
//SIMPLEST ANSWER since you using mixed environment with PAGES
return LocalRedirect("~/admin");
}
//TODO:
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
Check your issues below one by one:
I got error A method 'CakeStore.App.Areas.Admin.Controllers.HomeController.Index (CakeStore.App)' must not define attribute routed actions and non attribute routed actions at the same time, you should not define [HttpGet(Name ="AdminPanel")] and [Route(nameof(Admin) + "/[controller]")] at the same time.
//[HttpGet(Name ="AdminPanel")]
[Area(nameof(Admin))]
[Route(nameof(Admin) + "/[controller]")]
public IActionResult Index()
{
return View();
}
For var role = this.roleManage.GetUrl(Input.Username);, it will retrive the role by username, check whether you got expected role Admin.
return RedirectToAction("Index","Home",new { Area=Input.Role ,id=9});, you did not define id in Index, there is no need to add id route.

asp.net core 2.1 tempdata empty with redirecttoaction

I have an asp.net core 2.1 project and I try to use TempData with RedirectToAction but it's always null (without Error)
Here is my ConfigureServices method
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//services pour l'authentification
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/Login";
});
//services pour session
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(20);
});
//configuer port https
services.AddHttpsRedirection(options => options.HttpsPort = 443);
Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
ManageDI(services);
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddSessionStateTempDataProvider();
}
I have "app.UseSession();" in my Configure method
and here is my code
[HttpGet]
public async Task< IActionResult> ResetPassword(string query)
{
TempData["test"]= "test";
return RedirectToAction(nameof(Login));
}
[HttpGet]
public IActionResult Login(string returnUrl = null)
{
var b = TempData["test"];
//b is always null when calling ResetPassword action
var model = new Models.Account.LoginModel{
ReturnUrl = returnUrl
};
return View(model);
}
What did I forget please ?
Thanks
It's not entirely clear what the issue is based on the code you've provided, but since you mention that it's null in your ResetPassword action from within your Login action, I'm assuming you're not properly persisting the value.
TempData is just that: temporary data. Once it's been accessed, it is removed. Therefore, when you set b here with its value, that's it - it's gone. If you then try to access it in another action later or even just in the view this action returns, it will be null now.
If you need to get the value, but also keep it around for later, you need to use TempData.Peek:
var b = TempData.Peek("test");

Session variable value is getting null in ASP.NET Core

I am setting a session variable in one method and trying to get the session variable value from the another method in a controller but its always getting null:
Here is my code:
public class HomeController : Controller
{
public IActionResult Index()
{
HttpContext.Session.SetString("Test", "Hello!");
var message = HttpContext.Session.GetString("Test");// Here value is getting correctly
return View();
}
public IActionResult About()
{
var message = HttpContext.Session.GetString("Test"); // This value is always getting null here
return View();
}
}
Here is my session configuration in Startup class:
In ConfigureServices() method:
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDistributedMemoryCache();
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession(options =>
{
options.Cookie.Name = "TanvirArjel.Session";
options.IdleTimeout = TimeSpan.FromDays(1);
});
In Configure() method:
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Very strange and peculiar problem! Any help will be highly appreciated!
For ASP.NET Core 2.1 and 2.2
In the ConfigureServices method of the Startup class, Set options.CheckConsentNeeded = context => false; as follows:
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
Problem solved!
You can also just set Cookie.IsEssential = true as explained here: https://andrewlock.net/session-state-gdpr-and-non-essential-cookies/
There is an overload of services.AddSession() that allows you to configure SessionOptions in your Startup file. You can change various settings such as session timeout, and you can also customise the session cookie. To mark the cookie as essential, set IsEssential to true:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true; // consent required
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSession(opts =>
{
opts.Cookie.IsEssential = true; // make the session cookie Essential
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
I have had the same issue and tried the following separately and I found that either of them does work for me!
1. options.CheckConsentNeeded = context => false;
2. opts.Cookie.IsEssential = true; // make the session cookie Essential
However, not quite sure though, I think #1 might potentially lead to the breach of GDPR. Hence I would prefer #2.
I tried adding the mentioned lines from Microsoft docs on session it didn't work.
As I see from the code of HttpContext.Session Session can be used in the same request.
So at last, I created one static class as below which helped as Session throughout the application.
public static class SessionHelper
{
private static IDictionary<string, string> Session { get; set; } = new Dictionary<string, string>();
public static void setString(string key, string value)
{
Session[key] = value;
}
public static string getString(string key)
{
return Session.ContainsKey(key) ? Session[key] : string.Empty;
}
}
Usage:
set string in one request
SessionHelper.setString("UserId", "123");
read string in another request
SessionHelper.getString("UserId");
Hope it helps!

Custom Claims lost on Identity re validation

I'm implementing Asp.NET MVC application with Identity 2.x Authentication and Authorization model.
During LogIn process I add Custom Claims (not persisted in the DB!), deriving from data passed in the LogIn from, to the Identity and I can correctly access them later on, until the identity gets regenerated.
[HttpPost]
[AllowAnonymous]
[ValidateHeaderAntiForgeryToken]
[ActionName("LogIn")]
public async Task<JsonResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
return Json(GenericResponseViewModel.Failure(ModelState.GetErrors("Inavlid model", true)));
using (var AppLayer = new ApplicationLayer(new ApplicationDbContext(), System.Web.HttpContext.Current))
{
GenericResponseViewModel LogInResult = AppLayer.Users.ValidateLogInCredential(ref model);
if (!LogInResult.Status)
{
WebApiApplication.ApplicationLogger.ExtWarn((int)Event.ACC_LOGIN_FAILURE, string.Join(", ", LogInResult.Msg));
return Json(LogInResult);
}
ApplicationUser User = (ApplicationUser)LogInResult.ObjResult;
// In case of positive login I reset the failed login attempts count
if (UserManager.SupportsUserLockout && UserManager.GetAccessFailedCount(User.Id) > 0)
UserManager.ResetAccessFailedCount(User.Id);
//// Add profile claims for LogIn
User.Claims.Add(new ApplicationIdentityUserClaim() { ClaimType = "Culture", ClaimValue = model.Culture });
User.Claims.Add(new ApplicationIdentityUserClaim() { ClaimType = "CompanyId", ClaimValue = model.CompanyId });
ClaimsIdentity Identity = await User.GenerateUserIdentityAsync(UserManager, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, Identity);
WebApiApplication.ApplicationLogger.ExtInfo((int)Event.ACC_LOGIN_SUCCESS, "LogIn success", new { UserName = User.UserName, CompanyId = model.CompanyId, Culture = model.Culture });
return Json(GenericResponseViewModel.SuccessObj(new { ReturnUrl = returnUrl }));
}
}
The validation process is defined in the OnValidationIdentity which I havn't done much to customize. When the validationInterval goes by (...or better said the half way to the validationInterval) Identity gets re generatd and Custom Claims are lost.
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(1d),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
},
/// TODO: Expire Time must be reduced in production do 2h
ExpireTimeSpan = TimeSpan.FromDays(100d),
SlidingExpiration = true,
CookieName = "RMC.AspNet",
});
I think I should some how be able to pass the current Claims to the GenerateUserIdentityAsync so that I can re add Custom Clims, but I don't know how to.
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager, string authenticationType)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
// Add custom user claims here
// ????????????????????????????
return userIdentity;
}
Any help is appreciated.
Thanks
Problem solved (it seemms), I post my solution since I havn't found may appropriate answers and I think it might be useful to others.
The right track was found in an answer to the question Reuse Claim in regenerateIdentityCallback in Owin Identity in MVC5
I just had modify a little the code since the UserId in my case is of type string and not Guid.
Here is my code:
In Startup.Auth.cs
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
//OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
// validateInterval: TimeSpan.FromMinutes(1d),
// regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, DefaultAuthenticationTypes.ApplicationCookie))
OnValidateIdentity = context => SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, string>(
validateInterval: TimeSpan.FromMinutes(1d),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager, context.Identity),
getUserIdCallback: (ci) => ci.GetUserId()).Invoke(context)
},
/// TODO: Expire Time must be reduced in production do 2h
//ExpireTimeSpan = TimeSpan.FromDays(100d),
ExpireTimeSpan = TimeSpan.FromMinutes(2d),
SlidingExpiration = true,
CookieName = "RMC.AspNet",
});
NOTE: Please note that in my sample ExpireTimeSpan and validateInterval are ridiculously short since the purpose here was to cause the most frequest re validation for testing purposes.
In IdentityModels.cs goes the overload of GenerateUserIdentityAsync that takes care of re attaching all custom claims to the Identity.
/// Generates user Identity based on Claims already defined for user.
/// Used fro Identity re validation !!!
/// </summary>
/// <param name="manager"></param>
/// <param name="CurrentIdentity"></param>
/// <returns></returns>
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager, ClaimsIdentity CurrentIdentity)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Re validate existing Claims here
userIdentity.AddClaims(CurrentIdentity.Claims);
return userIdentity;
}
It works. Not really sure if it is the best solution, but in case anyone has better approaches please feel free to improve my answer.
Thanks.
Lorenzo
ADDENDUM
After some time using it I found out that what implemented in GenerateUserIdentityAsync(...) might give problems if used in conjunction with #Html.AntiForgeryToken(). My previous implementation would keep adding already existing Claims at each revalidation. This confuses AntiForgery logic that throws error. To prevent that I've re implemnted it this way:
/// <summary>
/// Generates user Identity based on Claims already defined for user.
/// Used fro Identity re validation !!!
/// </summary>
/// <param name="manager"></param>
/// <param name="CurrentIdentity"></param>
/// <returns></returns>
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager, ClaimsIdentity CurrentIdentity)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Re validate existing Claims here
foreach (var Claim in CurrentIdentity.Claims) {
if (!userIdentity.HasClaim(Claim.Type, Claim.Value))
userIdentity.AddClaim(new Claim(Claim.Type, Claim.Value));
}
return userIdentity;
}
}
ADDENDUM 2
I had to refine further me mechanism because my previosu ADDENDUM would lead in some peculiar cases to same problem described during re-validation.
The key to the current definitive solution is to Add Claims that I can clearly identify and Add only those during re-validation, without having to try to distinguish betweeb native ones (ASP Identity) and mine.
So now during LogIn I add the following custom Claims:
User.Claims.Add(new ApplicationIdentityUserClaim() { ClaimType = "CustomClaim.CultureUI", ClaimValue = UserProfile.CultureUI });
User.Claims.Add(new ApplicationIdentityUserClaim() { ClaimType = "CustomClaim.CompanyId", ClaimValue = model.CompanyId });
Note the Claim Type which now starts with "CustomClaim.".
Then in re-validation I do the following:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, string> manager, ClaimsIdentity CurrentIdentity)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Re validate existing Claims here
foreach (var Claim in CurrentIdentity.FindAll(i => i.Type.StartsWith("CustomClaim.")))
{
userIdentity.AddClaim(new Claim(Claim.Type, Claim.Value));
// TODO devo testare perché va in loop la pagina Err500 per cui provoco volontariamente la duplicazioen delle Claims
//userIdentity.AddClaims(CurrentIdentity.Claims);
}
return userIdentity;
}
userIdentity does not contain the Custom Claims, while CurrentIdentity does contain both, but the only one I have to "re attach" to the current Identity are my custom one.
So far it is working fine, so I'll mark this as teh answer.
Hope it helps !
Lorenzo
Ohh lord i got tired of trying to get this to work, i just modified the SecurityStampValidator to take a context that i could pull the Identity out of to update accordingly in my User class. as far as i can tell there is no way to directly extend it. Updating claims from manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); had no affect using GenerateUserIdentityAsync
var validator = MySecurityStampValidator
.OnValidateIdentity<ApplicationUserManager, ApplicationUser, Guid>(
validateInterval: TimeSpan.FromSeconds(2),
regenerateIdentityCallback: (manager, user, claims) => user.UpdateUserIdentityAsync(claims),
getUserIdCallback: (id) => id.GetUserGuid());
var cookieAuthenticationOptions = new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
Provider = new CookieAuthenticationProvider
{
// Not called on signin
OnValidateIdentity = validator
}
};
And then copied the owin class but added the context to it that would be passed into my regenerateIdentityCallback
static class MySecurityStampValidator
{
public static Func<CookieValidateIdentityContext, Task> OnValidateIdentity<TManager, TUser, TKey>(
TimeSpan validateInterval,
Func<TManager, TUser, ***ClaimsIdentity***, Task<ClaimsIdentity>> regenerateIdentityCallback,
Func<ClaimsIdentity, TKey> getUserIdCallback)
where TManager : UserManager<TUser, TKey>
where TUser : class, IUser<TKey>
where TKey : IEquatable<TKey>
{
......
And then in my user i just
public override async Task<ClaimsIdentity> UpdateUserIdentityAsync(ClaimsIdentity userIdentity)
{
userIdentity.RemoveClaim(CustomClaimTypes.CLAIM1);
userIdentity.RemoveClaim(CustomClaimTypes.CLAIM2);
if (Access1Service.GetService().UserHasAccess(Id))
{
userIdentity.AddClaim(new Claim(CustomClaimTypes.CLAIM1, "1"));
}
if (Access2Service.GetService().UserHasAccess(Id))
{
userIdentity.AddClaim(new Claim(CustomClaimTypes.CLAIM2, "1"));
}
return userIdentity;
}

Resources