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

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

问题描述

使用 FormsAuthentication 我们写code是这样的:

 如果(IsValidUser())
 {
      FormsAuthentication.SetAuthCookie(用户名,createPersistentCookie);
      FormsAuthentication.RedirectFromLoginPage(用户名,createPersistentCookie);
 }


  1. 我如何可以手动创建一个身份验证cookie,而不是写 FormsAuthentication.SetAuthCookie(用户名,createPersistentCookie)


  2. 我怎么能存储从登录页面重定向URL字符串中的变量,而不是写 FormsAuthentication.RedirectFromLoginPage(用户名,createPersistentCookie)



解决方案

在这里你去。 ASP.NET需要照顾这对你,当你使用内置到FormsAuthentication的更高层次的方法,但在较低水平,这是为了创建一个身份验证Cookie。

 如果(Membership.ValidateUser(用户名,密码))
{
  //有时用于保持用户角色
  字符串用户数据=的string.join(|,GetCustomUserRoles());  的FormsAuthenticationTicket票=新的FormsAuthenticationTicket(
    1,//票版
    用户名,//认证的用户名
    DateTime.Now,// issueDate
    DateTime.Now.AddMinutes(30),// expiryDate
    isPersistent //真正的跨浏览器会话持续存在
    用户数据,//可以用来存储附加用户数据
    FormsAuthentication.FormsCookiePath); // Cookie的路径  //使用机器密钥加密票
  字符串的encryptedTicket = FormsAuthentication.Encrypt(票);  //饼干添加到保存它的要求
  的HttpCookie饼干=新的HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket中);
  cookie.HttpOnly = TRUE;
  Response.Cookies.Add(饼干);  //你的重定向逻辑
  的Response.Redirect(FormsAuthentication.GetRedirectUrl(用户名,isPersistent));
}

我不知道你为什么会想定制这里做一些事情。如果您想要更改用户数据存储以及用户如何进行身份验证的实现,那么它是创建一个自定义的MembershipProvider 最佳实践。滚动自己的解决方案,并与身份验证cookie搞乱指在软件中引入安全漏洞的可能性很大。

我不明白你的一部分2.如果你想使用户返回他们试图访问时,他们得到了反弹登录页面,您只需要调用FormsAuthentication.GetRedirectUrl。如果你想在这里不管不行,重定向到存储在配置如果你想要一个网址。

要阅读FormsAuthentication饼干,通常你会在一个的HttpModule或在Global.asax勾的AuthenticateRequest 事件,并建立用户 IPrinciple 上下文。

 保护无效Application_AuthenticateRequest(对象发件人,EventArgs的发送)
{
    的HttpCookie authCookie = Request.Cookies时[FormsAuthentication.FormsCookieName]
    如果(authCookie!= NULL)
    {
        //提取窗体身份验证cookie
        的FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);        //如果用户数据缓存领域的角色然后解压
        字符串[] =角色authTicket.UserData.Split(新的char [] {'|'});        //创建IIdentity的实例
        IIdentity的ID =新FormsIdentity(authTicket);        //创建IPrinciple实例
        主要的IPrincipal =新的GenericPrincipal(ID,角色);        //设置用户环境
        Context.User =本金;
    }
}

Using FormsAuthentication we write code like this:

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

  1. How can I manually create a authentication cookie instead of writing FormsAuthentication.SetAuthCookie(userName, createPersistentCookie)?

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

解决方案

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));
}

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.

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.

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天全站免登陆