У меня есть веб-приложение ASP .NET (работает только в интрасети), где я использую простую модель авторизации пользователей. У меня есть таблица с именем tblApplicationAccess, которая имеет два поля - UserID и AccessLevel.
Например,
UserID: John.Smith, уровень доступа: 2
(1 - Общий доступ, 2 - Доступ к вводу данных, 3 - Суперпользователь, 4 - Доступ разработчика)
Я использую событие Session_Start в global.asax для авторизации пользователя. Вот код,
protected void Session_Start(object sender, EventArgs e)
{
string strUserID = User.Identity.Name.Substring(5);
bool isAllowedToView = false;
// UtilityClass is a root level class with various methods that I use throughout the application.
// QUESTION: Could this be the problem? Since it is at root level (alongside all the pages), could it be the case that this resource isn't checked for user access?
UtilityClass.StrCurrentSessionID = this.Session.SessionID;
// Add a row to BLSC_tblSession
int nRowsReturned;
string strConnectionString = UtilityClass.GetConnectionString("My Application");
string strQueryStartSession = "INSERT INTO BLSC_tblSession " +
"(SessionID, UserID, SessionStatus, StartTime, EndTime) " +
"VALUES ('" + this.Session.SessionID + "', '" + User.Identity.Name.Substring(5) + "', 'Active', '" + DateTime.Now + "', '" + DateTime.Now.AddDays(1) + "')";
SqlConnection connStartSession = new SqlConnection(strConnectionString);
if (connStartSession != null)
{
try
{
connStartSession.Open();
SqlCommand sqlStartSession = new SqlCommand(strQueryStartSession, connStartSession);
nRowsReturned = sqlStartSession.ExecuteNonQuery();
if (nRowsReturned == 0)
throw new Exception("Session could not be started.");
else
{
// Authorize User
// Check if user has access to the application. If not, redirect to UnauthorizedAccess.aspx
// Check for access level 1.
// IMPORTANT: For Dev server change access level to 4.
isAllowedToView = UtilityClass.CheckUserAccess(strUserID, 1);
if (isAllowedToView == false)
{
UtilityClass.WriteToLog("Application Access Denied: UserID - " + strUserID, 1);
Response.Redirect("Some URL");
}
else
{
// Browser detection
string strBrowserName = Request.Browser.Browser;
if (strBrowserName != "IE")
{
UtilityClass.WriteToLog("Non-supported browser usage detected: UserID - " + strUserID + ", Browser - " + strBrowserName, 0);
Response.Redirect("Some other URL");
}
}
}
connStartSession.Close();
}
catch (SqlException SqlEx)
{
UtilityClass.HandleError("Global.asax", "Session_Start", SqlEx.Message);
}
catch (Exception Ex)
{
UtilityClass.HandleError("Global.asax", "Session_Start", Ex.Message);
}
finally
{
if (connStartSession != null)
connStartSession.Close();
}
}
}
UtilityClass.CheckUserAccess
public static bool CheckUserAccess(string UserID, int RequiredAccessLevel)
{
bool bReturn = false;
object TemporaryPlaceHolder;
int nUserAccessLevel = 0;
string strQueryCheckUserAccess = "SELECT AccessLevel " +
"FROM BLSC_tblApplicationAccess " +
"WHERE UserID = '" + UserID + "'";
string strConnectionString = GetConnectionString("My Application");
SqlConnection connCheckUserAccess = null;
try
{
if (strConnectionString != String.Empty)
{
connCheckUserAccess = new SqlConnection(strConnectionString);
connCheckUserAccess.Open();
if (connCheckUserAccess != null)
{
SqlCommand sqlCheckUserAccess = new SqlCommand(strQueryCheckUserAccess, connCheckUserAccess);
TemporaryPlaceHolder = sqlCheckUserAccess.ExecuteScalar();
if (TemporaryPlaceHolder != DBNull.Value && TemporaryPlaceHolder != null)
{
nUserAccessLevel = Convert.ToInt32(TemporaryPlaceHolder);
if (nUserAccessLevel >= RequiredAccessLevel)
bReturn = true;
else
bReturn = false;
}
else
bReturn = false;
}
connCheckUserAccess.Close();
}
}
catch (SqlException SqlEx)
{
HandleError("UtilityClass.cs", "CheckUserAccess", SqlEx.Message);
}
catch (Exception Ex)
{
HandleError("UtilityClass.cs", "CheckUserAccess", Ex.Message);
}
finally
{
if (connCheckUserAccess != null)
connCheckUserAccess.Close();
}
return bReturn;
}
Проблема:
Мое приложение не загружается в производственной среде.
Приложение запускается с использованием аутентификации Windows. Если быть точным, у нас есть DomnainName \ ApplicationServer $ , которые обращаются к SQL Server, а не отдельным пользователям.
Мой вопрос:
Если я хочу проверить доступ к приложению, используя мою текущую модель и события global.asax, где лучше всего ее разместить? Я делаю что-то здесь не так? Мне нужно записать в таблицу сеанса для регистрации событий и не могу использовать проверку подлинности на основе ролей, которую обеспечивает ASP .NET.