Two virtual directories on IIS for secured pages - asp.net

I am developing application in .net 4.0.In my web application project it have secured folder.
now i want to redirect only authenticated users to secured pages.
i want to do this making two different virtual directories on IIS.(Virtual directory within one more directory)
can i do this? how can i do this? or is there any way to this?
Thanks in advanced.

If you like to do that manually with your code, the right place is on global.asax the Application_AuthenticateRequest trigger. Here is an example, and you can change it according to your logic.
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
string cTheFile = HttpContext.Current.Request.Path;
if(!cTheFile.Contains("/securedir/"))
{
if (HttpContext.Current.Request.IsSecureConnection)
{
HttpApplication app = (HttpApplication)sender;
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
// if this is null, then the user is not logged in
if (null == authCookie)
{
// for the same check you can also use
//if(HttpContext.Current.User == null || HttpContext.Current.User.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated)
string sExtentionOfThisFile = System.IO.Path.GetExtension(cTheFile);
if (sExtentionOfThisFile.Equals(".aspx", StringComparison.InvariantCultureIgnoreCase))
{
Response.Redirect("/", true);
Response.End();
// There is no authentication cookie.
return;
}
}
}
}
}
}

Related

How to Encrypt and Decrypt cookie in an Existing Project without changing all pages code

I am working on a project with 1000s of pages in it which uses cookies. Now There comes an security issue , so I am planning to encrypt the cookie and decrypt when use it in page level.
Sample code i have used in Login page where my cookie gets created is as below:
Response.Cookies.Clear()
Response.Cookies("userinfo")("username") = "Pravin Kumar"
Response.Redirect("Home.aspx")
Now i wanna access that cookie in my HOME.aspx page . The code is as below.
Response.Write(Request.Cookies("userinfo")("username"))
This is how my project pages working till now and this enables user to view cookie in browser window like below :
Now My intention is i want to do some encrypting in LOGIN.aspx page and do the decryption in such a centralized place so that i no need to change all pages .
PS: I have tried with GLOBAL.asax page using
Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs)
End Sub
But it didn't helped out.Pls suggest me if any simplest method found.
you will have to use HttpModule to override the behavior of the cookie read/write.
here is the sample code:
firstly, in your HttpModule
public class CookieEncryptModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.PreSendRequestContent += Context_PreSendRequestContent;
context.BeginRequest += Context_BeginRequest;
}
private void Context_BeginRequest(object sender, EventArgs e)
{
HttpApplication httpApplication = sender as HttpApplication;
for (int i = 0; i < httpApplication.Request.Cookies.Count; i++)
{
var cookie = httpApplication.Request.Cookies[i];
cookie.Value = dencryptCookieValue(cookie.Value);
}
}
private void Context_PreSendRequestContent(object sender, EventArgs e)
{
HttpApplication httpApplication = sender as HttpApplication;
for (int i = 0; i < httpApplication.Response.Cookies.Count; i++)
{
var cookie = httpApplication.Response.Cookies[i];
cookie.Value = encryptCookieValue(cookie.Value);
}
}
private string encryptCookieValue(string value)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
}
private string dencryptCookieValue(string value)
{
try
{
return Encoding.UTF8.GetString(Convert.FromBase64String(value));
}
catch
{
//in case some system generated cookies like session id will not be encrypted by our code
return value;
}
}
}
then in your web.config
<system.webServer>
<modules>
<add name="encryptCookie" type="[your_namespace].CookieEncryptModule, [your_assemably_name]"/>
</modules></system.webServer>
after above is done,
you cookies now will be stored in client with base64,
but to you server side codes it's transparent, you don't need to change anything
[notice]: this will make all JS fail to read the cookie value

