1.response.ClaimedIdentifier 是否是针对用户存储的正确信息?
Yes。并确保将其存储在数据库中的列区分大小写。这是一个表架构,演示了如何确保它区分大小写。这来自 DotNetOpenAuth 项目模板的数据库架构。指定排序规则的“CS”位代表区分大小写。
CREATE TABLE [dbo].[AuthenticationToken] (
[AuthenticationTokenId] INT IDENTITY (1, 1) NOT NULL,
[UserId] INT NOT NULL,
[OpenIdClaimedIdentifier] NVARCHAR (250) COLLATE SQL_Latin1_General_CP1_CS_AS NOT NULL,
[OpenIdFriendlyIdentifier] NVARCHAR (250) NULL,
[CreatedOn] DATETIME NOT NULL,
[LastUsed] DATETIME NOT NULL,
[UsageCount] INT NOT NULL
);
2.FormAuthentication.SetAuthCookie是表单身份验证的首选方式吗?或者,还有更好的方法?
对于 MVC 应用程序来说确实如此,因为您仍然可以返回您的首选ActionResult
从方法来看。
3.当我调用SetAuthCookie时,除了ClaimedIdentifier之外,没有与用户相关的数据。如果我始终引用他们的 UserId,那么创建用户然后将该 UserId 存储在 cookie 中而不是 ClaimedIdentifier 中是一个更好的主意吗?
这听起来像是个人喜好。但我通常会使用 user_id,因为每次收到需要查找任何用户信息的 HTTP 请求时,它可能会导致更快的数据库查找。
4.如果我在多个地方使用该 UserId,我如何从 cookie 中检索它,或将其存储在其他更合乎逻辑/有用的地方?
表单验证does提供了一种在其加密 cookie 中存储更多信息的方法,而不仅仅是用户名,但使用它比您想象的要困难。此片段来自 DotNetOpenAuth 的 Web SSO RP 示例:
const int TimeoutInMinutes = 100; // TODO: look up the right value from the web.config file
var ticket = new FormsAuthenticationTicket(
2, // magic number used by FormsAuth
response.ClaimedIdentifier, // username
DateTime.Now,
DateTime.Now.AddMinutes(TimeoutInMinutes),
false, // "remember me"
"your extra data goes here");
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
Response.SetCookie(cookie);
Response.Redirect(Request.QueryString["ReturnUrl"] ?? FormsAuthentication.DefaultUrl);
然后您可以通过以下方式在未来的 HTTP 请求中获取额外的数据:
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null) {
var ticket = FormsAuthentication.Decrypt(cookie.Value);
if (!string.IsNullOrEmpty(ticket.UserData)) {
// do something cool with the extra data here
}
}