سؤال

بالنسبة لتطبيق ويب ، قمت بتبديل من استخدام عضوية ASP.NET إلى استخدام نظام تسجيل الدخول الخاص بي والذي يقوم بشيء كهذا فقط لتمييز المستخدم كما سجل الدخول:

Session["UserId"] = User.Id

هل من الممكن تخزين معرف المستخدم في ملف تعريف الارتباط ASPXAUTH ، مما يؤدي إلى تشفيره ، بدلاً من استخدام الجلسة القياسية؟

الهدف من ذلك هو أن تدوم الدولة المسجلة لفترة أطول من الجلسة والبقاء على قيد الحياة في كل من المتصفح وإعادة تشغيل الخادم.

هل كانت مفيدة؟

المحلول

تحديث: كانت الإجابة الأصلية المقدمة بمشروع يستخدم العضوية Provider وتم شرحه في الإجابة نفسها. أنا ، السائل ، لا أستخدمه ، لذلك كانت الإجابة على مشكلتي مختلفة قليلاً ولكن مستخرجة من هذه الإجابة. أضع إجابتي في الأسفل لأي شخص يهتم ويترك الحرفي الأصلي ، لأنه يحتوي على الكثير من القيمة.


نعم ، يمكنك استخدام FormsAuthentication لاستراتيجيتك الخاصة. وعلى الرغم من أن هيكل ASP.NET DB لا يناسبك ، يمكنك تقديم تطبيق بسيط من العضوية Provider للسماح باستخدام البنية التحتية للعضوية. هاتان الوظيفيتان غير متزوجتين ، لذا يمكنك أن تقرر ما يناسبك.

مع الأخذ في الاعتبار سؤالك وبعض التعليقات ، إليك مثال قابل للتشغيل على مدى بساطة الاستفادة من نموذج المزود دون أن تتزوج من التطبيقات الافتراضية ومخططات DB.

استخدام Forms Auth لأغراضك أمر بسيط. تحتاج فقط إلى توفير المصادقة وتعيين التذكرة الخاصة بك (ملف تعريف الارتباط).

استخدام العضوية المخصصة بسيطة تقريبا. يمكنك تنفيذ القليل من الموفر أو بقدر ما تحتاجه لدعم ميزات البنية التحتية لـ ASP.NET التي ترغب في توظيفها.

على سبيل المثال ، في العينة أدناه ، أظهر أنه في عملية تسجيل الدخول ، يمكنك ببساطة التعامل مع حدث على عنصر التحكم في تسجيل الدخول للتحقق من صحة بيانات الاعتماد وتعيين التذكرة. فعله.

لكنني سأوضح أيضًا كيف يمكن أن يؤدي الاستفادة من نموذج المزود وتنفيذ مزود العضوية المخصصة إلى رمز نظيف أقوى. بينما نحن في مزود العضوية المخصص ، أقوم بتنفيذ الحد الأدنى اللازم لدعم استخدام النظام الفرعي للعضوية لتوفير وصول سهل إلى بيانات ميثى المستخدم دون الحاجة إلى كتابة البنية التحتية الخاصة بك.

ما عليك سوى إسقاط هذه الملفات في مشروع فارغ.

web.config


<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true"/>
    <authorization>
      <deny users="?"/>
    </authorization>
    <authentication mode="Forms"/>
    <!-- 
    optional but recommended. reusing the membership infrastructure via custom provider divorces 
    you from the aspnetdb but retains all of the baked in infrastructure which you do not have to 
    develop or maintain
    -->
    <membership defaultProvider="mine">
      <providers>
        <add name="mine" type="CustomAuthRepurposingFormsAuth.MyMembershipProvider"/>
      </providers>
    </membership>
  </system.web>
</configuration>

Site1.master


<%@ Master Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:LoginName ID="LoginName1" runat="server" />
        <asp:LoginStatus ID="LoginStatus1" runat="server" />
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

login.aspx


<%@ Page Title="" Language="C#" MasterPageFile="Site1.Master" %>
<%@ Import Namespace="CustomAuthRepurposingFormsAuth" %>
<script runat="server">

    /*
     * If you don't want to use a custom membership provider to authenticate
     * simply place your logic in the login control's handler and remove the 
     * membership element from config. It would have to take a very very 
     * compelling edge case to motivate me to not use a custom membership provider.
     * 
     */

    //protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    //{
    //    // perform mindbendingly complex authentication logic
    //    e.Authenticated = Login1.UserName == Login1.Password;
    //}


    /*
     * set your cookie and you are golden
     */
    void Authenticated(object sender, EventArgs e)
    {
        // this is an arbitrary data slot you can use for ???
        // keep cookie size in mind when using it.
        string userData = "arbitraryData";
        Response.Cookies.Add(TicketHelper.CreateAuthCookie(Login1.UserName, userData, Login1.RememberMeSet /*persistent cookie*/));
    }