Accessing Sessions Variables in code behind

Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Session["Authenticated"] )
{
Response.Redirect( "index.aspx", false );
}
}
Once they login I set the session to true. Basically, if they don't have an active session I want them re-directed back to the index/login page. How do I accomplish this?
Use this check
if(Session["Authenticated"] == null || !(bool)Session["Authenticated"])
If you are using cookie, you can store a marker in your cookie so you can tell the difference between "fresh browser + new session" and "old browser + expired session".
Below is sample code that will redirect the user to an expired page if the session has expired.
void Session_OnStart(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
HttpCookieCollection cookies = context.Request.Cookies;
if (cookies["starttime"] == null) {
HttpCookie cookie = new HttpCookie("starttime", DateTime.Now.ToString());
cookie.Path = "/";
context.Response.Cookies.Add(cookie);
}
else {
context.Response.Redirect("expired.aspx");
}
}
And if you are trying to implement sessions this might help you http://aspalliance.com/1621_Implementing_a_Session_Timeout_Page_in_ASPNET.2

Using session for user authentication in asp.net c#

I am using session to authenticate a user. I have 2 web pages in my project. One is webform and other one is EntryForm.aspx and other one is log.aspx
In log.aspx i have done
protected void Button1_Click(object sender, EventArgs e)
{
user_login loginu = new user_login();
String uid_db = loginu.login(this.DropDownList1, this.TextBox1, this.TextBox2, this.Label5);
if (uid_db == "invalid")
{
Label5.Visible = true;
Label5.Text = "Invalid Login";
}
else
{
string uname = uid_db.Substring(0, uid_db.IndexOf(",")).Trim();
string[] tokens = uid_db.Split(',');
string dbname = tokens[tokens.Length - 1];
Session["login"] = uname;
Session["db"] = dbname;
Response.Redirect("EntryForm.aspx");
}
}
In class user_login I am taking the password stored in the database and matching it with the value entered by user. if it finds a value i redirect it to EntryForm.aspx. In which i check for session variable as follows
protected void Page_Load(object sender, EventArgs e)
{// CHEK SESSION VARIABLE AND LOAD dropdownlist1 WITH VALUES
if (!IsPostBack)
{
String DB = "";
String AccountID = "";
if (Session["login"] != null && Session["db"] != null)
{
AccountID = Session["login"].ToString();
DB = Session["db"].ToString();
Label9.Text = AccountID;
}
else
{
Response.Redirect("log.aspx");
}
HiddenField1.Value = DB.ToString();
DropDown a = new DropDown();
a.filldropdown1(this.DropDownList1, DB);
}
}
This is what i have done do authenticate a user. On server i have done the following configuration:
I have done no settings in Global.asax nor anything is web.config . I have seen many forum wherein Global.asax and web.config is configured.
I want to know what do i need to do in my project in order to be very efficient to work. I am facing problem with session timeout. I have set it to 20 mins on my server but sometimes suddenly i get logged out.
Please help me to understand using session for authentication.
First of all you have to edit web.config and set session timeout attribute.
<configuration>
<system.web>
<sessionState timeout="200"></sessionState>
</system.web>
</configuration>
Another issue is the use of IsPostBack block.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["login"] != null && Session["db"] != null)
{
String DB = "";
String AccountID = "";
AccountID = Session["login"].ToString();
DB = Session["db"].ToString();
Label9.Text = AccountID;
HiddenField1.Value = DB.ToString();
DropDown a = new DropDown();
a.filldropdown1(this.DropDownList1, DB);
}
else
{
Response.Redirect("log.aspx");
}
}

How to properly authenticate mvc-mini-profiler with AspNetSqlMembershipProvider

