C# 使用 FormsAuthentication.SetAuthCookie 存储更多信息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1149996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Storing more information using FormsAuthentication.SetAuthCookie
提问by Eden
I am using aspx and c# for a setting a authentication cookie for a login.
我正在使用 aspx 和 c# 为登录设置身份验证 cookie。
FormsAuthentication.SetAuthCookie(UserName, True)
I want to store more information in the same cookie. Can I add values to this authentication cookie or do I have to use a second http cookie?
我想在同一个 cookie 中存储更多信息。我可以向此身份验证 cookie 添加值还是必须使用第二个 http cookie?
Basically I'm looking for away to store the User's Id
so I may be able to access the database using the users table row key
基本上我正在寻找存储用户的Id
所以我可以使用用户表行键访问数据库
Thanks, Eden
谢谢,伊甸
采纳答案by Joe
You can add user data to the FormsAuthenticationTicket, then generate the cookie yourself.
您可以将用户数据添加到 FormsAuthenticationTicket,然后自己生成 cookie。
There's an example in the the MSDN documentation for FormsAuthenticationTicket.
FormsAuthenticationTicket 的 MSDN 文档中有一个示例。
EDIT
编辑
Note that when creating the ticket, you need to set the timeout, which in general you will want to be the same as the value configured in web.config. Unfortunately, in the Framework 3.5 or earlier, the FormsAuthentication
class does not expose this timeout publicly. For a workaround, use one of the techniques described in the response to this connect feedback item.
请注意,在创建票证时,您需要设置超时时间,通常您希望与 web.config 中配置的值相同。不幸的是,在 Framework 3.5 或更早版本中,FormsAuthentication
该类不会公开此超时。对于变通方法,请使用对此连接反馈项的响应中描述的技术之一。
UPDATE
更新
That Connect feedback item is no longer there, sadly. Wish you had briefly described what the techniques were.
遗憾的是,Connect 反馈项目已不复存在。希望你简要描述了这些技术是什么。
Yes, it's a pity Microsoft has discarded historical Connect items. IIRC, the two techniques they suggested were:
是的,很遗憾微软丢弃了历史上的 Connect 项目。IIRC,他们建议的两种技术是:
Use WebConfigurationManager to read the relevant configuration section and get the timeout value.
Create a cookie using
FormsAuthentication.GetAuthCookie
, decrypt it usingFormsAuthentication.Decrypt
and inspect the generatedFormsAuthenticationTicket
.
使用 WebConfigurationManager 读取相关配置节并获取超时值。
使用 创建一个 cookie,使用
FormsAuthentication.GetAuthCookie
解密它FormsAuthentication.Decrypt
并检查生成的FormsAuthenticationTicket
.
Or upgrade to .NET 4.x where there is a FormsAuthentication.Timeout
property.
或者升级到有FormsAuthentication.Timeout
属性的.NET 4.x。
See this questionfor more info
有关更多信息,请参阅此问题
回答by user134706
Pass that user ID as the userName param.
将该用户 ID 作为 userName 参数传递。
FormsAuthentication.SetAuthCookie(userId, True)
How are you securing your auth tickets?
您如何确保您的身份验证票?
回答by andymeadows
You can put whatever you want in the auth cookie as long as it's useful to you. That said, if you're putting sensitive information you should, at the very least, encrypt it, but I'd recommend against putting sensitive information there. You can do something like:
只要对您有用,您就可以在 auth cookie 中放入任何您想要的内容。也就是说,如果您要放置敏感信息,则至少应该对其进行加密,但我建议不要将敏感信息放在那里。您可以执行以下操作:
Forms.SetAuthCookie (UserName + "|" + UserId, true);
Then, whenever you need the username or the user id, it is there. Just load the cookie and parse out the values you need.
然后,每当您需要用户名或用户 ID 时,它就在那里。只需加载 cookie 并解析出您需要的值。
Again, I'd advise against doing this, especially as I have it presented above. That said, it is possible. You should create accessor methods to pull the data back out:
同样,我建议不要这样做,尤其是在我上面介绍的情况下。也就是说,这是可能的。您应该创建访问器方法来提取数据:
public int CurrentUserId
{
get
{
int userId = 0;
if (HttpContext.Current.Request.IsAuthenticated)
{
userId = Convert.ToInt32(HttpContext.Current.User.Identity.Name.Split('|')[1]);
}
return userId;
}
}
public string CurrentUserName
{
get
{
string userName = string.Empty;
if (HttpContext.Current.Request.IsAuthenticated)
{
userName = HttpContext.Current.User.Identity.Name.Split('|')[0];
}
return userName;
}
}
回答by Ryan Liu
Yes it is smart to use "|" to put more info. If Microsoft have another overloaded method
是的,使用“|”是明智的 把更多的信息。如果 Microsoft 有另一个重载方法
public static void SetAuthCookie(String userName, bool createPersistentCookie, string userData)`
Then our life will be much easier, our code will be safer.
那么我们的生活就会轻松很多,我们的代码也会更安全。
回答by dochoffiday
You can store additional information in the UserData
property of the FormsAuthenticationTicket
:
您可以在 的UserData
属性中存储其他信息FormsAuthenticationTicket
:
using Newtonsoft.Json;
using System.Web;
using System.Web.Security;
public class LoggedInUser
{
public string FirstName { get; set; } = null;
public bool IsAdmin { get; set; } = false;
}
public static class Authentication
{
static void SignIn(
HttpContextBase context,
string emailAddress,
bool rememberMe,
LoggedInUser user = null)
{
var cookie = FormsAuthentication.GetAuthCookie(
emailAddress.ToLower(),
rememberMe);
var oldTicket = FormsAuthentication.Decrypt(cookie.Value);
var newTicket = new FormsAuthenticationTicket(
oldTicket.Version,
oldTicket.Name,
oldTicket.IssueDate,
oldTicket.Expiration,
oldTicket.IsPersistent,
JsonConvert.SerializeObject(user ?? new LoggedInUser()));
cookie.Value = FormsAuthentication.Encrypt(newTicket);
context.Response.Cookies.Add(cookie);
}
static void SignOut(HttpContextBase context)
{
FormsAuthentication.SignOut();
}
static LoggedInUser GetLoggedInUser()
{
if (HttpContext.Current.User?.Identity?.Name != null && HttpContext.Current.User?.Identity is FormsIdentity identity)
return JsonConvert.DeserializeObject<LoggedInUser>(identity.Ticket.UserData);
return new LoggedInUser();
}
}
进一步阅读:https: //docs.microsoft.com/en-us/aspnet/web-forms/overview/older-versions-security/introduction/forms-authentication-configuration-and-advanced-topics-cs#step-4 -storing-additional-user-data-in-the-ticket