gpt4 book ai didi

servicestack - 用数据库中的数据填充 IAuthSession

转载 作者:行者123 更新时间:2023-12-03 09:24:07 25 4
gpt4 key购买 nike

因此,我按照位于此处的示例使用 ServiceStack 创建了一个自定义 CredentialsAuthProvider:
https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization

我有工作的身份验证方面,但我不确定如何在 OnAuthenticated 方法中使用数据库中的数据填充 session 。在示例中,它们显示以下内容:

     //Fill the IAuthSession with data which you want to retrieve in the app eg:
session.FirstName = "some_firstname_from_db";

在 TryAuthenticate 方法中,我有用户名/密码,我可以用它来针对数据库对用户进行身份验证,但是一旦它转到 OnAuthenticate 方法,我将如何/使用什么来访问/检索数据库中的用户信息?

最佳答案

我知道这是一个较旧的线程,但它可能仍然相关,因为不幸的是,自 2012 年 9 月以来,在 ServiceStack 文档的可用性、示例的清晰度甚至代码中的注释方面没有太大改进。 ( @mythz: 如果你们可以为所有的类和方法添加有意义的摘要,那将会非常有帮助。)

在查看 CredentialsAuthProvider 的实际代码之前,我一直在同样的困境中挣扎(这通常是了解 ServiceStack 中工作方式的唯一方法)。 OnAuthenticated 在 Authenticate 方法中的 TryAuthenticate 之后立即调用,因此我认为没有必要像@mythz 在他的示例中建议的那样在 OnAuthenticated 中进行所有数据库调用。相反,我将填充 IAuthSession 对象的代码直接放入我的 TryAuthenticate 实现中,如下所示:

public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
try
{
// Use my own repo to authenticate the user.
var userRepo = authService.TryResolve<IUserRepository>();
var user = userRepo.Authenticate(userName, password);

// Populate session properties with data from my user POCO.
var session = authService.GetSession();
session.Id = user.CurrentSession.ID.ToString();
session.IsAuthenticated = true;
session.CreatedAt = DateTime.UtcNow;
session.DisplayName = session.FirstName = session.LastName = user.FullName;
session.UserAuthName = session.UserName = user.Username;
session.UserAuthId = user.ID.ToString();
}
catch (Exception ex)
{
// Log the exception, etc....
return false;
}
return true;
}

但是,您仍然必须覆盖 OnAuthenticated 以将 cookie 保存在 HTTP 响应中(我认为这是来自同一浏览器的后续请求进行身份验证所必需的),因为基本实现仅在 IOC 容器中找到 IUserAuthRepository 时才设置 cookie ,在我的情况下不会发生,因为我使用我自己的存储库。所以我的实现现在看起来像这样:
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
try
{
// Save the browser cookie.
var httpRes = authService.RequestContext.Get<IHttpResponse>();
if (httpRes != null)
{
httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
}

// Save the user session object (ServiceStack stores it in the in-memory cache).
authService.SaveSession(session, SessionExpiry);
}
catch (Exception ex)
{
// Log the exception, etc....
}
}

@mythz:请让我知道以上是否合理。

关于servicestack - 用数据库中的数据填充 IAuthSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12594048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com