I tried to check if the user is in role at Application_BeginRequest and Application_AuthenticateRequest with this code and it will not work. At BeginRequest the code is never hit and Authenticate it's hit with some of the request and the profiler does not show up.
Checking only for Request.IsLocal works fine.
if(Request.IsAuthenticated)
{
if(User.IsInRole("Admin");
MiniProfiler.Start();
}
Any idea or why it's not working or better way to do it?
[Update] I accepted the awnser but undid it as I didn't quite get it do work
I did the following but the profiler is not showing up at first.
After a few tries it started showing up, even when I tried to acess the site with incognito mode, so no cookie.
protected void Application_PostAuthorizeRequest(Object sender, EventArgs e)
{
if (User.IsInRole("Admin"))
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if (cookie == null)
{
cookie = new HttpCookie("RoleProfiler");
cookie.Value = "yes";
cookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookie);
}
}
}
And I'm checking with
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("RoleProfiler");
if ((cookie != null) && (cookie.Value == "yes") )
{
MvcMiniProfiler.MiniProfiler.Start();
}
}
And ending at the end of the request.
protected void Application_EndRequest()
{
MvcMiniProfiler.MiniProfiler.Stop();
}
[Update2] Closing question, ignore this, I was being owned by outputcache.
The cookie feanz mentions is a handy trick, a second method is profiling unconditionally and then abandoning the session for an unauthenticated user:
protected void Application_BeginRequest()
{
MvcMiniProfiler.MiniProfiler.Start();
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if(!CurrentUserIsAllowedToSeeProfiler())
{
MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);
}
}
Begin request happens before the user is fully authenticated in the request life cycle.
I solved this issue by adding a cookie if the user is in a role ("Admin" in your case) when the request is authenticated then you can check for this cookie on begin request and initialise the profiler.
It wont't work the first time but should every time after that.
This is my 2cent.
context.AcquireRequestState += (sender, e) =>
{
// Check debug in session. Can be set from Querystring. (?debug=true)
if (HttpContext.Current.Session != null && HttpContext.Current.Session["Debug"] != null)
{
try{
bool debug = (bool)HttpContext.Current.Session["Debug"];
if (debug == true)
MiniProfiler.Start();
else
MiniProfiler.Stop(discardResults: true);
}
catch{
MiniProfiler.Stop(discardResults: true);
}
}// Or always show if Administrator.
else if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
{
bool admin = HttpContext.Current.User.IsInRole("Administrator");
if (admin == false)
{
MiniProfiler.Stop(discardResults: true);
}
}
else
{
MiniProfiler.Stop(discardResults: true);
}
};

ASP.NET Forms Authentication with Windows Safari

Does anyone know why ASP.NET Forms Authentication does not work on windows safari, or better yet, how to get it to work? It seems like a very weird issue. When I use a login control (System.Web.UI.WebControls.Login) everything works fine, but if I try to do a custom Forms Authentication login when I call FormsAuthentication.RedirectFromLoginPage safari just sends me back to the login page as if I'm not authenticated whereas every other browser logs me in and sends me on my way.
protected void lnkLogin_Click(object sender, EventArgs e)
{
if (Membership.Provider.ValidateUser(txtUsername.Text, txtPassword.Text))
{
Session.Clear();
HttpContext.Current.Response.Cookies.Clear();
FormsAuthentication.SetAuthCookie(txtUsername.Text, true);
FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
}
}
Try either SetAuthCookie, or RedirectFromLoginPage. The redirect needs to know where to redirect to anyway (ReturnUrl), maybe that is your problem.
if (Request.QueryString["ReturnUrl"] != null)
{
FormsAuthentication.RedirectFromLoginPage("someuserid", false);
}
else
{
FormsAuthentication.SetAuthCookie("someuserid", false);
Response.Redirect("~/SomePage.aspx");
}
This works fine for me in Safari:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
//check login
User user = UserBAL.GetUser(Login1.UserName, Login1.Password);
//null and filled object check
if (user != null && user.Id > 0 && user.Roles != null && user.Roles.Count > 0)
{
e.Authenticated = true;
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1, //version
Login1.UserName, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(60),// Expiration
false, // Persistent
string.Join("|", user.Roles.ToArray())); // User ata
// Now encrypt the ticket.
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
// Create a cookie and add the encrypted ticket to the
// cookie as data.
HttpCookie authCookie =
new HttpCookie(FormsAuthentication.FormsCookieName,
encryptedTicket);
Response.Cookies.Add(authCookie);
//redirect
Response.Redirect(FormsAuthentication.GetRedirectUrl(
Login1.UserName,
false));
}
else
{
Login1.FailureText = "Login failed.";
}
}

Resources