ASP .NET安全使用SQL Compact 4.0管理用户

时间:2013-06-22 10:48:41

标签: asp.net security sql-server-ce

我发现这个伟大的网站谈论如何使用SQL Compact for Roles,Membership等...它就像一个魅力。 http://sqlcemembership.codeplex.com

问题是该示例缺少应用程序中Roles和Membership文件夹的代码文件。我找到了这些代码文件可用的其他示例,但它们是为SQL Server Express编写的。以下是一个示例:http://www.asp.net/web-forms/tutorials/security/roles/role-based-authorization-cs

我试过编辑这些,但它们只是不起作用。有没有人拥有访问SQL Compact的角色和成员资格文件夹的示例?我真的不想在这里重新发明这个轮子,并且已经在这方面工作了一个多星期。

我还直接通过电子邮件发送了ErikEJ(sqlcemembership文件的开发者),因为我确信其他人也有同样的问题。我不喜欢双重发帖,因为我在ExpertsExchange上发布了这个帖子,但是ErikEJ要求将它发布在这里。没问题。

更新......我似乎找到了错误的来源。如果代码引用标准安全项,那么它可以正常工作。但是,如果您尝试使用sql语句,则它不起作用。在下面的代码中,它在sql连接上出错。不知道如何解决。我认为这与使用SqlMembershipProvider有关,但不太确定。

using System;
using System.Collections;
using System.Configuration;

using System.Data.SqlServerCe;

using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

// Classes from the following namespaces are used in the code below
using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.Web.Configuration;
using System.Data.SqlClient;


