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

 if (IsValidUser())
 {
      FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
      FormsAuthentication.RedirectFromLoginPage(userName, createPersistentCookie); 
 }
  1. 如何手动创建身份验证cookie而不是编写FormsAuthentication.SetAuthCookie(userName, createPersistentCookie)

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

推荐答案

干得好.ASP.当您使用FormsAuthentication中内置的更高级别方法时,NET会为您解决这一问题,但在较低级别上,创建身份验证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意味着很有可能在您的软件中引入安全漏洞.

我不理解您的第2部分.如果您希望将用户返回到他们被弹出登录时试图访问的页面,则只需调用FormsAuthentication.GetRedirectUrl.如果您不想在这里执行任何操作,请根据需要重定向到存储在配置中的URL.

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

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

Asp.net相关问答推荐

内容根路径在 .NET 6 中如何工作?

从 Request.Url.AbsolutePath 获取应用相对 url

在正则表达式中允许 -(破折号)

在 ASP.NET 中访问没有值的查询字符串参数

任何人都有解决 Internet Explorer 上剩余 n 项问题的 idea 吗?

ASP.NET web api 无法获取 application/x-www-form-urlencoded HTTP POST

业务线应用程序:F# 会让我的生活变得轻松吗?

如何在txt文件中保存异常?

在 Blazor 中 Select 框绑定

我应该如何在类和应用层之间传递数据?

如何在同一解决方案中从 MVC 项目调试 Web API 项目

无法序列化会话状态

在asp.net控件之间动态添加

如何从 Web API 应用程序返回 PDF

如何使div按钮提交其所在的表单?

.NET 4.0 中的自定义 MembershipProvider

ASP.NET 应用程序状态与静态对象

通过 CultureInfo 格式化字符串

ASP.NET 网格视图与列表视图

.Net 上是否有 URL 验证器?