asp.net forms authentication redirect problem - asp.net

The default document feature is turned off in IIS and here's the situation...
My start page for my project say is A.aspx. I run the project and sure enough, A.aspx appears in the url of the browser. Like it should though, A.aspx finds no user logged in and redirects to Login.aspx like it should.
A.aspx:
if (Session["UserStuff"] == null)
Response.Redirect("~/Account/Login.aspx");
The login.aspx shows up BUT when the user Logs in, the code:
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
always redirects to "Default.aspx" and not "A.aspx"
I've examined FormsAuthentication.GetRedirectUrl and sure enough it returns "Default.aspx"
I'm stumped????

In web.config you could set the default page using the defaultUrl attribute:
<authentication mode="Forms">
<forms
loginUrl="login.aspx"
defaultUrl="a.aspx"
protection="All"
timeout="30"
/>
</authentication>

http://www.codeproject.com/KB/aspnet/custom_authentication.aspx Follow this

If you're using FormsAuthentication, your settings should be defined in the web.config. It sounds like you have a default setting in the web.config for DefaultUrl. You shouldn't need the session redirect though. FormsAuthentication should perform this for you. It doesn't hurt to check the session and force a SignOut() if you don't find it, but FormsAuthentication should perform this redirect.

From my understanding, when the user is redirectoed to your login screen, the Forms Authentication mechanism will add the url of the page that the user was originally tring to access, to the login url that that they user tried to access. For example, if you had a login page: http;//bob/login.aspx, and a user tried to access http;//bob/showmethemoney.aspx, then they would get redirected to http;//bob/login.aspx?ReturnUrl=showmethemoney.aspx. So, if you use the ReturnUrl to redirect the user after the user logs in, the user will always be returned to the resource that they were originally trying to get to.

Related

Forms Authentication in IE

I have seem a few of these asking the same question but none of the solutions have worked for me thus far so I wanted to see if I am doing something wrong. I have a site that I am using asp.net MVC to create, at current I am using forms authentication to prevent anonymous users from browsing the site. That bit of code is as follows.
<authentication mode="Forms" >
<forms loginUrl="~/login" timeout="15"/>
</authentication>
Then I have a login controller that has the user enter their userName and password then creates an authcookie if the information is accurate.
if (password == encryptedPassword)
{
FormsAuthentication.SetAuthCookie("user", true, model.userName);
}
All of this works in Firefox and Chrome and after the user has logged in he is able to browse the site. However in IE it keeps returning to the log in screen because it keeps recognizing the user as an anonymous user. I checked and the Auth cookie is either never created or doesn't persist as soon as you enter the next page. Some of my attempts to fix this involved using cookieless in the web.config. The only one that works was the one that actually puts the cookie in the URI and we can't have that for the site. Then I tried setting ticketCompatibilityMode="Framework40" but there was no luck there either.
I did see a bug with domain names having non-alpha numerica characters. I currently use the IP to access the domain directly, so I don't know if periods run this problem but even my local host suffers from the same issues. Any input would be appreciated.
Parameters should be in the following order.
FormsAuthentication.SetAuthCookie(model.userName, true, ...);
OR
FormsAuthentication.SetAuthCookie(model.userName, true);
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.setauthcookie.aspx

can I write my Login Page redirect code in Session_End?