</script>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:Login ID="Login1" runat="server" OnLoggedIn="Authenticated" >
    </asp:Login>
    username==password==authenticated. <br />e.g.: uid: me, pwd:me
</asp:Content>

default.aspx


<%@ Page Title="" Language="C#" MasterPageFile="Site1.Master" %>

<%@ Import Namespace="System.Security.Principal" %>
<%@ Import Namespace="CustomAuthRepurposingFormsAuth" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        /*
         * you get this for free from asp.net
         */

        HttpContext page = HttpContext.Current;

        IIdentity identity = page.User.Identity;
        string username = identity.Name;
        bool authenticate = identity.IsAuthenticated;
        // or use the Request.IsAuthenticated convenience accessor

        /* 
         * you get this really cheap from forms auth
         * 
         * cost: validating credentials and setting your own ticket
         */

        // this page is protected by formsauth so the identity will actually 
        // be a FormsIdentity and you can get at the user data.
        // UserData is an appropriate place to store _small_ amounts of data
        var fIdent = (FormsIdentity)identity;
        string userData = fIdent.Ticket.UserData;


        // so, using only forms auth this is what you have to work with
        LblAuthenticated.Text = page.User.Identity.IsAuthenticated.ToString();
        LblUserId.Text = page.User.Identity.Name;
        LblUserData.Text = userData;

        /* 
         * this is an example of using a custom membership provider and subclassing the 
         * MembershipUser class to take advantage of the established mature infrastructure
         * 
         * this is entirely optional, you can delete the Membership section in web.config 
         * and delete MyMembershipProvider and MyMembershipUser and just use the authentication.
         * 
         */

        // get the custom field
        string myCustomField = ((MyMembershipUser)Membership.GetUser()).MyCustomField;
        LblMembership.Text = myCustomField;
    }        
</script>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <br />
    Authenticated:<asp:Label ID="LblAuthenticated" runat="server" Text=""></asp:Label><br />
    UserId:<asp:Label ID="LblUserId" runat="server" Text=""></asp:Label><br />
    UserData:<asp:Label ID="LblUserData" runat="server" Text=""></asp:Label><br />
    <br />
    Membership User Custom Field:<asp:Label ID="LblMembership" runat="server" Text=""></asp:Label><br />
</asp:Content>

customauthclasses.cs


using System;
using System.Web;
using System.Web.Security;

namespace CustomAuthRepurposingFormsAuth
{
    public static class TicketHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="userData">be mindful of the cookie size or you will be chasing ghosts</param>
        /// <param name="persistent"></param>
        /// <returns></returns>
        public static HttpCookie CreateAuthCookie(string userName, string userData, bool persistent)
        {
            DateTime issued = DateTime.Now;
            // formsAuth does not expose timeout!? have to hack around the
            // spoiled parts and keep moving..
            HttpCookie fooCookie = FormsAuthentication.GetAuthCookie("foo", true);
            int formsTimeout = Convert.ToInt32((fooCookie.Expires - DateTime.Now).TotalMinutes);

            DateTime expiration = DateTime.Now.AddMinutes(formsTimeout);
            string cookiePath = FormsAuthentication.FormsCookiePath;

            var ticket = new FormsAuthenticationTicket(0, userName, issued, expiration, true, userData, cookiePath);
            return CreateAuthCookie(ticket, expiration, persistent);
        }

        public static HttpCookie CreateAuthCookie(FormsAuthenticationTicket ticket, DateTime expiration, bool persistent)
        {
            string creamyFilling = FormsAuthentication.Encrypt(ticket);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, creamyFilling)
                             {
                                 Domain = FormsAuthentication.CookieDomain,
                                 Path = FormsAuthentication.FormsCookiePath
                             };
            if (persistent)
            {
                cookie.Expires = expiration;
            }

