24. februar 2006 - 23:24Der er
14 kommentarer og 1 løsning
User/Role managment sammen med egen SQL
Jeg er ved at lave en web-applikation i .NET 2.0, som skal fungere som noget opgave styring...
Jeg har opbygget db'en i MSSQL.
.NET 2.0 har en indbygget User/role managment system som jeg flere steder har læst skulle være tæmmelig godt?
Mit problem, opstår i at den indbyggede user/role managment ikke helt passer til min applikation (Jeg kunne godt tænke mig at gemme nogle andre data omkring brugerne end dem der er standard)
Nå men det som det hele nok bunder ud i er: Kan jeg drage nytte af den indbyggede user/role managment samtidigt med at jeg gemmer brugerinformationerne i min SQL, eller er det bedre at lavet sit eget user/role managment?
Du må meget gerne vise et eksempel på hvordan du bruger custom providers. Det tror jeg kunne hjælpe mig meget =)
Da jeg læste artiklen du linker til faldt jeg over at der er krævet et skema?
By default the developer is directed to using a local SQLEXPRESS database, however they can easily redirect the default SQL based providers to use a different database via a connection string. And it is simplicity itself to use the aspnet_regsql tool to create a new (or update an existing) database with the database schema required.
Betyder dette at man foreksempel SKAL benytte sikkerhedsspørgsmål og sikkerhedssvar? For det syntes jeg er noget af det mest irreterende der findes... hehe
using System.Web.Security; using System.Configuration.Provider; using System.Collections.Specialized; using System; using System.Data; using System.Configuration; using System.Diagnostics; using System.Web; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Web.Configuration;
/// <summary> /// Summary description for TIMemberShipProvider /// </summary> public sealed class CustomMemberShipProvider : MembershipProvider { private int newPasswordLength = 2; private string eventSource = "CustomMemberShipProvider"; private string eventLog = "Application"; private string exceptionMessage = "An exception occurred. Please check the Event Log."; private string connectionString;
// // Bruges til at bestemme enkryption værdier //
private MachineKeySection machineKey;
// // hvis false vises exceptionsmeddelelsen til brugeren ellers skrives den til //eventlog //
private bool pWriteExceptionsToEventLog;
public bool WriteExceptionsToEventLog { get { return pWriteExceptionsToEventLog; } set { pWriteExceptionsToEventLog = value; } } public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "CustomMemberShipProvider";
if (String.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "CustomMemberShipProvider"); } // Initialize the abstract base class. base.Initialize(name, config);
switch (temp_format) { case "Hashed": pPasswordFormat = MembershipPasswordFormat.Hashed; break; case "Encrypted": pPasswordFormat = MembershipPasswordFormat.Encrypted; break; case "Clear": pPasswordFormat = MembershipPasswordFormat.Clear; break; default: throw new ProviderException("Password format not supported."); }
// Get encryption and decryption key information from the configuration. Configuration cfg = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath); machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey"); }
// // A helper function to retrieve config values from the configuration file. //
public override bool ChangePassword(string username, string oldPwd, string newPwd) { ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPwd, true);
OnValidatingPassword(args);
if (args.Cancel) if (args.FailureInformation != null) throw args.FailureInformation; else throw new MembershipPasswordException("Change password canceled due to new password validation failure.");
/* if (Bruger.SkiftPassword(username, newPwd)) return true; else*/ return false; }
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { throw new Exception("The method or operation is not implemented."); } public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { throw new Exception("The method or operation is not implemented."); } public override bool DeleteUser(string username, bool deleteAllRelatedData) { throw new Exception("The method or operation is not implemented."); } // // MembershipProvider.GetAllUsers //
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { throw new Exception("The method or operation is not implemented."); } // // MembershipProvider.GetNumberOfUsersOnline //
public override int GetNumberOfUsersOnline() { throw new Exception("The method or operation is not implemented."); } // // MembershipProvider.GetUser(string, bool) //
public override MembershipUser GetUser(string username, bool userIsOnline) { using (DataSet ds = Bruger.GetBruger().FindBrugerInfoMedBrugerNavn(username)) { try { DataRow dr = ds.Tables[0].Rows[0]; MembershipUser u = new MembershipUser(this.Name, username, dr["BrugerID"], dr["Email"].ToString(), "", "", true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now); return u; } catch (Exception e) { WriteToEventLog(e, "GetUser"); return null; } }
} public override MembershipUser GetUser(object providerUserKey, bool userIsOnline) { throw new Exception("The method or operation is not implemented."); } // // MembershipProvider.UnlockUser //
public override bool UnlockUser(string username) { throw new Exception("The method or operation is not implemented."); } // // MembershipProvider.GetUserNameByEmail //
public override string GetUserNameByEmail(string email) { throw new Exception("The method or operation is not implemented."); } // // MembershipProvider.ResetPassword //
public override string ResetPassword(string username, string answer) { throw new Exception("The method or operation is not implemented."); } // // MembershipProvider.UpdateUser //
public override void UpdateUser(MembershipUser user) { throw new Exception("The method or operation is not implemented."); }
public override bool ValidateUser(string username, string password) { Bruger b = Bruger.GetBruger();
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new Exception("The method or operation is not implemented."); } public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords) { throw new Exception("The method or operation is not implemented."); } public override string GetPassword(string username, string answer) { throw new Exception("The method or operation is not implemented."); } // // WriteToEventLog // A helper function that writes exception detail to the event log. Exceptions // are written to the event log as a security measure to avoid private database // details from being returned to the browser. If a method does not return a status // or boolean indicating the action succeeded or failed, a generic exception is also // thrown by the caller. //
private void WriteToEventLog(Exception e, string action) { EventLog log = new EventLog(); log.Source = eventSource; log.Log = eventLog;
string message = "An exception occurred communicating with the data source.\n\n"; message += "Action: " + action + "\n\n"; message += "Exception: " + e.ToString();
log.WriteEntry(message); }
}
alle de steder hvor der står Bruger.GetBruger() er hvor jeg bruger egne metoder.
samme gælder for role provider: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
/// <summary> /// Summary description for MyCustomRoleProvider /// </summary> public class MyCustomRoleProvider: SqlRoleProvider { public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) {
} public override void CreateRole(string roleName) { throw new Exception("The method or operation is not implemented."); } public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { throw new Exception("The method or operation is not implemented."); } public override void AddUsersToRoles(string[] usernames, string[] roleNames) { throw new Exception("The method or operation is not implemented."); } public override string ApplicationName { get { throw new Exception("The method or operation is not implemented."); } set { throw new Exception("The method or operation is not implemented."); } } public override string Description { get { throw new Exception("The method or operation is not implemented."); } } public override bool Equals(object obj) { throw new Exception("The method or operation is not implemented."); } public override string[] FindUsersInRole(string roleName, string usernameToMatch) { throw new Exception("The method or operation is not implemented."); } public override string[] GetAllRoles() { throw new Exception("The method or operation is not implemented."); } public override int GetHashCode() { throw new Exception("The method or operation is not implemented."); } public override string[] GetRolesForUser(string username) { string userdata = ""; int accesslevel = Bruger.GetBruger().HentAdgangsNiveauID(HttpUtility.HtmlEncode(username)); switch (accesslevel) { case 1: { userdata = "System"; break;
} case 2: { userdata = "Bruger"; break; } case 3: { userdata = "Bruger,Ansvarlig"; break; } case 4: { userdata = "Bruger,Ansvarlig,Administrator"; break; } } string[] roles = userdata.Split(','); return roles; } public override string[] GetUsersInRole(string roleName) { throw new Exception("The method or operation is not implemented."); } public override bool IsUserInRole(string username, string roleName) { return Bruger.GetBruger().IsUserInRole(username, roleName); } public override string Name { get { return "MyCustomRoleProvider"; } } public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { throw new Exception("The method or operation is not implemented."); } public override bool RoleExists(string roleName) { throw new Exception("The method or operation is not implemented."); } public override string ToString() { throw new Exception("The method or operation is not implemented."); } }
ja using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient;
/// <summary> /// Summary description for Bruger /// </summary> public sealed class Bruger { private static readonly Bruger instance = new Bruger(); private Bruger() { } //returnere en instans af bruger klassen public static Bruger GetBruger() { return instance; } //bruges til at godkende en brugers logind public bool Valider(string brugernavn, string password) { int rowsAffected; //parameters defineres SqlParameter[] parameters = { new SqlParameter("@BrugerNavn", SqlDbType.VarChar,50), new SqlParameter("@Password", SqlDbType.VarChar,50), new SqlParameter("@LogindGodkendt", SqlDbType.Bit) }; //parameters værdier sættes parameters[0].Value = brugernavn; parameters[1].Value = password; parameters[2].Direction = ParameterDirection.Output; try { //stored procedure afvikles DbHandler.GetDbHandler().RunProcedure("SP_Bruger_ValiderLogind",parameters,out rowsAffected); return (bool)parameters[2].Value; } catch (Exception e) {//evt fejl gemmes FejlLog.GetFejlLog().gemFejl(HttpContext.Current.Profile.GetPropertyValue("BrugerInfo.BrugerID").ToString(), e); return false; } } //bruges til at hente brugerinfo med brugernavn public DataSet FindBrugerInfoMedBrugerNavn(string brugernavn) { //parameter defineres SqlParameter[] parameters = { new SqlParameter("@BrugerNavn", SqlDbType.VarChar, 50) }; //parameters værdier sættes parameters[0].Value = brugernavn;
try { //bruger info retuneres return DbHandler.GetDbHandler().RunProcedure("SP_Bruger_HentBrugerInfoMedBrugerNavn", parameters, "DsBruger"); } catch (Exception e) { //evt fejl gemmes FejlLog.GetFejlLog().gemFejl(HttpContext.Current.Profile.GetPropertyValue("BrugerInfo.BrugerID").ToString(), e); return new DataSet(); } } //bruges til at hente en bruges email og password udfra brugernavn public void GlemtPassword(string brugernavn, out string Email, out string password) { int rowsAffected; //parametre defineres SqlParameter[] parameters = { new SqlParameter("@BrugerNavn", SqlDbType.VarChar,50), new SqlParameter("@Email", SqlDbType.VarChar,255), new SqlParameter("@Password", SqlDbType.VarChar,50) }; //parametersværdier sættes parameters[0].Value = brugernavn; parameters[1].Direction = ParameterDirection.Output; parameters[2].Direction = ParameterDirection.Output; try { //stored proce´dure afvikles DbHandler.GetDbHandler().RunProcedure("SP_Bruger_GlemtPassWord", parameters,out rowsAffected); //email og password sættes Email = parameters[1].Value.ToString(); password = parameters[2].Value.ToString(); } catch (Exception e) { Email = ""; password = ""; //evt fejl gemmes FejlLog.GetFejlLog().gemFejl(HttpContext.Current.Profile.GetPropertyValue("BrugerInfo.BrugerID").ToString(), e); } } //bruges til at returnere en brugers adgangsniveauid public int HentAdgangsNiveauID(string brugernavn) { int rowsAffected; //parametre defineres SqlParameter[] parameters = { new SqlParameter("@BrugerNavn", SqlDbType.VarChar,50), new SqlParameter("@AdgangsNiveauID", SqlDbType.Int) }; //parameterværdier sættes parameters[0].Value = brugernavn; parameters[1].Direction = ParameterDirection.Output;
try { //stored procedure afvikles DbHandler.GetDbHandler().RunProcedure("SP_Bruger_HentAdgangsNiveauID", parameters, out rowsAffected); return (int)parameters[1].Value; } catch (Exception e) { //evt fejl gemmes FejlLog.GetFejlLog().gemFejl(HttpContext.Current.Profile.GetPropertyValue("BrugerInfo.BrugerID").ToString(), e); return 0; } } //bruges til at finde ud af om en bruger er i en bestemt rolle public bool IsUserInRole(string brugernavn, string rolle) { int rowsAffected; //parametere defineres SqlParameter[] parameters = { new SqlParameter("@BrugerNavn",SqlDbType.VarChar,50), new SqlParameter("@AdgangsNiveauTekst", SqlDbType.VarChar,50), new SqlParameter("@IsUserInRole", SqlDbType.Bit) }; //parameter værdier sættes parameters[0].Value = brugernavn; parameters[1].Value = rolle; parameters[2].Direction = ParameterDirection.Output; try { //stored procedure afvikles DbHandler.GetDbHandler().RunProcedure("SP_Bruger_IsUserInRole", parameters, out rowsAffected); return (bool)parameters[2].Value; } catch (Exception e) { //evt fejl gemmes FejlLog.GetFejlLog().gemFejl(HttpContext.Current.Profile.GetPropertyValue("BrugerInfo.BrugerID").ToString(), e); return false; } } //bruges til at hente de virksomheder brugeren har ret til at se public DataSet VisVirksomheder() { SqlParameter[] parameters = { new SqlParameter("@BrugerID", SqlDbType.Int,4) }; parameters[0].Value = HttpContext.Current.Profile.GetPropertyValue("BrugerInfo.BrugerID"); try { //stored procedure afvikles return DbHandler.GetDbHandler().RunProcedure("SP_Bruger_VisVirksomheder", parameters, "dsVirk"); } catch (Exception e) { //evt fejl gemmes FejlLog.GetFejlLog().gemFejl(HttpContext.Current.Profile.GetPropertyValue("BrugerInfo.BrugerID").ToString(), e); return new DataSet(); } } //metode som checker om et brugernavn eksisterer eller ej public bool CheckBrugerNavn(string brugernavn, int brugerid) { int rowsAffected; //parametre defineres SqlParameter[] parametres = { new SqlParameter("@BrugerNavn", SqlDbType.VarChar,50), new SqlParameter("@BrugerID", SqlDbType.Int) }; //parameter værdier sættes parametres[0].Value = brugernavn; parametres[1].Value = brugerid;
return System.Convert.ToBoolean(DbHandler.GetDbHandler().RunProcedure("SP_Bruger_CheckBrugerNavn", parametres, out rowsAffected));
} public bool OpretBruger(string brugernavn, string password, string fornavn, string efternavn, string email, int adgangsniveauid) { int rowsAffected; //parametere defineres SqlParameter[] parameters = { new SqlParameter("@BrugerNavn", SqlDbType.VarChar,50), new SqlParameter("@Password", SqlDbType.VarChar, 50), new SqlParameter("@Fornavn", SqlDbType.VarChar, 50), new SqlParameter("@Efternavn", SqlDbType.VarChar, 50), new SqlParameter("@Email", SqlDbType.VarChar,255), new SqlParameter("@AdgangsNiveauID", SqlDbType.Int), new SqlParameter("@VirksomhedsID", SqlDbType.Int), new SqlParameter("@BrugerOprettet", SqlDbType.Bit) }; //parameter værdier sættes parameters[0].Value = brugernavn; parameters[1].Value = password; parameters[2].Value = fornavn; parameters[3].Value = efternavn; parameters[4].Value = email; parameters[5].Value = adgangsniveauid; parameters[6].Value = HttpContext.Current.Profile.GetPropertyValue("BrugerInfo.ValgtVirk"); parameters[7].Direction = ParameterDirection.Output; try { //stored procedure afvikles DbHandler.GetDbHandler().RunProcedure("SP_Bruger_OpretBruger", parameters, out rowsAffected); return (bool)parameters[7].Value; } catch (Exception e) { //evt fejl gemmes FejlLog.GetFejlLog().gemFejl(HttpContext.Current.Profile.GetPropertyValue("BrugerInfo.BrugerID").ToString(), e); return false; }
} public bool OpdaterBruger(string brugernavn, string fornavn, string efternavn, string email, int adgangsniveauid, bool brugeraktiv, int brugerid) { int rowsAffected; //parametere defineres SqlParameter[] parameters = { new SqlParameter("@BrugerNavn", SqlDbType.VarChar,50), new SqlParameter("@Fornavn", SqlDbType.VarChar, 50), new SqlParameter("@Efternavn", SqlDbType.VarChar, 50), new SqlParameter("@Email", SqlDbType.VarChar,255), new SqlParameter("@AdgangsNiveauID", SqlDbType.Int), new SqlParameter("@Aktiv", SqlDbType.Bit), new SqlParameter("@BrugerID", SqlDbType.Int), new SqlParameter("@BrugerOpdateret", SqlDbType.Bit) }; //parameter værdier sættes parameters[0].Value = brugernavn; parameters[1].Value = fornavn; parameters[2].Value = efternavn; parameters[3].Value = email; parameters[4].Value = adgangsniveauid; parameters[5].Value = brugeraktiv; parameters[6].Value = brugerid; parameters[7].Direction = ParameterDirection.Output; try { //stored procedure afvikles DbHandler.GetDbHandler().RunProcedure("SP_Bruger_OpdaterBruger", parameters, out rowsAffected); return (bool)parameters[7].Value; } catch (Exception e) { //evt fejl gemmes FejlLog.GetFejlLog().gemFejl(HttpContext.Current.Profile.GetPropertyValue("BrugerInfo.BrugerID").ToString(), e); return false; }
og min database klasse: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.Sql; using System.Data.SqlClient;
/// <summary> /// Summary description for DbHandler /// </summary> public class DbHandler { private string ConnectionString; private SqlConnection Connection = new SqlConnection(); private static readonly DbHandler instance = new DbHandler(); private DbHandler() { ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; Connection.ConnectionString = ConnectionString; } public static DbHandler GetDbHandler() {
return instance; } /// <summary> /// Private routine allowed only by this base class, it automates the task /// of building a SqlCommand object designed to obtain a return value from /// the stored procedure. /// </summary> /// <param name="storedProcName">Name of the stored procedure in the DB, eg. sp_DoTask</param> /// <param name="parameters">Array of IDataParameter objects containing parameters to the stored proc</param> /// <returns>Newly instantiated SqlCommand instance</returns> private SqlCommand BuildIntCommand(string storedProcName, IDataParameter[] parameters) { SqlCommand command = BuildQueryCommand(storedProcName, parameters);
/// <summary> /// Builds a SqlCommand designed to return a SqlDataReader, and not /// an actual integer value. /// </summary> /// <param name="storedProcName">Name of the stored procedure</param> /// <param name="parameters">Array of IDataParameter objects</param> /// <returns></returns> private SqlCommand BuildQueryCommand(string storedProcName, IDataParameter[] parameters) { SqlCommand command = new SqlCommand(storedProcName, Connection); command.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters) { command.Parameters.Add(parameter); }
return command;
}
/// <summary> /// Builds a SqlCommand designed to return a SqlDataReader, and not /// an actual integer value. /// </summary> /// <param name="storedProcName">Name of the stored procedure</param> /// <param name="parameters">Array of IDataParameter objects</param> /// <returns></returns>
/// <summary> /// Runs a stored procedure, can only be called by those classes deriving /// from this base. It returns an integer indicating the return value of the /// stored procedure, and also returns the value of the RowsAffected aspect /// of the stored procedure that is returned by the ExecuteNonQuery method. /// </summary> /// <param name="storedProcName">Name of the stored procedure</param> /// <param name="parameters">Array of IDataParameter objects</param> /// <param name="rowsAffected">Number of rows affected by the stored procedure.</param> /// <returns>An integer indicating return value of the stored procedure</returns> public int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) { int result; try { Connection.Close(); } catch (Exception e) { }
/// <summary> /// Will run a stored procedure, can only be called by those classes deriving /// from this base. It returns a SqlDataReader containing the result of the stored /// procedure. /// </summary> /// <param name="storedProcName">Name of the stored procedure</param> /// <param name="parameters">Array of parameters to be passed to the procedure</param> /// <returns>A newly instantiated SqlDataReader object</returns> public SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) { SqlDataReader returnReader; try { Connection.Close(); } catch (Exception e) { } SqlCommand command = BuildQueryCommand(storedProcName, parameters); command.CommandType = CommandType.StoredProcedure;
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.