Can I write my code in the Session_End method when my session is timeout and I redirect users to the Login Page?
I am using Form Authentication method.
Currently I have create a "CheckSession()" method and calling on each page...
please suggest...
I've always placed the session check code in a master page for webform projects or, more recently, creating a base controller that has this method. Either way the goal is not to duplicate that code everywhere for obvious maintenance reasons.
I think you can manage this through settings in your web.config file without having to use code at all. Just ensure that the duration of your forms authentication cookie and your session are the same length. If your authentication session times out ASP.NET will automatically redirect a user to the login page.
Try:
<forms ... timeout="20" slidingExpiration="true" />
(slidingExpiration is true by default but I've specified it here because it must be true to replicate the timeout behaviour of sessions in ASP.NET)
and:
<sessionState ... timeout="20" />

Sessions in asp.net

i have a login page so once the user enters the correct details he enters into the home page. Now i want to implement 3 things
once he clicks the button 'log out' he must be redirected to a page saying" logged out successfully " n even if clicks the back button in the browser, he should not be able to access.
if the user leaves the homepage idle for a specific amount of time say 10minutes and then he tries to navigate after 10 mins a msg should display saying "Your Session has been expired login again"
if given the url of homepage he shouldnt be able to access unless logged in.
I am not sure about what exactly i need to do and how to do. Plz Help
Regards
Indranil Mutsuddy
1) When the user logs out of the system I would recommend doing a Session.Abandon(). If the user clicks the Back button in the browser he might see the cached version of the old page (this is entirely browser dependant), but he won't be able to do anything anyway.
Disable the caching in your pages and the user shouldn't even see the cached old version :)
A simple way to do this would be to add the following into Global.asax's Application_BeginRequest:
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
2) In your web.config set the session lifetim to 10 minutes, incremental.. That will do the trick
<system.web>
<authentication mode="Forms">
<forms defaultUrl="~/LoggedIn.aspx" loginUrl="~/Login.aspx" protection="All" path="/" slidingExpiration="true" timeout="10"/>
</authentication>
</system.web>
3) You can do this using authorization rules in web.config. If you want no anonymous users to access your website just enable access only to logged in users like this:
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
If you want to restrict access not to the whole website, but only to some areas (like the MyAccount area, then you can add this instead.. Note: Web.config can have multiple <location> elements!
<location path="MyAccountFolder">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
There's one important note about the location tag. The Path does NOW start with a '/'! So if you want to secure the /MyAccount folder, then your tag will start like this:
<location path="MyAccount" />
You should generally use ASP.NET Forms Authentication for this.
When the Log Out button is clicked, call FormsAuthentication.SignOut. This will remove the forms-authentication ticket information from the cookie (or URL if cookieless).
For a timeout, use the timeout attribute in the system.web/authentication/forms element of your web.config. Note that your forms authentication timeout is independent of your Session timeout.
Case 1:
When clicked on the log off button clear the Session.
Clicking the back button in the browser might result in fetching the page from the cache. So by cheking Session in the page might not be effective. You can disable caching for the page so that when back button is clicked a new request to the page will be generated.
For pages not to be cached set this
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Case 2:
You can set the default timeout for Session as 10 minutes. See HttpSessionState.Timeout Property
Case 3:
Check Session for null and if found to be null then redirect to a login page.

ASP.NET: Authenticating user in code

I'm playing around with authentication and authorization to prepare for some task. I've created two pages: Login.aspx and Default.aspx. In config file i've set authentication to forms and denied unauthenticated users access:
<authentication mode="Forms">
<forms name="aaa" defaultUrl="~/Login.aspx" />
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Then I've written some simple code to authenticate my user in Login.aspx:
protected void Page_Load(object sender, EventArgs e)
{
GenericIdentity identity = new GenericIdentity("aga", "bbb");
Context.User = new GenericPrincipal(identity, new String[] { "User" }); ;
Response.Redirect("~/Default.aspx");
}
When i run it, the redirection doesn't take place. Instead Login.aspx is called over and over because the user is not authenticated (Context.User.Identity.IsAuthenticated is false at every load). What am i doing wrong?
Context.User only sets the principal for the current request. Once the redirect takes place, the current request ends and a new one begins with the non-overridden principal again (which is apparently not authenticated). So, setting Context.User doesn't actually authenticate anything.
Using FormsAuthentication.SetAuthCookie() will set the user's cookie to a valid value accepted by the FormsAuthentication provider, or put the token in the URL. You can redirect to your heart's content because the cookie obviously sticks with the user for future requests.
From MSDN (em added):
With forms authentication, you can use the SetAuthCookie method when you want to authenticate a user but still retain control of the navigation with redirects.
As stated, this does not necessarily require cookies - the name is a little misleading, because it will still work via the URL if FormsAuthentication is in cookieless mode:
The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection, or to the URL if CookiesSupported is false.
Use FormsAuthentication.SetAuthCookie(..). Or FormsAuthentication.RedirectFromLoginPage(..).
You need to actually set the user as authenticated. All of the following methods will work and let you actually get away from your login screen.
FormsAuthentication.Authenticate()
FormsAuthentication.RedirectFromLoginPage()
FormsAuthentication.SetAuthCookie()
Lots of ways to get to the same result.
You need to actually make a call to the formsAuthentication provider to set the login.
FormsAuthentication.RedirectFromLoginPage(txtUser.Text, chkPersistLogin.Checked)
is a simple example
After creating the dummy Context.User, you need to perform a FormsAuthentication.SetAuthCookie or RedirectFromLoginPage method.

After doing FormsAuthentication.SignOut(), user is not able to login again

I am using formAuthentication with the following Web.Config file.
<authentication mode="Forms">
<forms name="SnowBall" timeout="30" slidingExpiration="true" loginUrl="Login.aspx" cookieless="AutoDetect">
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
I have a user control which has a LogOut button. Code of the logout button is:
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
After executing this code, I am no longer able to authenticate the user. When i click "Sign In", the page is refreshed and event handlers are not executed.
When I close the browser window and re-run the site, everything works fine. Please help me.
First you need to clear that there are two separate Ids one is session id which is alloted for browser session and another is form authentication cookie which is encrypted alphanumeric id.
Whenever you use formauthentication.signout your formauthentication cookies will removed as per your implementation.But your session id will remain there.
You cancheck it by using fiddler/ firefox browser.
I have found the solution.Hope it helps somebody out there
Problem lies with this line
Response.Redirect("Login.aspx");
What it does is redirects user to Login.aspx with ReturnUrl as querystring.For Eg.
Login.aspx?ReturnUrl="Name of the page from where logout happened";
Now what happened was that FormsAuthentication.GetRedirectUrl() preserved this querystring path and after authentication was redirecting to this path.the user credentials i was putting in were not authorized to view this page.So i was always on the login screen.
To Resolve this issue replace
Response.Redirect("Login.aspx");
With
Response.Redirect(FormsAuthentication.LoginUrl);

Resources