членство в asp.net api - контроль входа в систему (где выполняется код?) - PullRequest
1 голос
/ 02 января 2012

вот страница входа, созданная для вас, когда вы создаете приложение по умолчанию в asp.net, и я пытаюсь понять, где на самом деле код проверяет / аутентифицирует идентификатор пользователя и пароль ?, я не нашел никакого кодакод, кроме этого: где он проверяет имя пользователя и пароль?

я вижу CommandName="Login", но не могу найти код ....

 protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        }
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Log In
    </h2>
    <p>
        Please enter your username and password.
        <asp:HyperLink ID="RegisterHyperLink" runat="server" EnableViewState="false">Register</asp:HyperLink> if you don't have an account.
    </p>
    <asp:Login ID="LoginUser" runat="server" EnableViewState="false" RenderOuterTable="false">
        <LayoutTemplate>
            <span class="failureNotification">
                <asp:Literal ID="FailureText" runat="server"></asp:Literal>
            </span>
            <asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="failureNotification" 
                 ValidationGroup="LoginUserValidationGroup"/>
            <div class="accountInfo">
                <fieldset class="login">
                    <legend>Account Information</legend>
                    <p>
                        <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label>
                        <asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" 
                             CssClass="failureNotification" ErrorMessage="User Name is required." ToolTip="User Name is required." 
                             ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
                    </p>
                    <p>
                        <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
                        <asp:TextBox ID="Password" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" 
                             CssClass="failureNotification" ErrorMessage="Password is required." ToolTip="Password is required." 
                             ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator>
                    </p>
                    <p>
                        <asp:CheckBox ID="RememberMe" runat="server"/>
                        <asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label>
                    </p>
                </fieldset>
                <p class="submitButton">
                    <asp:Button ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="LoginUserValidationGroup"/>
                </p>
            </div>
        </LayoutTemplate>
    </asp:Login>
</asp:Content>

Ответы [ 4 ]

2 голосов
/ 02 января 2012

Орудие работает по методу Login.OnBubbleEvent.Для получения дополнительной информации см. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.onbubbleevent.aspx

0 голосов
/ 07 января 2015

Найдите в своем коде класс, который наследует: MembershipProvider

У меня есть этот класс

public class TsMembershiProvider : MembershipProvider
{
    private Dictionary<string, MembershipUser> _Users;

    // MembershipProvider Properties
    public override string ApplicationName
    {
        get { throw new NotSupportedException(); }
        set { throw new NotSupportedException(); }
    }

    public override bool EnablePasswordRetrieval
    {
        get { return true; }
    }

    public override bool EnablePasswordReset
    {
        get { return true; }
    }

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

    public override int MinRequiredNonAlphanumericCharacters
    {
        get { return 2; }
    }

    public override int MinRequiredPasswordLength
    {
        get { return 5; }
    }

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

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

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

    public override bool RequiresQuestionAndAnswer
    {
        get { return false; }
    }

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

    // MembershipProvider Methods
    public override void Initialize(string name, NameValueCollection config)
    {
        // Verify that config isn't null
        if (config == null)
            throw new ArgumentNullException("config");

        // Assign the provider a default name if it doesn't have one
        if (String.IsNullOrEmpty(name))
            name = "TsMembershipProvider";

        // Add a default "description" attribute to config if the
        // attribute doesn't exist or is empty
        if (string.IsNullOrEmpty(config["description"]))
        {

            config.Add("description", "Membership provider");
        }

        // Call the base class's Initialize method
        base.Initialize(name, config);

        // Throw an exception if unrecognized attributes remain
        if (config.Count > 0)
        {
            string attr = config.GetKey(0);
            if (!String.IsNullOrEmpty(attr))
                throw new ProviderException
                    ("Unrecognized attribute: " + attr);
        }
    }

    public override bool ValidateUser(string username, string password)
    {
        if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            return false;

        SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.ConnString, "spc_UserAuthorization", username, password);

        bool ret = dr.HasRows;

