gpt4 book ai didi

authentication - 使用身份验证的ASP.NET MVC 3

转载 作者:行者123 更新时间:2023-12-03 11:34:38 28 4
gpt4 key购买 nike

如何使用FormsAuthentication保存内容?我不想通过URL存储UserId。
例如,现在我有以下代码:

//UserController class:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (repository.ValidateUser(model.Login, model.Password))
{
FormsAuthentication.SetAuthCookie(model.Login, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Project", "Index");
}
}
else
{
ModelState.AddModelError("", "Incorrect name or password.");
}
}

return View(model);
}
ProjectController类:
public ViewResult Index()
{
return View(repository.GetUserProjects(
this.ControllerContext.HttpContext.User.Identity.Name));
}
ProjectRepository:
ProjectsContext context = new ProjectsContext();
UsersContext uCnt = new UsersContext();

public IEnumerable<Project> GetUserProjects(String username)
{
if (String.IsNullOrEmpty(username))
throw new ArgumentNullException("username", "Login is empty");
return this.uCnt.Users
.FirstOrDefault(u => u.Login == username)
.Projects
.ToList();
}
ProjectController和ProjectRepository看起来不是很好的代码...也许有人可以提供建议,如何在不使用URL的情况下存储UserID?我认为,最好的方法是将ID保留在自动提升上。我没有在User.Identity中找到任何属性来执行此操作...
UPD
请原谅,但我忘了说我在Razor View 中使用MVC-3。
而且UserId不是字符串(User.Identity.Name是字符串),它可能是GUID或我自己的对象...

最佳答案

用户登录时,将用户ID保存在授权cookie的FormsAuthentication票证的UserData属性中:

string userData = userID.ToString();

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.Email,
DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
createPersistentCookie, userData);
string hashedTicket = FormsAuthentication.Encrypt(ticket);

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket);
HttpContext.Current.Response.Cookies.Add(cookie);

您可以在Global.asax的PostAuthenticateRequest方法中读回它:
HttpCookie formsCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

if (formsCookie != null)
{
FormsAuthenticationTicket auth = FormsAuthentication.Decrypt(formsCookie.Value);

Guid userID = new Guid(auth.UserData);

var principal = new CustomPrincipal(Roles.Provider.Name, new GenericIdentity(auth.Name), userID);

Context.User = Thread.CurrentPrincipal = principal;
}

请注意,在这种情况下,CustomPrincipal是从RolePrincipal派生的(尽管如果您不使用Roles,我认为您需要从GenericPrincipal派生),并且只需添加UserID属性并重载构造函数即可。

现在,无论您在应用中需要UserID的什么地方,都可以执行以下操作:
if(HttpContext.Current.Request.IsAuthenticated)
Guid userID = ((CustomPrincipal)HttpContext.Current.User).UserID;

关于authentication - 使用身份验证的ASP.NET MVC 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4237394/

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