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>
Related
I'm working on an ASP.net MVC project using EF in combination with MySql. Now this works just fine on its own but I also want to reference another class library that uses EF with SQL.
When I reference the library EF seems to get confused on what provider to use for each DbContext.
On my MySql DbContext I have the following attribute in order to tell EF this DbContext should be handled by the MySql provider:
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
Now on the SQL DbContext, I have no attribute. Should I place one on there and if so which one?
Currently, I get the following error:
The default DbConfiguration instance was used by the Entity Framework
before the 'MySqlEFConfiguration' type was discovered. An instance of
'MySqlEFConfiguration' must be set at application start before using
any Entity Framework features or must be registered in the
application's config file.
This is pretty straightforward since the SQL context is used before the MySql one but I can't seem to find a fix on this.
What would be 'Best Practice' on handling this? Or is this something that I should avoid, combining 2 DbContexts in the same project?
MySql DbContext
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class MySqlContext : DbContext
{
public MySqlContext() : base("name=MySqlContext")
{
this.Configuration.LazyLoadingEnabled = false;
}
//DbSets....
}
SQL DbContext
public class SqlContext : DbContext
{
public SqlContext() : base("name=SqlContext")
{
Configuration.LazyLoadingEnabled = false;
}
//DbSets....
}
Web.config:
<connectionStrings>
<add name="SqlContext" connectionString="some connectionString" providerName="System.Data.SqlClient" />
<add name="MysqlContext" connectionString="some connectionString" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d"></provider>
</providers>
</entityFramework>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.9.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
I see on the DbProviderFactories it's only saying Mysql.
It's not important that how many DbContexts you have(In entity framework 6). Just put connection strings in appConfig or webConfig of startup project.
Example of appConfig with two connectionString with Ef 6.01 & Sql Server and My SQL
<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="MySqlDB" connectionString="Your My SQL ConnectionString" providerName="My Sql Provider" />
<add name="SqlDB" connectionString="Your SQL ConnectionString" providerName="Sql Provider" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
MySql DbContext
public class MySqlContext : DbContext
{
public MySqlContext() : base("MySqlDB")
{
this.Configuration.LazyLoadingEnabled = false;
}
//DbSets....
}
SQL DbContext
public class SqlContext : DbContext
{
public SqlContext() : base("SqlDB")
{
Configuration.LazyLoadingEnabled = false;
}
//DbSets....
}
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
I'm trying to authenticate users through LDAP in C#. Each time I try to log in, I get the 'Input string was not in a correct format' error.
This is my connection string:
<connectionStrings>
<add name="MyConnectionString" connectionString="LDAP://123.193.111.22:389.local" />
</connectionStrings>
<system.web>
<roleManager enabled="true" />
<membership defaultProvider="MyMembershipProvider"><providers>
<add name="MyMembershipProvider"
connectionStringName="MyConnectionString"
type="System.Web.Security.ActiveDirectoryMembershipProvider,
System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
connectionUsername="MyUsername"
connectionPassword="MyPassword"
connectionProtection="Secure"
enableSearchMethods="true" />
</providers>
</membership>
<trust level="Full" />
</system.web>
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Admin/Login"
timeout="450" slidingExpiration="false" protection="All"/>
</authentication>
The error seems to be at type="System.Web.Security.ActiveDirectoryMembershipProvider. Any suggestions would be greatly appreciated. Thanks!
I've managed to figure it out. Had to rework the membership provider code and now I'm able to authenticate users.
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.