我正在使用 EF core 在 asp.net 中开发 API。对于用户管理,我使用 FirebaseAuth 以及这里我如何实现用户登录/注销:
`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.");
} `
我在我的项目中使用基于声明的身份验证
`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)
});
}`
这是我检查用户是否经过身份验证的方法:
`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;
}
}`
但问题是,几分钟后(~10-15)我登录所有需要授权用户的请求都会返回 401Unauthoreized 错误。我还创建了测试请求,其中我将索赔信息作为响应。这是身份验证后的响应:
`{
"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"
}
],
}`
几次之后:
` "responseStatusCode": 200,
"isAuthenticated": false,
"userName": null,
"claims": [],`
正如您所见,几分钟后用户变得未经授权。有谁知道为什么会发生这种情况以及如何解决它?
我已经尝试使用 SecurityStampValidatorOptions 但没有帮助:
services.Configure<SecurityStampValidatorOptions>(options => { options.ValidationInterval = TimeSpan.FromHours(10); });
通过在服务初始化中添加此行解决了此问题:
services.AddDataProtection()
.PersistKeysToDbContext<ApplicationDbContext>() // Store keys in the database
.SetDefaultKeyLifetime(TimeSpan.FromDays(90));
还更新了我的 dbcontext 并进行新的迁移:
public class ApplicationDbContext : DbContext,IDataProtectionKeyContext
{
//other db logic
public DbSet<DataProtectionKey> DataProtectionKeys { get; set; }
}