使用身份验证的 ASP.NET MVC 3 [英] ASP.NET MVC 3 using Authentication

查看:27
本文介绍了使用身份验证的 ASP.NET MVC 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 FormsAuthentication 保存内容?我不想通过 URL 存储 UserId.

How can I save something using FormsAuthentication? I don't want to store UserId through URL's.

例如,现在我有这个代码:

For example, now I have this code:

//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 中找到任何属性来执行此操作...

ProjectController and ProjectRepository don't looks like good code... Maybe someone can give advise, how to store UserID without using URL's? Best way to do this is save IDs on autorisation, I think. I don't found any properties in User.Identity to do this...

对不起,我忘了说我正在使用带有 Razor 视图的 MVC-3.而那个 UserId 不是一个字符串(User.Identity.Name 是一个字符串)它可能是 GUID 或者我自己的对象......

I beg a pardon, but I forgot to say that I'm using MVC-3 with Razor view. And that UserId is not a string (User.Identity.Name is a string) it could be GUID or maybe my own object...

推荐答案

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

Save the UserID in the UserData property of the FormsAuthentication ticket in the authorization cookie when the user logs on:

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 方法中读取它:

You can read it back in the PostAuthenticateRequest method in Global.asax:

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 属性并重载构造函数.

Note that in this case, CustomPrincipal derives from RolePrincipal (although if you're not using Roles, I think you need to derive from GenericPrincipal), and simply adds the UserID property and overloads the constructor.

现在,无论您在应用中需要 UserID 的任何位置,都可以执行以下操作:

Now, wherever you need the UserID in your app, you can do this:

if(HttpContext.Current.Request.IsAuthenticated)
    Guid userID = ((CustomPrincipal)HttpContext.Current.User).UserID;

这篇关于使用身份验证的 ASP.NET MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