ASP Identity Core GeneratePasswordResetTokenAsync expired - asp.net

I have set up an Identity Server 4 project in .NET Core 2.1, I have everything working but when I use the user manager to generate the reset password token, the token expires after 24 hours, can I change this so it's 48 hours?
My code to send the reset token looks like this:
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = url.EmailConfirmationLink(user.Id, code, scheme);
My ConfigureServices looks like this:
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
Thanks :)

Adding the following code to ConfigureServices() method in Startup.cs class should help you.
services.Configure<DataProtectionTokenProviderOptions>(options =>
options.TokenLifespan = TimeSpan.FromDays(2));
Default Token Lifespan is 24 hours (1 day). Please refer github and TokenOptions

Related

How to handle default antiforgery cookie in ASP.NET Core 6?

I published an ASP.NET Core 6 web app to an IIS 10 server.
Apparently the site produces an antiforgery cookie:
Does anyone know how to get rid of it or rename it?
I tried:
builder.Services.AddAntiforgery(options =>
{
options.HeaderName = "heres-a-cookie";
});
But that just added another cookie
The following also didn't help - it renamed the identity cookie.
builder.Services.AddAntiforgery(options =>
{
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.Name = "heres-a-cookie";
});
Thanks in advance.
services.AddMvc().AddRazorPagesOptions(o=>
{
o.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
});
try above.

.Net Core 6 Can't get Claims after authenticated by ADFS

I recently got a problem about authenticated by ADFS
In dot net core 6, below is my scenario.
I got one Web-Api site host on IIS in server 2019, and an ADFS server
Web -Api domain like https://xxx.domain.com
ADFS one like https://ooo.domain.com
I use WS-federation in my program
both browsers can't get value, edge and chrome
setting is
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = WsFederationDefaults.AuthenticationScheme;
}).AddWsFederation(options =>
{ options.MetadataAddress = "my adfs url/FederationMetadata/2007-06/FederationMetadata.xml";
options.Wreply = "https://my webpai url/checkstate";
options.CallbackPath = "/checkstate";
options.BackchannelTimeout = TimeSpan.FromMinutes(1);
options.RemoteAuthenticationTimeout = TimeSpan.FromMinutes(15);
})
.AddCookie();
web-api
signin action for auth and will redirect to adfs server login page
and auth back to the checkstate action this part are work very well.
But I can't Get the value what I want.
In my understanding use the ws-federation(Microsoft.AspNetCore.Authentication.WsFederation6.0.3)
don't need to fetch other service for parse the value.
whole workflow should like this
Users fetch the Api => auth => adfs login => success and get adfs shared value in cookies
=> back to the callback action => get value in action and do something.
When I opened the Dev tools, I can see the real flow like
Signin 302 =>adfs 200 this with a lot cookies
prefix and key is "MSISAUTH"
=> checkstate 200 but, no cookies
I already contact with the ADFS server cruise member and got response said
"We done every setting and it's look fine. "
My question is Did I miss some key-part ?
and is any misunderstanding on workflow?
[Authorize]
[HttpGet("signin")]
public IActionResult Signin()
{
return new EmptyResult();
}
[HttpPost("checkstate")]
public IActionResult CheckState()
{
var name = User.Claims.FirstOrDefault(x=>x.Type == ClaimTypes.Name)?.Value;
return Ok($"Name:{name}");
}
My question is Did I miss some key-part ?
and is any misunderstanding on workflow?
How can I get the Claims value ?

.NET Core Shared Cookies