            return cookie;
        }
    }

    /// <summary>
    /// This is an example of inheriting MembershipUser to
    /// expose arbitrary data that may be associated with your
    /// user implementation.
    /// 
    /// You may repurpose existing fields on the base and add your own.
    /// Just perform a cast on the MembershipUser returned from your
    /// MembershipProvider implementation
    /// </summary>
    public class MyMembershipUser : MembershipUser
    {
        public MyMembershipUser(string providerName, string name, object providerUserKey, string email,
                                string passwordQuestion, string comment, bool isApproved, bool isLockedOut,
                                DateTime creationDate, DateTime lastLoginDate, DateTime lastActivityDate,
                                DateTime lastPasswordChangedDate, DateTime lastLockoutDate)
            : base(
                providerName, name, providerUserKey, email, passwordQuestion, comment, isApproved, isLockedOut,
                creationDate, lastLoginDate, lastActivityDate, lastPasswordChangedDate, lastLockoutDate)
        {
        }

        protected MyMembershipUser()
        {
        }

        // e.g. no desire to use Profile, can just add data
        // say, from a flat record containing all user data
        public string MyCustomField { get; set; }
    }

    /// <summary>
    /// At the most basic level, implementing a MembershipProvider allows you to
    /// reuse established framework code. In this case, we just provide services
    /// for the Login control and user identification via Membership subsystem.
    /// </summary>
    public class MyMembershipProvider : MembershipProvider
    {
        #region Minimum implementation in order to use established authentication and identification infrastructure

        /// <summary>
        /// You can just do this in the login logic if you do not want
        /// leverage framework for membership user access
        /// </summary>
        public override bool ValidateUser(string username, string password)
        {
            return username == password;
        }


        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            /*
             * Simulate going to the DB to get the data
             */

            // membership user non nullable fields, repurpose or use
            // implied null value e.g DateTime.MinValue;

            var createdDate = new DateTime(2009, 10, 25);
            var lastLogin = new DateTime(2009, 10, 25);
            var lastActivity = new DateTime(2009, 10, 25);
            var lastPasswordChange = new DateTime(2009, 10, 25);
            var lastLockoutDate = new DateTime(2009, 10, 25);

            object providerUserKey = 3948; // e.g. user primary key. 


            /*
             * build your custom user and send it back to asp.net
             */

            // need to use the full constructor to set the username and key
            var user = new MyMembershipUser(Name, username, providerUserKey, null, null, null, true, false, createdDate,
                                            lastLogin,
                                            lastActivity, lastPasswordChange, lastLockoutDate)
                           {
                               MyCustomField = "Hey"
                           };

            return user;
        }

        #endregion

        #region Optional implementations depending on the framework features you would like to leverage.

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override string ApplicationName
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }


        public override MembershipUser CreateUser(string username, string password, string email,
                                                  string passwordQuestion, string passwordAnswer, bool isApproved,
                                                  object providerUserKey, out MembershipCreateStatus status)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password,
                                                             string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            throw new NotImplementedException();
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }


        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize,
                                                                 out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize,
                                                                  out int totalRecords)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

يستخدم الحل بالفعل (في مشروع ASP.NET MVC باستخدام OpenID):

لديّ حساب حساب أستخدمه لتسجيل الدخول والخارج وهذه الطرق موجودة.

#region Methods to log in a user.
/// <summary>
/// Create the auth cookie in the same way it is created my ASP.NET Membership system, hopefully lasting for more than 20 minutes.
/// 
/// For more information check out http://stackoverflow.com/questions/2122831/is-it-possible-to-use-aspxauth-for-my-own-logging-system
/// </summary>
/// <param name="userId">Id of the user that is logged in</param>
/// <returns>Cookie created to mark the user as authenticated.</returns>
private static HttpCookie CreateAuthCookie(int userId) {
  DateTime issued = DateTime.Now;
  // formsAuth does not expose timeout!? have to hack around the spoiled parts and keep moving..
  HttpCookie fooCookie = FormsAuthentication.GetAuthCookie("foo", true);
  int formsTimeout = Convert.ToInt32((fooCookie.Expires - DateTime.Now).TotalMinutes);

  DateTime expiration = DateTime.Now.AddMinutes(formsTimeout);

  var ticket = new FormsAuthenticationTicket(0, userId.ToString(), issued, expiration, true, "", FormsAuthentication.FormsCookiePath);
  return CreateAuthCookie(ticket, expiration, true);
}

/// <summary>
/// Create an auth cookie with the ticket data.
/// </summary>
/// <param name="ticket">Ticket containing the data to mark a user as authenticated.</param>
/// <param name="expiration">Expriation date for the cookie.</param>
/// <param name="persistent">Whether it's persistent or not.</param>
/// <returns>Cookie created to mark the user as authenticated.</returns>
private static HttpCookie CreateAuthCookie(FormsAuthenticationTicket ticket, DateTime expiration, bool persistent) {
  string encryptedAuthData = FormsAuthentication.Encrypt(ticket);
  var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedAuthData) {
    Domain = FormsAuthentication.CookieDomain,
    Path = FormsAuthentication.FormsCookiePath
  };
  if (persistent) {
    cookie.Expires = expiration;
  }

  return cookie;
}

/// <summary>
/// Expire the authentication cookie effectively loging out a user.
/// </summary>
private void ExpireAuthCookie() {
  var cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
  cookie.Expires = DateTime.Now.AddDays(-1);
  Response.Cookies.Add(cookie);
}
#endregion

نصائح أخرى

يفصل ملف تعريف الارتباط Aspxauth رمز المصادقة عن الجلسة تمامًا ، وهو أحد الأسباب التي يتم استخدامها. إذا كان نظامك يستخدم الجلسة ، فهذا يتعارض حقًا مع النماذج التي تحاول مصادقة القيام بها.

إذا كان كل شيء في جلسة ، فأنت لا تحتاج حقًا إلى تذكرة المصادقة على الإطلاق ، على افتراض أن الجلسة مضمونة.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top