in web.config code is
section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<forms loginUrl="Login.aspx" cookieless="UseCookies">
</forms>
</authentication>
whenever iam closing application and logging back user remains in and ask me to log out.. i want to make sure whenever application starts it should not be logged in previously..
this is web.config code..
<authentication mode="Forms">
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<forms loginUrl="Login.aspx" cookieless="UseCookies">
</forms>
</authentication>
<authorization>
<allow roles="Administrator,Attorney,Director of Operations,Office Manager,Paralegal,Partner,Processor,Salary Admin,Unit Manager"/>
<deny users="?"/>
</authorization>
<pages>
</pages>
</system.web>
Login button code
string [] arr = new string[10];
bool bCheckUser;
try
{
if ((txtUserName.Text == "") || (txtPassword.Text == ""))
{
lblError.Visible = true;
lblError.ForeColor = System.Drawing.Color.Red;
lblError.Text = "Enter UserName and Password";
}
else
{
bCheckUser = Membership.ValidateUser(txtUserName.Text, txtPassword.Text);
arr = Roles.GetRolesForUser(txtUserName.Text);
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
FormsAuthentication.Authenticate(txtUserName.Text, txtPassword.Text);
if (bCheckUser == true)
{
lblError.Visible = false;
Response.Redirect("MainMenu.aspx");
}
else
{
lblError.Visible = true;
lblError.ForeColor = System.Drawing.Color.Red;
lblError.Text = "You Username or Password is Invalid. Please try Again";
}
}
}
catch(Exception ex)
{
lblError.Text = ex.Message.ToString();
}
}
You are passing true to this method that is to create persistent cookies:
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, true);
pass false instead and also move that inside of if block and remove that redirect if you don't want hard redirect:
if (bCheckUser == true)
{
lblError.Visible = false;
// Response.Redirect("MainMenu.aspx");
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
}
Or use SetAuthCookie method like below:
if (bCheckUser == true)
{
lblError.Visible = false;
FormsAuthentication.SetAuthCookie(txtUserName.Text, false);
Response.Redirect("MainMenu.aspx");
}
Edit:
It looks like you are calling FormsAuthentication.RedirectFromLoginPage regardless of whether Membership.ValidateUser returns true or false. That might have something to do with it. Is this code being called in the Page_Load of your login page?
A couple of questions I have for you:
Are you actually closing the browser
and then reopening it, or just
returning to your site after
receiving an error in the same
browser?
Does your login page have a Remember
Me setting?
Have you restricted access to your
webpages in your webconfig?
By default I think the webconfig leaves most pages open. You'll need an authorization section to restrict access.
<authorization>
<deny users="?" />
</authorization>
Here's some links to check out as well:
http://ondotnet.com/pub/a/dotnet/2004/02/02/effectiveformsauth.html
http://www.asp.net/security/tutorials/an-overview-of-forms-authentication-vb
Related
I've got the following error when I have : in url address:
A potentially dangerous Request.Path value was detected from the client (:)
I want when my application get an error I can redirect to /Error/NotFound action but sometimes it doesn't happen.
For example, I have below code for handle custom errors and it works properly but when I have a potentially dangerous error controller.Execute() doesn't fire.
protected void Application_Error()
{
var lastException = Server.GetLastError();
if (lastException.GetType() != typeof(HttpException))
return;
var httpException = lastException as HttpException;
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
if (httpException?.GetHttpCode() == 404 || httpException?.GetHttpCode() == 400)
routeData.Values.Add("action", "NotFound");
if (routeData.Values.Count <= 1)
return;
try
{
IController controller = new ErrorController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
catch (NullReferenceException e)
{
Console.WriteLine(e.Message);
throw new NullReferenceException();
}
}
I realize that when a potentially dangerous error occurred some property of my context such as CurrentNotification, Handler, Items, Profile, Session and User is null. I don't know exactly my context is related to this problem or not.
And here is my webconfig:
<system.web>
<compilation debug="true" targetFramework="4.6.2" />
<httpRuntime targetFramework="4.6.2" maxRequestLength="314572800" enableVersionHeader="false" requestPathInvalidCharacters="<,>,%,&,:,\,?" />
</system.web>
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
</httpErrors>
</system.webServer>
you can handle all types of errors in your Web.Config like this :
<customErrors mode="On" defaultRedirect="~/Error/ErrorPage/404" >
<error statusCode="404" redirect="~/Error/ErrorPage/404" />
<error statusCode="403" redirect="~/Error/ErrorPage/403" />
<error statusCode="500" redirect="~/Error/ErrorPage/500" />
</customErrors>
what i added is the
defaultRedirect
to handle any type of errors
How to show a custom error page when an application error occurred without changing the url?
When application error occurs, then how to show customer a custom error page without routing to another Url?
Inside your web.config check that the configuration looks like:
<system.web>
...
<customErrors mode="On">
<error statusCode="404" redirect="~/custom404.html"/>
<customErrors
</system.web>
<customErrors mode="On" defaultRedirect="~/custom404.html">
</customErrors>
You can do this in code too. For a MVC project one can ovverride the Controller's function OnException, perform some logging and other stuff then load the contents from an Error.URL in background where the error information is formated.
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext != null && filterContext.Exception != null && !filterContext.ExceptionHandled)
{
ViewBag.Exception = filterContext.Exception;
filterContext.Result = View("~/Views/Shared/Error.cshtml");
filterContext.ExceptionHandled = true;
Log.Error(filterContext.Exception.Message +":" + filterContext.Exception.StackTrace);
}
}
In this snippet all Controllers in the project inherit from a BaseController where the function OnException is being overridden.
Try this in your Web.config file
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="/errors/error">
</customErrors>
In any error it will redirect to the /errors/error page. Please note the redirectMode attribute. With the value ResponseRewrite the url will not change.
Now, if you want to show a different page for a specific error, you can set it with the following.
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="/errors/error">
<error statusCode="404" redirect="/errors/error404" />
<error statusCode="500" redirect="/errors/error500" />
</customErrors>
I have the following code inside my action methods:-
public ActionResult ManageCustomerVLANs(string customerName)
{
if (!repository.IsCustomerExsists(customerName))
{
throw new HttpException(404, "Your error message");//RedirectTo NoFoundPage
}
And I have defined the following inside my web.config, to handle any 404 http code:-
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="NoCache" noStore="true" duration="0" varyByParam="*"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
<!--<customErrors mode="RemoteOnly"/>-->
<customErrors mode="RemoteOnly">
<error statusCode="404" redirect="~/Home/" />
</customErrors>
But currently if the action method return “throw new HttpException”, nothing is actually returned and the execution will continue after this “throe new HttpException”.
so can anyone advice, how I can return an http 404 ?
You can return 404 like this.
return new HttpStatusCodeResult(HttpStatusCode.NotFound);
i wrote a login menu and control panel for users,
but during short time it takes me out, see the codes
you know in the config file i wrote that "Admin" folder is secure and it's timeout is 30 minutes but when i'm logging maybe in 40-50 sec it take me out, where am i wrong ?
please help me
Web.config codes :
<authentication mode="Forms">
<forms name="MyAppCookie" path="/" loginUrl="Login.aspx" protection="All" timeout="60" defaultUrl="Admin" />
</authentication>
<authorization>
<allow users="*" />
</authorization>
<customErrors mode="Off" />
<pages validateRequest="false" enableEventValidation="false" viewStateEncryptionMode="Never" enableViewStateMac="false" />
<!--<sessionState timeout="1440"></sessionState>-->
</system.web>
<location path="Admin">
<system.web>
<authorization>
<deny users="?" />
<deny users="Users" />
</authorization>
</system.web>
</location>
Login Menu :
var login = (from u in DataContext.Context.Core_Users
where u.UserName == txtuid.Text && u.Password == txtPwd.Text
select u).FirstOrDefault();
if(login != null)
{
var role = (from r in DataContext.Context.Core_Roles
where r.RoleID == login.RoleID
select r).FirstOrDefault();
if(role != null)
{
string RoleName = role.RoleName;
FormsAuthenticationTicket AuthTicket = new FormsAuthenticationTicket(1, txtuid.Text, DateTime.Now, DateTime.Now.AddDays(1),false,RoleName,FormsAuthentication.FormsCookiePath);
string encryptedTocket = FormsAuthentication.Encrypt(AuthTicket);
HttpCookie AuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName,encryptedTocket);
Response.Cookies.Add(AuthCookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtuid.Text, chkRemember.Checked));
}
else
{
lblMessage.Text = "Role Deleted";
}
}
else
{
lblMessage.Text = "Wrong username or password";
}
And secure pages :
if (!IsPostBack)
{
//Start Authorization Section
if (!Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.RedirectToLoginPage();
}
// End of Authorization Section
}
Sessionstate timeout property is mentioned in minutes
In webconfig file...
<system.web>
.......
<sessionState timeout="1440"></sessionState>
</system.web>
The session will get expired if the webform is idle for 24 hrs continuously.
You can have this sessionstate block only within .
The following posts show how to setup the web.config for a site using Mixed Mode Authentication. IIS7 Mixed Mode Authentication and How to allow mixed-mode authentication in IIS 7.0.
I've got my site setup and working locally (on my developer machine). However, when I run it locally on the server I get 401.2 - Login failed due to server configuration error.
Anyone know how I'm supposed to configure the server, Default Web Site, and My Site?
Edit: Here are the settings in my web.config, including the loginUrl from the Forms authentication node.
<location path="~/Account/WinLogin.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
</system.web>
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false"/>
<windowsAuthentication enabled="true"/>
</authentication>
</security>
</system.webServer>
</location>
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/WinLogin.aspx" timeout="60"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
Let's start with server roles configuration (this is under server manager, roles, IIS)
You're gonna want to make sure that the windows auth and anonymous auth sections are enabled/installed, and also the forms auth (which presumably you already have). After those are installed/configured, you'll need to define the following stuff:
In your Web.Config you're going to want to have the following sections defined:
<configuration>
<system.web>
<authentication mode="Forms">
<forms cookieless="UseDeviceProfile" defaultUrl="~/Default.aspx" enableCrossAppRedirects="true" loginUrl="~/WindowsLogin.aspx" name=".ASPXAUTH" path="/" protection="All" requireSSL="false" slidingExpiration="true" timeout="10080"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
<location path="Login.aspx">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="true"/>
<windowsAuthentication enabled="false"/>
</authentication>
</security>
</system.webServer>
</location>
<location path="WindowsLogin.aspx">
<system.web>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
</system.web>
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="false"/>
<windowsAuthentication enabled="true"/>
</authentication>
</security>
</system.webServer>
</location>
</configuration>
Then you'll need two files:
Login.aspx (this does forms auth)
WindowsLogin.aspx (this does Windows auth)
LOGIN does forms, right, so that's just bog standard ASP.NET forms auth
It's WindowsLogin that does the magic (and here's that file)
using System;
using System.Web;
using System.Web.Security;
using App_Code.Biz;
public partial class WindowsLogin : System.Web.UI.Page {
protected string UserIsInRoles = string.Empty;
private static readonly BAL _mBAL = new BAL();
protected void Page_Load(object sender, EventArgs e) {
string redirectUrl = Request["returnurl"] ?? "~/default.aspx";
string username = Request.ServerVariables["LOGON_USER"];
try {
if ( Roles.GetRolesForUser( username ).Length < 1 )
Roles.AddUserToRole( username, Global.defaultRole );
int status;
_mBAL.aspnet_Membership_CreateUser( username, out status );
} catch ( Exception ex ) {
ErrHandler.WriteXML( ex );
}
/* Test to see if the user is in any roles */
if ( Roles.GetRolesForUser( username ).Length < 1 ) {
UserIsInRoles = "<br />" + username + "You are not in any rules. This must be your first visit to our site!<br /> Adding you to the " + Global.defaultRole + " role now!";
} else {
UserIsInRoles = "You are in the following roles: ";
string[] roles = Roles.GetRolesForUser( username );
foreach ( string role in roles )
UserIsInRoles += role + ", ";
UserIsInRoles = UserIsInRoles.Remove( UserIsInRoles.Length - 2 ) + "!";
if ( Login( username, String.Join( ",", roles ) ) )
Response.Redirect( redirectUrl );
}
//we shouldn't get here, so if we do, redirect back to a page they can use.
if ( Page.IsPostBack ) {
if ( Response.StatusCode == 401 )
Response.Redirect( "~/Login.aspx" );
}
}
private bool Login(string strUser, string strRole) {
if ( strRole != null ) {
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // version
strUser, // user name
DateTime.Now, // create time
DateTime.Now.AddYears(1), // expire time
false, // persistent
strRole ); // user data
string strEncryptedTicket = FormsAuthentication.Encrypt( ticket );
HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, strEncryptedTicket );
Context.Response.Cookies.Add( cookie );
return true;
}
return false;
}
}
After all this, you might get a config error for section locked at a parent level. Lock is either by default (overrideModeDefault="Deny") or set explicitly by a location tag ... and if so, then the fastest way to fix that is to open C:\Windows\System32\inetsrv\config\applicationHost.config and edit the following block:
<configSections>
<sectionGroup name="system.webServer">
<sectionGroup name="security">
<sectionGroup name="authentication">
<section name="anonymousAuthentication" overrideModeDefault="Allow">
<section name="windowsAuthentication" overrideModeDefault="Allow">
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
Also see the chat log: https://chat.stackoverflow.com/rooms/5/conversation/configuring-iis7-and-mixed-mode-authentication-in-asp-net