Cookies expiring too quickly enough in c# asp.net webpages - c#

For some reason my cookies don't last as long as they should, usually within 15 min a user would have to log back on. I am using webform login and when a user logs in I set the cookie like this.
HttpCookie cookie = new HttpCookie("UserName", "Joe");
cookie.Expires = DateTime.UtcNow.AddDays(5);
HttpContext.Current.Response.SetCookie(cookie);
When I read the cookie this is what I do
if (Request.Cookies["UserName"] != null && Request.Cookies["UserName"].value == "Joe")
This is what is on my web.config file for authentication, everyone gets bounced back to the loginpage.aspx in less than 1 hour
<authentication mode="Forms">
<forms name="LoginPage" path="/" loginUrl="/LoginPage.aspx" defaultUrl="Index.aspx"/>
</authentication>
<authorization>
<deny users="?"/>
<!-- Deny all anonymous users-->
<allow users="*"/>
<!-- Allow all authanticated users-->
</authorization>

I think this is timeout works. To fix that add attribute timeout="0" to your element. MSDN

Related

Best way to redirect user to Login page on cache lost

What is the best way to redirect user to login when cache is lost?
At moment I'm doing this:
if (Session["Id"] == null)
{
return RedirectToAction("Login", "Home");
}
But with this method, it put this code in every function, is there any other way to do this in the entire program? I tried search by doing this from web.config, but no results.
Assuming you are using Form-based authentication and permitting access to only authorised users then this could be achieved through making changes in web.config
<authentication mode="Forms">
<forms loginUrl="login.aspx" defaultUrl="default.aspx" name=".YourApplication" timeout="60" cookieless="AutoDetect" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
the loginUrl property tells the server where to direct the user if he is not logged in, and the defaultUrl property tells the server where to direct him after the user is logged.
the deny users="?" tells the server to deny any user that is not authenticated and directs him to the loginUrl page
In the codebehind of the login page, you need something like this after you check the credentials inserted:
FormsAuthentication.RedirectFromLoginPage(userName.Text, True)
Reference
private const string GlobalAuthKey = "GlobalAuthTime";
You can insert all auth user info in authList.
HttpRuntime.Cache.Insert(GlobalAuthKey, authList);
Then Get cache :
var authList = HttpRuntime.Cache.Get(GlobalAuthKey) as List<AuthInfo> ?? new
List<AuthInfo>();
After that you check this specific user login info,and you force your user by this desire condition.Hopefully You understand.

C# Webforms - How to fix localhost redirect you too many times after login?

I want to deny anonymous users and allow all authenticated users to access. After successful login, it supposed to redirect to Default page. However, it keep showing error : too many redirects. It seems like it keep redirecting back to login page. Why and how to fix it? Below are my codes, did i missed anything or done anything wrong that cause the problem? Thanks in advance
FormsAuthentication.SetAuthCookie(this.txtusername.Text, false);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1,
this.txtusername.Text,
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,
Role
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
// the login is successful
if (Request.QueryString["ReturnUrl"] == null)
{
Response.Redirect("~/Default.aspx");
}
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="30"> </forms>
</authentication>
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>

Validating a user on every page using session information, c# & ASP.NET

