Reputation: 11
I'm developing an API in asp.net with EF core. For user management i use FirebaseAuth and here how i implement login/logout of user:
`public async Task<IResult> LogInUser(HttpContext context, string userCred, string password,
LoginDeviceType deviceType)
{
try
{
var user = await databaseUserProvider.GetUser(userCred);
if (user == null)
return Results.Problem(detail: "Cannot find user in database", statusCode: 500,
title: "User not found");
string userEmail = emailAttribute.IsValid(userCred) ? userCred : user.Email;
var authLink = await firebaseAuthProvider.SignInWithEmailAndPasswordAsync(userEmail, password);
await SignInUserV2(userCred, password, context);
return Results.Ok(new { user.Id,user.DisplayName ,authLink.FirebaseToken });
}
catch (Exception ex)
{
return Results.Problem(detail: ex.Message, statusCode: 500, title: "An error occurred while logging in");
}
}`
`public async Task<IResult> LogOutUser(HttpContext context)
{
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Results.Ok("User has been logged out successfully.");
} `
i use claims-based authentication in my project
`public async Task SignInUserV2(string username, string password, HttpContext httpContext)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.Role, "User")
};
var claimsIdentity = new ClaimsIdentity(
claims,
CookieAuthenticationDefaults.AuthenticationScheme);
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await httpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal,
new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddDays(7)
});
}`
an this is how i check if the user authenticated:
`public override bool IsUserAuthorized(HttpContext httpContext)
{
if (httpContext.User.Identity?.IsAuthenticated == true)
{
var username = httpContext.User.Identity.Name;
var roles = httpContext.User.FindAll(ClaimTypes.Role);
return true;
}
else
{
// User is not authenticated
return false;
}
}`
but the problem is that after several minutes(~10-15) i logged in all the requests that require authorized user returns 401Unauthoreized error. Also i created test request in which i put claims info in response. This is the response right after authentication:
`{
"responseStatusCode": 200,
"isAuthenticated": true,
"userName": "myuser",
"claims": [
{
"type": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
"value": "myuser"
},
{
"type": "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
"value": "User"
}
],
}`
and this after a few time:
` "responseStatusCode": 200,
"isAuthenticated": false,
"userName": null,
"claims": [],`
as you can see after few minutes user become unauthorized. Does anyone know why this happens and how to fix it?
Ive already tried to use SecurityStampValidatorOptions but it doesnt help:
services.Configure<SecurityStampValidatorOptions>(options => { options.ValidationInterval = TimeSpan.FromHours(10); });
Upvotes: 0
Views: 30
Reputation: 11
fixed this problem by adding this line in services iniliatlization:
services.AddDataProtection()
.PersistKeysToDbContext<ApplicationDbContext>() // Store keys in the database
.SetDefaultKeyLifetime(TimeSpan.FromDays(90));
also updated my dbcontext and make new migreations:
public class ApplicationDbContext : DbContext,IDataProtectionKeyContext
{
//other db logic
public DbSet<DataProtectionKey> DataProtectionKeys { get; set; }
}
Upvotes: 1