        return ret;
    }

    public override MembershipUser GetUser(string username, bool userIsOnline)
    {
        // Note: This implementation ignores userIsOnline

        // Validate input parameters
        if (String.IsNullOrEmpty(username))
            return null;

        // Retrieve the user from the database

        MembershipUser user = MU(username, userIsOnline); //userIsOnline = AltEmail - gets alternative email (hvb)
        return user;
    }

    public override MembershipUserCollection GetAllUsers(int pageIndex,
        int pageSize, out int totalRecords)
    {
        // Note: This implementation ignores pageIndex and pageSize,
        // and it doesn't sort the MembershipUser objects returned

        // Make sure the data source has been loaded
        ReadMembershipDataStore();

        MembershipUserCollection users =
            new MembershipUserCollection();

        foreach (KeyValuePair<string, MembershipUser> pair in _Users)
            users.Add(pair.Value);

        totalRecords = users.Count;
        return users;
    }

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

    public override bool ChangePassword(string username, string oldPassword, string newPassword)
    {
        MembershipUser u = Membership.GetUser(username);
        if (u == null || oldPassword != u.GetPassword())
        {
            return false;
        }

        if (newPassword.Length < MinRequiredPasswordLength)
        {
            return false;
        }

        CharEnumerator chars = newPassword.GetEnumerator();
        int nr = 0;
        while (chars.MoveNext())
        {
            if (!Char.IsLetterOrDigit(chars.Current))
                nr++;
        }

        if (MinRequiredNonAlphanumericCharacters < nr)
        {
            return false;
        }

        // CALL TO SQL TO CHANGE PASSWORD
        return true;
    }

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

    public override MembershipUser CreateUser(string username,
        string password, string email, string passwordQuestion,
        string passwordAnswer, bool isApproved, object providerUserKey,
        out MembershipCreateStatus status)
    {
        //SOME CODE i DON'T WHANT YOU TO SEE :)
        string strStatus = "";
        string strUserid = "";

        status = (MembershipCreateStatus)Enum.Parse(typeof(MembershipCreateStatus), strStatus, true);

        if (status == MembershipCreateStatus.Success)
        {
            int userid = 0;
            try
            {
                userid = Convert.ToInt32(strUserid);
            }
            catch
            {
                status = MembershipCreateStatus.ProviderError;
            }

            MembershipUser mu = MU(username);
            return mu;
        }
        else
        {
            return null;
        }
    }

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

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

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

    public override string GetPassword(string username, string answer)
    {
        //GET PASS FROM SQL
        return "";
    }

    public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
    {
        string UserName = (string)SqlHelper.ExecuteScalar(SqlHelper.ConnString, CommandType.Text, "select .... WHERE UserID = " + providerUserKey.ToString());
        MembershipUser m = MU(UserName, userIsOnline);
        return m;
    }

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

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

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

    // Helper method
    private void ReadMembershipDataStore()
    {
        lock (this)
        {
        }
    }

    private MembershipUser MU(string UserName)
    {
        return MU(UserName, false);
    }

    private MembershipUser MU(string UserName, bool isOnline)
    {
        MembershipUser user = null;

        //SOME CODE

        return user;
    }
}
0 голосов
/ 23 октября 2012

Login.OnBubbleEvent, как отметил Эдвард Чжу, является правильным ответом. Для дальнейшего понимания происходящего здесь приведен фрагмент кода из System.Web.dll для события (с использованием Reflector.exe)

protected override bool OnBubbleEvent(object source, EventArgs e)
{
    bool flag = false;
    if (e is CommandEventArgs)
    {
        CommandEventArgs args = (CommandEventArgs) e;
        if (string.Equals(args.CommandName, LoginButtonCommandName, StringComparison.OrdinalIgnoreCase))
        {
            this.AttemptLogin();
            flag = true;
        }
    }
    return flag;
}

LoginButtonCommandName по умолчанию имеет значение «Login»

Pawel

0 голосов
/ 02 января 2012

Вы смотрели в коде файла? Это будет похоже на login.aspx.cs.

...