如何手动创建身份验证 cookie 而不是默认方法? [英] How can I manually create a authentication cookie instead of the default method?

查看:22
本文介绍了如何手动创建身份验证 cookie 而不是默认方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 FormsAuthentication 我们编写如下代码:

Using FormsAuthentication we write code like this:

 if (IsValidUser())
 {
      FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
      FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie); 
 }

  1. 如何手动创建身份验证 cookie 而不是编写 FormsAuthentication.SetAuthCookie(userName, createPersistentCookie)?

如何将登录页面的重定向 URL 存储在字符串变量中,而不是编写 FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie)?

How can I store a redirect URL from the login page in a string variable instead of writing FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie)?

推荐答案

给你.当您使用 FormsAuthentication 中内置的更高级别方法时,ASP.NET 会为您处理此问题,但在低级别,这是创建身份验证 cookie 所必需的.

Here you go. ASP.NET takes care of this for you when you use the higher level methods built into FormsAuthentication, but at the low level this is required to create an authentication cookie.

if (Membership.ValidateUser(username, password))
{  
  // sometimes used to persist user roles
  string userData = string.Join("|",GetCustomUserRoles());

  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    1,                                     // ticket version
    username,                              // authenticated username
    DateTime.Now,                          // issueDate
    DateTime.Now.AddMinutes(30),           // expiryDate
    isPersistent,                          // true to persist across browser sessions
    userData,                              // can be used to store additional user data
    FormsAuthentication.FormsCookiePath);  // the path for the cookie

  // Encrypt the ticket using the machine key
  string encryptedTicket = FormsAuthentication.Encrypt(ticket);

  // Add the cookie to the request to save it
  HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
  cookie.HttpOnly = true; 
  Response.Cookies.Add(cookie);

  // Your redirect logic
  Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}

我不知道你为什么要在这里做一些自定义的事情.如果您想更改用户数据存储位置和用户身份验证方式的实现,那么最好创建自定义 MembershipProvider.滚动您自己的解决方案并弄乱身份验证 cookie 意味着很可能会在您的软件中引入安全漏洞.

I'm not sure why you would want to do something custom here. If you want to change the implementation of where user data is stored and how users authenticate then it's best practice to create a custom MembershipProvider. Rolling your own solution and messing with the authentication cookie means a high probability of introducing security holes in your software.

我不明白你的第 2 部分.如果你想让用户返回到他们在被退回登录时试图访问的页面,你只需要调用 FormsAuthentication.GetRedirectUrl.如果不在这里做任何你想做的事,如果你愿意,重定向到配置中存储的 url.

I don't understand your part 2. You only need to call FormsAuthentication.GetRedirectUrl if you want to return users to the page they were trying to access when they got bounced to login. If not do whatever you want here, redirect to a url stored in the configuration if you want.

要读取 FormsAuthentication cookie,通常您会在 HttpModule 或 Global.asax 中挂钩 AuthenticateRequest 事件并设置用户 IPrinciple 上下文.

To read the FormsAuthentication cookie, normally you would hook the AuthenticateRequest event in a HttpModule or the Global.asax and set up the user IPrinciple context.

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    if(authCookie != null)
    {
        //Extract the forms authentication cookie
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

        // If caching roles in userData field then extract
        string[] roles = authTicket.UserData.Split(new char[]{'|'});

        // Create the IIdentity instance
        IIdentity id = new FormsIdentity( authTicket );

        // Create the IPrinciple instance
        IPrincipal principal = new GenericPrincipal(id, roles);

        // Set the context user 
        Context.User = principal;
    }
}

这篇关于如何手动创建身份验证 cookie 而不是默认方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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