public partial class Administration_UserInformation : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // If querystring value is missing, send the user to ManageUsers.aspx
            string userName = Request.QueryString["user"];
            if (string.IsNullOrEmpty(userName))
                Response.Redirect("ManageUsers.aspx");


            // Get information about this user
            MembershipUser usr = Membership.GetUser(userName);
            if (usr == null)
                Response.Redirect("ManageUsers.aspx");

            UserNameLabel.Text = usr.UserName;
            CreationDateLabel.Text = usr.CreationDate.ToShortDateString();
            LastPasswordChangedDateLabel.Text = usr.LastPasswordChangedDate.ToShortDateString();
        }
    }

    protected void CancelUpdate_Click(object sender, EventArgs e)
    {
        // Return the user to ManageUsers.aspx
        Response.Redirect("ManageUsers.aspx");
    }

    protected void UpdateUser_Click(object sender, EventArgs e)
    {
        // Update the user information as needed...
        if (!Page.IsValid)
            return;

        string userName = Request.QueryString["user"];

        // Did the user supply a new password?
        if (NewPassword1.Text.Length > 0)
        {
            if (ValidPassword(NewPassword1.Text))
            {
                SqlMembershipProvider sqlProvider = Membership.Provider as SqlMembershipProvider;

                // Invoke the aspnet_Membership_SetPassword sproc
                using (SqlCeConnection myConnection = new SqlCeConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
                {
                    myConnection.Open();        // Open the connection

                    // Get the salt for this user
                    string salt = null;
                    SqlCeCommand myGetSaltCommand = new SqlCeCommand("aspnet_Membership_GetPasswordWithFormat", myConnection);
                    myGetSaltCommand.CommandType = CommandType.StoredProcedure;

                    // Add the in parameters
                    myGetSaltCommand.Parameters.AddWithValue("@ApplicationName", Membership.ApplicationName);
                    myGetSaltCommand.Parameters.AddWithValue("@UserName", userName);
                    myGetSaltCommand.Parameters.AddWithValue("@UpdateLastLoginActivityDate", false);
                    myGetSaltCommand.Parameters.AddWithValue("@CurrentTimeUtc", DateTime.UtcNow);

                    // Retrieve the salt
                    SqlCeDataReader mySaltReader = myGetSaltCommand.ExecuteReader(CommandBehavior.SingleRow);
                    if (mySaltReader.Read())
                        salt = mySaltReader.GetString(2);       // Read in the password salt
                    else
                        // No information for user account!
                        throw new ApplicationException("User account not found in Membership...");
                    mySaltReader.Close();

                    // Encode the password
                    object encodedPassword = EncodePassword(NewPassword1.Text, salt);


                    // Change the user's password
                    SqlCeCommand mySetPasswordCommand = new SqlCeCommand("aspnet_Membership_SetPassword", myConnection);
                    mySetPasswordCommand.CommandType = CommandType.StoredProcedure;

                    // Add the in parameters
                    mySetPasswordCommand.Parameters.AddWithValue("@ApplicationName", Membership.ApplicationName);
                    mySetPasswordCommand.Parameters.AddWithValue("@UserName", userName);
                    mySetPasswordCommand.Parameters.AddWithValue("@NewPassword", encodedPassword);
                    mySetPasswordCommand.Parameters.AddWithValue("@PasswordSalt", salt);
                    mySetPasswordCommand.Parameters.AddWithValue("@PasswordFormat", (int)sqlProvider.PasswordFormat);
                    mySetPasswordCommand.Parameters.AddWithValue("@CurrentTimeUtc", DateTime.UtcNow);

                    // Update the user's password
                    mySetPasswordCommand.ExecuteNonQuery();

                    StatusMessage.Text = "The password has been updated...";

                    myConnection.Close();   // Close the connection
                }
            }
        }
    }

    private bool ValidPassword(string password)
    {
        // Ensure that the password is not too long or too short
        if (password.Length > 128)
        {
            StatusMessage.Text = "The password cannot exceed 128 characters.";
            return false;
        }
        else if (password.Length < Membership.MinRequiredPasswordLength)
        {
            StatusMessage.Text = string.Format("The password must contain at least {0} characters.", Membership.MinRequiredPasswordLength);
            return false;
        }

        // Determine how many non-alphanumeric characters are in the password
        int nonAlphanumericCharacters = 0;
        for (int i = 0; i < password.Length; i++)
            if (!char.IsLetterOrDigit(password, i))
                nonAlphanumericCharacters++;

        if (nonAlphanumericCharacters < Membership.MinRequiredNonAlphanumericCharacters)
        {
            StatusMessage.Text = string.Format("The password must contain at least {0} non-alphanumeric characters.", Membership.MinRequiredNonAlphanumericCharacters);
            return false;
        }

        // Check the PasswordStrengthRegularExpression, if specified
        if (!string.IsNullOrEmpty(Membership.PasswordStrengthRegularExpression))
        {
            if (!Regex.IsMatch(password, Membership.PasswordStrengthRegularExpression))
            {
                StatusMessage.Text = "The password does not meet the necessary strength requirements.";
                return false;
            }
        }

        // If we get this far, the password is valid
        return true;
    }

    private object EncodePassword(string password, string salt)
    {
        // Determine how the password is to be formatted
        SqlMembershipProvider sqlProvider = Membership.Provider as SqlMembershipProvider;

        // If it's Clear, just return password
        if (sqlProvider.PasswordFormat == MembershipPasswordFormat.Clear)
            return password;

        // Create the byte arrays to hold the encoded passwords
        byte[] bytes = Encoding.Unicode.GetBytes(password);
        byte[] src = Convert.FromBase64String(salt);
        byte[] dst = new byte[src.Length + bytes.Length];

        // Copy the src and bytes arrays to the dst array
        System.Buffer.BlockCopy(src, 0, dst, 0, src.Length);
        System.Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);

        if (sqlProvider.PasswordFormat == MembershipPasswordFormat.Hashed)
        {
            // We need to hash the password
            HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType);
            return Convert.ToBase64String(algorithm.ComputeHash(dst));
        }
        else
        {
            // TODO: Handle encoded passwords
            throw new ApplicationException("TODO: Handle encoded passwords...");
        }
    }
}

0 个答案:

没有答案