I have .NET Core app with .NET Core Identity.
I've setup shared cookie into Startup.cs:
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<DataContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = ".AspNet.SharedCookie";
});
services.AddAuthentication()
...
app.UseAuthentication();
app.UseAuthorization();
Also I have 2nd .NET Core app where I don't have authentication at all but want to use just that SharedCookie and I did the following in the Startup.cs:
services.AddAuthentication("Identity.Application")
.AddCookie("Identity.Application", options =>
{
options.Cookie.Name = ".AspNet.SharedCookie";
});
...
app.UseAuthentication();
app.UseAuthorization();
and on controller actions I set attribute [Authorize].
I logged in into 1st app and go to 2nd app and see error /Account/Login... page doesn't exist.
Yes I don't have that page but why do I see this issue? Did I forget anything to add in my code?
And one more question: what's SharedCookie string? Is it random string or it's encoded some user data? can I extract any info from that SharedCookie, for example Id of User?
So my solution was to add DataProtection step to both apps:
if (!Env.IsDevelopment())
{
services.AddDataProtection()
.PersistKeysToFileSystem("{PATH TO COMMON KEY RING FOLDER}")
.SetApplicationName("SharedCookieApp");
}
And one more question: what's SharedCookie string? Is it random string or it's encoded some user data? can I extract any info from that SharedCookie, for example Id of User?
Yes, I can extract Id, Email of user in the following way:
var id = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
var email = HttpContext.User.FindFirstValue(ClaimTypes.Email);

.NET core 2.0 cookie authentication - do not redirect [duplicate]

This question already has answers here:
ASP.NET Core 2.0 disable automatic challenge
(8 answers)
Closed 5 years ago.
I am using .NET core 2.0 with cookie authentication.
My configuration looks like this:
services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(1);
options.SlidingExpiration = true;
options.Cookie.Name = "authtoken";
});
When I access unauthorized controller, I am being redirected to /Account/Login
In .NET Core 1.1 I was able to configure this by setting
AutomaticChallenge = false.
How can I configure this in .NET Core 2.0?
I just want my controller to return HTTP 403.
Unfortunately the flag is well and truly removed. However you can override the "RedirectToLogin" event like so in your ConfigureServices method of your startup.cs
services.AddAuthentication("CookieAuthenticationScheme")
.AddCookie(options => {
options.Events.OnRedirectToLogin = (context) =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
});
Couple more tidbits here if you get stuck on the upgrade : https://dotnetcoretutorials.com/2017/09/16/cookie-authentication-asp-net-core-2-0/
Am I right to assume this is because it's an ajax call you are making (Or a Web API in general?). It seems like MS have gone hard with JWT being for Web API, and for Cookie to be for MVC only. Hence why the forced login page.

ASP .NET Core Cookie Authentication expiration changes from timestamp to "Session" upon return

I am using ASP .NET Core RC1 with Facebook-authentication and silding window cookie expiration set up like this:
app.UseIdentity();
app.UseFacebookAuthentication();
and
services.AddIdentity<ApplicationUser, IdentityRole>((options =>
{
options.Cookies.ApplicationCookie.CookieName = "myauthcookie";
options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(5);
options.Cookies.ApplicationCookie.SlidingExpiration = true;
}))
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
This works fine when the user first logs in - the cookie expiration is set correctly. However, when the user returns to the page, the expiration of the cookie is set to "Session", so in practice the user has to re-authenticate every other visit.
Why is this happening? Have I not configured it correctly?
Update:
I have now done some testing without SlidingExpiration, and the issue remains the same. Upon returning to the page, the expiration of the cookie is changed to "Session". I am using Chrome.
Also, I am not running on https. Might this be a factor?
Short Answer
Set isPersistent: true when calling SignInManager.ExternalLoginSignInAsync.
Details
In the ASP.NET Core Web Application template, the AccountController.ExternalLoginCallback method contains this code:
_signInManager.ExternalLoginSignInAsync(
info.LoginProvider,
info.ProviderKey,
isPersistent: true); <------ set a persistent cookie.
If we set isPersistent: true when calling ExternalLoginSignInAsync , this startup configuration...
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Cookies.ApplicationCookie.CookieName = "MyApplicationCookie";
options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(5);
options.Cookies.ApplicationCookie.SlidingExpiration = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
...results in this application cookie...
...which persists across browser sessions.

Resources