My question is more of a request for advice on how to implement a feature to a website using session information. I have a website that asks for username and password on the landing page. When a user successfully logs in, a session is created that stores their username and a few other variables related to the account. In the Page_Load function immediately following login, I successfully access this information attached to the user via session variables, verifying that it is implemented properly.
In the MySession class:
private MySession()
{
Username = Data.User.lblUsername;
CompanyId = Data.User.lblCompanyId;
}
In my welcome page (immediately following successful login)
private void Page_Load(object sender, System.EventArgs e)
{
secure_username = MySession.Current.Username;
...
}
I want to use this information, i.e. secure_username to validate the user once a page is accessed so that people can no longer skip the login form. From MySession class, do I simply use if(MySession.Current.Username == ??) statements to check each variable at the start of the Page_Load function, or is there a proper way to go about this?
Please ask for clarification if it is needed. Thanks.
EDIT: Based on some of the responses given, i think it is important to note that if a user suddenly becomes anonymous (or times out) they should be redirected to the login page.
If you are using form authentication then you can add following tags to web.config to deny any anonymous access. If you do this, you don't have to check if user is logged in on every page.
<authorization>
<deny users="?" />
</authorization>
Add this to allow all users to see Login.aspx so that they can login
<location path="Login.aspx" allowOverride="false">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
Add this so that all your css/images folders are visible to anonymous users
<location path="css" allowOverride="false">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="images" allowOverride="false">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
You may have to add extra location tags based on your website setup and the folders you want any anonymous user to have access to
If login form authentication session expires user will be redirected to url you mention in this tag
<forms loginUrl="Login.aspx" timeout="30">
</forms>
If you need to do the same action on every page it sounds like you need a base class where all your secure pages inherit from:
Base page:
public class BasePage : System.Web.UI.Page
{
public user secure_username
{get;set;}
protected void Page_Load(object sender, EventArgs e)
{
//add your checks that repeat on each page
}
}
Other pages:
public class AuthenticatedUsersPage : BasePage
{
}
Note: This of course assumes that you have already taken care of authorization and authentication on your config file (see rs' answer for more info). Also, if you are using forms authentication, remember to make your session last longer than your forms authentication timeout.

FormsAuthentication Login refuses to redirect after setting auth ticket

So I have a login page where I set my own cookie and FormsAuthenticationTicket. However, when I finally choose to redirect the user to the new homepage after logging in, it refuses. It just redirects right back to the login page for no reason. I don't understand why.
My web.config with part of the machinekey removed:
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" defaultUrl="~/Default.aspx" cookieless="UseCookies" name=".ASPXFORMSAUTH" timeout="50" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
<machineKey decryption="AES" validation="SHA1" ........ />
My Login click event after entering username/pass and authenticating it as true:
if (Authenticated)
{
//Create Form Authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), false, userName, FormsAuthentication.FormsCookiePath);
string encryptedCookie = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedCookie);
Response.Cookies.Add(cookie);
Response.Redirect("MainPage.aspx", true);
}
MasterPage checks to make sure only certain pages can be accessed:
else if (Context.User.Identity.IsAuthenticated)
{
if (Session["uid"] == null)
{
userclass u = new userclass();
int uid = -1;
uid = (int)u.Getuseridbyusername(Context.User.Identity.Name);
if (uid != -1)
{
Session["uid"] = uid;
}
}
} else if (!Context.User.Identity.IsAuthenticated)
{
// First check if user is was redirected to ChangePassword
if (!Request.Path.Contains("ForgotPass.aspx") && !Request.Path.Contains("ChangePass.aspx") && !Request.Path.Contains("CreateAccount.aspx") && !Request.Path.Contains("Error.aspx") && !Request.Path.Contains("Logout"))
{
if (!Request.Path.Contains("Login"))
FormsAuthentication.RedirectToLoginPage();
}
}
Commenting out RedirectToLoginPage() has no effect. Trying to use RedirectFromLoginPage has no effect. Trying to use <allow users="?" /> has no effect. Trying to use <deny users="?" /> in conjunction has no effect.
EDIT: Cookie is set according to browser traffic. But no redirect is coming through. Apparently, either you cannot redirect after setting a cookie or ASP.NET doesn't know how to read instructions.
Solved. Apparently, I did have a Redirect somewhere that was taking the user back to the login page even though the cookie is set and Context.User.Identity.IsAuthenticated was returning true because the session variable "uid" was being set.
use this in config file
<authorization>
<deny users="?" />
<allow users="*" />
</authorization>

Roles authentication is not working in asp.net

I am using the code below to access a page base based upon user authentication
if (user.FirstOrDefault() == HashedPassword)
{
string roles = "Member";
// Create the authentication ticket
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1, // version
loginName.Text, // user name
DateTime.Now, // creation
DateTime.Now.AddMinutes(60),// Expiration
false, // Persistent
roles); // User data
// 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);
// Add the cookie to the outgoing cookies collection.
Response.Cookies.Add(authCookie);
Response.Redirect("/Members/ClientAccount.aspx");
}
else
{
Response.Redirect("signin.aspx");
}
}
The user is getting directed to ClientAccount.aspx if the login details are correct but I want that to happen only if his/her role is set as Admin as shown in the web.config file below .
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<location path="members.aspx">
<system.web>
<authorization>
<allow roles="Member" />
<allow roles="Admin" />
<deny users="?" />
</authorization>
</system.web>
</location>
<location path="ClientAccount.aspx">
<system.web>
<authorization>
<allow roles="Admin" />
<deny roles="Member"/>
<deny users="?" />
</authorization>
</system.web>
</location>
</configuration>
How do I make this happen ?
I guess the web.config file is not looking at the cookie to do the authorization so I am doing something wrong there.
Double check your location path relative to the web.config, my guess is that is the problem.
<location path="/Members/ClientAccount.aspx">
...
</location>
Of course you'll need to do something else instead of this line, you were just doing this for testing I'd assume?
Response.Redirect("/Members/ClientAccount.aspx");
i.e. redirect them to a page you know they're not allowed to hit. I figure you're going to beef that part up once you're sure its not allowing members to access that page.
You should make sure your web.config has the following tag:
<authentication mode="Forms" />
You need to configure it right, there are lots of options:
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
protection="All"
timeout="30"
name=".ASPXAUTH"
path="/"
requireSSL="false"
slidingExpiration="true"
defaultUrl="default.aspx"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" />
</authentication>
http://msdn.microsoft.com/en-us/library/ff647070.aspx
hey there, did you mean to have
<deny roles="Member"/>
right now, the deny policy really doesn't need the member role listed. If you are wanting member to also be allowed to that page, you will need to swap out the deny, to allow:
<authorization>
<allow roles="Admin" />
<allow roles="Member"/>
<deny users="?" />
</authorization>

Categories