Working on a MVC5 project, I have access to the account / login page. When I enter wrong credentials it tells me that the username / password is incorrect. When I enter the right credentials it redirects me to home/index so I assume the login did work.
How ever upon getting to the new page I get the following error.
HTTP Error 401.0 - Unauthorized.
Ant i'm not sure how I would go on and solve this.
My Login Controller
public ActionResult LogIn()
{
return View();
}
[HttpPost]
public ActionResult LogIn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
And my model
public class LogOnModel {
[Required]
[DisplayName("User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string Password { get; set; }
[DisplayName("Remember me?")]
public bool RememberMe { get; set; }
}
public interface IFormsAuthenticationService {
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public class FormsAuthenticationService : IFormsAuthenticationService {
public void SignIn(string userName, bool createPersistentCookie) {
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
And last my web.config:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="SaleswebEntities" connectionString=
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<appSettings>
<add key="ClientValidationEnabled" value="false" />
<add key="UnobtrusiveJavaScriptEnabled" value="false" />
</appSettings>
</configuration>
The connection string is not empty, but I did remove it I do not want it posted public.
I've had a simular issue and it were nothing with the code, something did happen with my iis and I had to reinstall it. The key thing here is to make sure you uninstall the Windows Process Activation Service or otherwise your ApplicationHost.config will be still around.
I have noticed that you use FormsService in your Login Controller. I think that this class is SharePoint-specific. I would recommend using WebSecurity.Login() or FormsAuthentication.Authenticate() instead.
Have you checked that your Startup.cs has configured the application correctly?
There should be something similar to the following in there:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
Sounds like a IIS permission issue, you should try running VS as administrator if you have not already.
" HTTP Error 401.0 - Unauthorized
You do not have permission to view this directory or page."
Diagnose 401.x HTTP errors on IIS
Try to make sure permissions are correct for the folders.
Double-click the Authentication feature in IIS. Right-click the "Anonymous Authentication" provider and select edit. Now, right-click the web application in the left pane, select Edit Permissions..., select the Security tab, click Edit -> Add and add IIS APPPOOL\NameOfAppPool. Make sure the Application Pool Identity has read and execute permissions of the folder.
Here are a few links.
Configuring IIS (Windows 7) for ASP.NET / ASP.NET MVC 3
http://patrickdesjardins.com/blog/asp-net-mvc-http-error-401-0-unauthorized
https://serverfault.com/questions/348049/iis-and-http-401-0-unauthorized
Related
I am using formsauthentication on my MVC project and when testing locally using the Visual Studio Development Server everything works as expected. Once deployed to IIS 7.5 the HTTPContext.User is causing NullReferenceExceptions.
Both Dev and Prod machines are using the same SQL db (at the moment - this will change post-deployment of course) so I know it is not a problem with the DB or data within.
This must be a setting in IIS or my web.config but I cannot find it.
I've tried various changes to my web.config(from suggestions I've found around SE), here is part of my web.config for the current implementation:
<appSettings>
<add key="autoFormsAuthentication" value="true" />
<add key="enableSimpleMembership" value="false" />
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
****Snip****
<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" cookieless="UseCookies"/>
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="ProjectSquid.WebUI.HTMLHelpers" />
</namespaces>
</pages>
<roleManager enabled="true" defaultProvider="CustomRoleProvider">
<providers>
<clear />
<add name="CustomRoleProvider"
type="Project.Domain.Filters.CustomRoleProvider"
connectionStringName="EFDbContext"
enablePasswordRetrieval="false"
cacheRolesInCookie="true"/>
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="EFDbContext" />
</providers>
</sessionState>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=9" />
</customHeaders>
</httpProtocol>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<modules runAllManagedModulesForAllRequests="false">
<remove name="FormsAuthentication" />
<remove name="DefaultAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="" />
<add name="DefaultAuthentication" type="System.Web.Security.DefaultAuthenticationModule" preCondition="" />
<remove name="UrlRoutingModule-4.0"/>
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" preCondition="" />
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
</modules>
</system.webServer>
What could cause HttpContext.User to differ from the VS Development Server and the IIS 7.5 implementation?
EDIT:
HttpContext is fed through the inherited BaseController:
protected virtual new CustomPrincipal User
{
get { return HttpContext.User == null? null : HttpContext.User as CustomPrincipal; }
}
public new HttpContextBase HttpContext
{
get
{
return ControllerContext == null ? null : ControllerContext.HttpContext;
}
}
The cookie isn't created until the PostAuthenticationRequest:
public void MvcApplication_PostAuthenticationRequest(object sender, EventArgs e)
{
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
string encTicket = authCookie.Value;
if (!String.IsNullOrEmpty(encTicket))
{
var ticket = FormsAuthentication.Decrypt(encTicket);
var id = new UserIdentity(ticket);
string[] userRole = Roles.GetRolesForUser(id.Name);
var prin = new CustomPrincipal(id);
HttpContext.Current.User = prin;
Thread.CurrentPrincipal = prin;
}
}
}
The authentication itself appears to be working fine as the function causing the exception starts with [Authorize] and successfully begins executing but fails as null when it reaches the first User reference:
int userT = User.Team.TeamId;
In this context the User being CustomPrincipal BaseController.User.
EDIT2:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880"
cookieless="UseCookies"
name=".ASPXAUTH"
protection="All"
slidingExpiration="true"/>
</authentication>
EDIT3
Custom IIdentity:
[Serializable]
public class UserIdentity : MarshalByRefObject, IIdentity
{
private readonly FormsAuthenticationTicket _ticket;
public UserIdentity(FormsAuthenticationTicket ticket)
{
_ticket = ticket;
}
public string AuthenticationType
{
get { return "Custom"; }
}
public bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(this.Name); }
}
public string Name
{
get { return _ticket.Name; }
}
public string UserId
{
get { return _ticket.UserData; }
}
public bool IsInRole(string Role)
{
return Roles.IsUserInRole(Role);
}
public IIdentity Identity
{
get { return this; }
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (context.State == StreamingContextStates.CrossAppDomain)
{
GenericIdentity gIdent = new GenericIdentity(this.Name, this.AuthenticationType);
info.SetType(gIdent.GetType());
System.Reflection.MemberInfo[] serializableMembers;
object[] serializableValues;
serializableMembers = FormatterServices.GetSerializableMembers(gIdent.GetType());
serializableValues = FormatterServices.GetObjectData(gIdent, serializableMembers);
for (int i = 0; i < serializableMembers.Length; i++)
{
info.AddValue(serializableMembers[i].Name, serializableValues[i]);
}
}
else
{
throw new InvalidOperationException("Serialization not supported");
}
}
Custom IPrincipal:
interface ICustomPrincipal : IPrincipal
{
int Id { get; set; }
string Name { get; set; }
string Role { get; set; }
}
public class CustomPrincipal : IPrincipal
{
public CustomPrincipal(UserIdentity identity)
{
this.Identity = identity;
}
public IIdentity Identity { get; private set; }
Most likely, you are attempting to retrieve HttpContext.User before it has been initialized. This behavior differs between IIS Classic (or the Visual Studio Web Server) and IIS Integrated pipeline modes, which would explain why you are seeing different behavior between the environments.
Explanation
HttpContext is part of an application's runtime state. In modern hosting environments (IIS integrated pipeline mode and OWIN), HttpContext is not populated until after the Application_Start method is complete. Any behavior that you have that requires HttpContext.User should not be executed until the Application_BeginRequest event or after.
Reference: Request is not available in this context
It's not clear from your post since configuring the authentication depends on various settings in your project plus the configuration file. For example in Web.config file, there are several places to customize/configure the authentication like this one (the most important rule) that you haven't placed in your post:
<system.web>
<authentication mode="" />
</system.web>
As you know, since the configuration system is based on a hierarchical system of management system that uses **.config* files, you should consider the defaults, perhaps by <remove/> or <add/> some parameters. The configuration files for IIS 7 and later are located in your %WinDir%\System32\Inetsrv\Config folder, and the primary configuration files are:
ApplicationHost.config - This configuration file stores the settings for all your Web sites and applications.
Administration.config - This configuration file stores the settings for IIS management. These settings include the list of
management modules that are installed for the IIS Manager tool, as
well as configuration settings for management modules.
Redirection.config - IIS 7 and later support the management of several IIS servers from a single, centralized configuration file.
This configuration file contains the settings that indicate the
location where the centralized configuration files are stored.
Note: Some settings can be delegated to Web.config files, which may override settings in the ApplicationHost.config file. In addition, settings that are not delegated cannot be added to Web.config files.
Tip: A default installation of IIS 7 does not contain Digest authentication, so adding the settings for Digest authentication to your ApplicationHost.config will have no effect or may cause errors until the Digest authentication module is installed.
You need to see both local and deployment configurations to meet your purpose. If you have trouble with integrated pipeline, see the following pages to take its advantages :
Debugging the IIS7 integrated pipeline with failed request
tracing
How to Take Advantage of the IIS 7.0 Integrated Pipeline
Update About SlidingExpiration : According to MSDN:
Sliding expiration resets the expiration time for a valid
authentication cookie if a request is made and more than half of the
timeout interval has elapsed.
If the cookie expires, the user must re-authenticate. Setting the SlidingExpiration property to false can improve the security of an application by limiting the time for which an authentication cookie is valid, based on the configured timeout value. So I think there's no need to use this as false. This means It will expire cache after time period at the time of activating cache if any request is not made during this time period. This type of expiration is useful when there are so many data to cache. So It will put those items in the cache which are frequently used in the application. So it will not going to use unnecessary memory.
I have created a membership database using the asp_regsql.exe tool instead of the default wizard on an existing database.
When I create new user account with membership createuser method for aspnetdb membership database, I get below error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
I am using VS 2013.
my aspnetdb database name is : SecurityTutorials.mdf
my web.config setting :
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="newsdbConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\newsdb.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="SecurityTutorialsConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\SecurityTutorials.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
my CreatingUserAccounts.aspx.cs code is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Web.UI.HtmlControls;
public partial class Membership_CreatingUserAccounts : System.Web.UI.Page
{
const string passwordQuestion = "What is your favorite color";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) SecurityQuestion.Text = passwordQuestion;
}
protected void CreateAccountButton_Click(object sender, EventArgs e)
{
MembershipCreateStatus createStatus;
MembershipUser newUser = System.Web.Security.Membership.CreateUser(Username.Text,
Password.Text,
Email.Text,
SecurityQuestion.Text,
SecurityAnswer.Text,
true, out createStatus);
switch (createStatus)
{
case MembershipCreateStatus.Success:
CreateAccountResults.Text = "The user account was successfully created!";
break;
case MembershipCreateStatus.DuplicateUserName:
CreateAccountResults.Text = "There already exists a user with this username.";
break;
case MembershipCreateStatus.DuplicateEmail:
CreateAccountResults.Text = "There already exists a user with this email address.";
break;
case MembershipCreateStatus.InvalidEmail:
CreateAccountResults.Text = "There email address you provided in invalid.";
break;
case MembershipCreateStatus.InvalidAnswer:
CreateAccountResults.Text = "There security answer was invalid.";
break;
case MembershipCreateStatus.InvalidPassword:
CreateAccountResults.Text = "The password you provided is invalid. It must be seven characters long and have at least one non-alphanumeric character.";
break;
default:
CreateAccountResults.Text = "There was an unknown error; the user account was NOT created.";
break;
}
}
}
you should add below lines to <system.web></system.web> block,and of course customize the code as you need
<authentication mode="Forms">
<forms name="/.ASPXAUTH" loginUrl="~/ui/public/ads.aspx" defaultUrl="~/ui/Public/ads.aspx" protection="All" timeout="525600" path="/" requireSSL="false" slidingExpiration="true" cookieless="UseDeviceProfile"/>
</authentication>
<roleManager enabled="true"/>
<membership defaultProvider="AspNetSqlMembershipProvider" userIsOnlineTimeWindow="30" hashAlgorithmType="">
<providers>
<clear/>
<add connectionStringName="LocalSqlServer" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false" applicationName="/" requiresUniqueEmail="True" passwordFormat="Encrypted" maxInvalidPasswordAttempts="15" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</membership>
I'm deploy my MVC 3 application to a server and, after solve several issues related with missing MVC dlls (the server does not have MVC installed) it start to give a error:
Firefox "The page isn't redirecting properly"
Chrome "This webpage has a redirect loop"
IE "This page can't be displayed"
I found people saying that it is something cookie related, but I can't understand how to solve the problem.
I never see the default page whether.
I suspect there is a problem with my Global.asax file or my Web.Config.
Global.asax:
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
And there is a part of my Web.Config without AppSettings, connectionStrings and system.serviceModel:
<system.web>
<compilation debug="true" defaultLanguage="c#" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<customErrors mode="Off">
<error statusCode="404" redirect="/Error/PageNotFound" />
</customErrors>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="UrlRoutingHandler" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Index action from Login page:
public ActionResult Index()
{
if (CurrentAuthenticatedData != null && CurrentAuthenticatedData.User != null)
ViewBag.IsLogin = true;
else
ViewBag.IsLogin = false;
return View();
}
CurrentAuthenticatedData:
System.Web.Routing.RequestContext Ctx = null;
public AuthenticatedData CurrentAuthenticatedData
{
get
{
AuthenticatedData retval = null;
if (Ctx.HttpContext.User.Identity.IsAuthenticated)
{
retval = (AuthenticatedData)ViewBag.Auth;
}
return retval;
}
}
AuthenticatedData is a class where I store several attributes related to logged user.
And finally my View code:
#{
ViewBag.Title = "Index";
}
<h2>Efetuar Login</h2>
#using (Html.BeginForm())
{
<div style="#(ViewBag.IsLogin??false ? "display: none" : "")">
#Html.ValidationMessage("Error")
<p>Username:<input type="text" name="usr" /></p>
<p>Password:<input type="password" name="pwd" /></p>
<p>
<input type="submit" value="Login" />
</p>
</div>
}
I try to deploy a dummie MVC application and it works! =/
Can you help me?
Thanks
There's probably a problem with your MVC installation. Make sure you install MVC correctly.
I'm guessing that your routes are not properly registered and thus if you go to your app's home page it will show you a 404. This gets picked up by this line in the web.config:
<error statusCode="404" redirect="/Error/PageNotFound" />
and redirects you to that page, which also throws a 404, redirecting you again to the same page, and so on and so on, causing the redirect loop.
For debugging purposes, you could comment out that line and check whether your routes are registered or not.
I discover that MVC runs a method called Initialize, in my BaseController, before any other:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
...
}
Inside that method I has a verification to know if user is authenticated and when not I do a Session.Abandon(); and a strange thing (I don't know why):
if (!requestContext.HttpContext.Request.CurrentExecutionFilePath.Equals("/MyWebSite/"))
Response.Redirect("~/", true);
It runs me into a infinite loop because the request page was MyNewWebsite insted MyWebSite...
Sorry and thank you for your patience
I am trying to make an access role in my system. I have these two roles ; Admin and user. In my login page, I put this line of code:
if (Roles.IsUserInRole(Login1.UserName, "Administrator"))
Response.Redirect("~/4_Admin/Page1.aspx");
else if (Roles.IsUserInRole(Login1.UserName, "Users"))
Response.Redirect("~/3_User/Expense.aspx");
When user role logged in, they are directed to the correct page but for the admin, it gives me this error,
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Self_studies/login.aspx
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="Connection" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" applicationName="SampleApplication"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="Connection" applicationName="SampleApplication"/>
</providers>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="Connection" applicationName="SampleApplication"
name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
</providers>
</roleManager>
<compilation debug="false">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Forms" />
I think I have checked the name and went through all the coding for so many times. Is there anything that I can do to fix this? Thank you.
Reference this- Examining ASP.NET's Membership, Roles, and Profile
try to configure your role manager as:
<roleManager enabled="true"
defaultProvider="CustomizedRoleProvider">
<providers>
<add name="CustomizedRoleProvider"
type="System.Web.Security.SqlRoleProvider"
connectionStringName="MyDB"
applicationName="/" />
</providers>
</roleManager>
and at login button check user role as: Ref: Validation on current user
if (HttpContext.Current.User.IsInRole("Administrators"))
Response.Redirect("~/PageA.aspx");
else
Response.Redirect("~/PageB.aspx");
I made a new MVC3 application and it's hosted on WinHost's basic plan.
The gist of the problem is, the app pool memory limits are reached and every session InProc is erased, meaning my users are logged out.
As per their documentation, I see this:
http://support.winhost.com/KB/a626/how-to-enable-aspnet-sql-server-session-on-your-web.aspx
Here is the contents of my web.config after following the steps outlined above:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<connectionStrings>
<!-- REMOVED FOR PRIVACY -->
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<sessionState mode="SQLServer"
allowCustomSqlDatabase="true"
cookieless="false"
timeout="2880"
sqlConnectionString="data Source='tcp:s407.winhost.com';database='DB_41_xx';user id='DB_11_xx_user'; password='xx';" />
<trust level="Full"/>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/" timeout="2880"/>
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers"/>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.8.0" newVersion="4.0.8.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Here lies the problem:
My users are still getting logged of after some time. I thought using SQL for the session would prevent this issue.
Here is the relevant bit of code on how I'm loggin my users in:
[HttpPost]
public ActionResult Login(LogOnModel model)
{
using (EfAccountRepository accountRepository = new EfAccountRepository())
{
if (accountRepository.ValidateCredentials(model.Email, model.Password))
{
FormsAuthentication.SetAuthCookie(model.Email, true);
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "Your email or password is incorrect.");
return View(model);
}
And here is some code I use to see if the user is logged in:
public static MvcHtmlString AdminDashboardLink()
{
if (SecurityHelpers.UserIsPartOfCompany(HttpContext.Current))
{
string html = "<li><a href='/Admin'>ADMIN DASHBOARD</a></li>";
return new MvcHtmlString(html);
}
else
{
return new MvcHtmlString("");
}
}
public static bool UserIsPartOfCompany(HttpContext context)
{
if (!context.Request.IsAuthenticated)
return false;
using (EfAccountRepository accountRepository = new EfAccountRepository())
{
var loggedInUser = accountRepository.FindByEmail(context.User.Identity.Name);
string[] userRoles = accountRepository.GetRolesForUser(loggedInUser.AccountId);
return userRoles.Contains("Editor") || userRoles.Contains("Finance") || userRoles.Contains("Administrator");
}
}
Any suggestions? Maybe my web.config is botched and this is causing issues. Maybe I also needed to remove something after I added in the session information?
It is caused some times because the garbage collector cleans the machine key assigned to your application and assigns a new key that causes the looged in users to log out. Solution is to generate a machineKey for your application and place it in the web.config under system.web like
<system.web>
<machineKey validationKey="###YOUR KEY HERE ###"
decryptionKey="## decrypt key here ##"
validation="SHA1" decryption="AES" />
...
...
this link may help you http://aspnetresources.com/tools/machineKey
Forms auth is not session related, at all. It has nothing to do with session state. Everything required is stored in the forms auth cookie.
Your timeout above is set to 2880, so 48 hours i.e. two days so I would expect timeouts to happen.