MVC 3 FormsAuthentication Not working when deployed - asp.net-mvc-3

I have an MVC 3 Application that works fine in my dev environment (you
must have heard that before..) I am deploying it to a free hosting
service http://somee.com for testing, the .NET framework is set to
4. I have a custom membership provider. I am able to register a user, as I can see it in the database, but the user never gets authenticated. I always get redirected to the LogOn page, either after the registration or when loging on. I have done a bin deployment and have this dlls in my bin folder:
•System.Web.Mvc
•Microsoft.Web.Infrastructure
•System.Web.Razor
•System.Web.WebPages
•System.Web.WebPages.Razor
•System.Web.Helpers
In the config:
...
<add key="loginUrl" value="~/Account/Logon" />
</appSettings>
....
<membership defaultProvider="ServiceMembershipProvider">
<providers>
<clear/>
<add name="ServiceMembershipProvider"
type="Infrastruture.ServiceMembershipProvider, Infrastruture" />
</providers>
</membership>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
The controllers:
[HttpPost]
public ActionResult Register(FormCollection registration)
{
try
{
if (ModelState.IsValid)
{
var registrationViewModel = MapFormToRegistrationViewModel(registration);
companyManager.RegisterCompany(registrationViewModel);
FormsAuthentication.SetAuthCookie(registrationViewModel.SystemUserViewModel.Email, false);
return RedirectToAction("Welcome", "Home");
}
else
{
ModelState.AddModelError("", "LogId already taken");
}
}
catch(Exception ex)
{
return View("Register", new RegistrationViewModel(dataReferenceService));
}
return View("Register", new RegistrationViewModel(dataReferenceService));
}
/* /Home/Welcome */
[Authorize]
public ActionResult Welcome()
{ return View(); }
Running out of ideas now ...

I know this is an old question but I had a similar problem and found this while searching for the answer.
The solution is to add the following setting to your web config file.
<appSettings>
<add key="enableSimpleMembership" value="false"/>
</appSettings>
The reason this is required is some pre application startup code appears to have some issues with default settings.
A better explaination and the place I found this solution is here

Related

keep getting The view "Error" not found when using Elmah and asp.net mvc 4

I am using Elmah 1.2 as the logging framework for my asp.net mvc 4 application.
in the web.config file, I set customErrors mode to on.
<customErrors mode="On" defaultRedirect="/Error">
<error statusCode="404" redirect="/Error/NotFound" />
</customErrors>
I also created a custom HandleErrorAttribute, copied the code from this link.
http://joel.net/logging-errors-with-elmah-in-asp.net-mvc-3--part-4--handleerrorattribute
In my Home controller, i just throw an exception to test the logging framework.
public ActionResult About()
{
throw new Exception("this is a buggggggggggggg");
ViewBag.Message = "Your app description page.";
return View();
}
"this is a buggggggggggggg" is logged in the database, great, it works. then there's another error also logged, and I didnt expect that to happen.
The view 'Error' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/Home/Error.aspx ~/Views/Home/Error.ascx ~/Views/Shared/Error.aspx ~/Views/Shared/Error.ascx ~/Views/Home/Error.cshtml ~/Views/Home/Error.vbhtml ~/Views/Shared/Error.cshtml ~/Views/Shared/Error.vbhtml
Update:
follow Tim's suggestion, then it causes another issue.
If I create a Error.cshtml in the shared folder. when unhandled exception happens, it will show this Error.cshtml file, not "/Error" page. I have customErrors enabled. They should all get redirected to "/Error" page.
We created an empty MVC5 app and added ELMAH to it. We also were receiving the extra error you described even though we did not add the HandleErrorAttribute. After some research I found the nuget package Elmah.MVC which adds some additional configuration settings. In the appSettings section of web.config you will find these 2 lines:
<appSettings>
<add key="elmah.mvc.disableHandler" value="false" />
<add key="elmah.mvc.disableHandleErrorFilter" value="false" />
</appSettings>
These 2 keys default to "false". I changed their values to "true" and the extra logged exception went away.
I am developing an application using ASP.NET MVC 5 RC and I use Elmah too for error logging. I am using too a custom error handling attribute to redirect errors to a custom action on a custom controller, but mine doesn't look like the one shown in the link you provided.
However I had the same problem: Elmah was properly logging the error, but was also adding a "Error view not found" entry. I solved this by adding the following line to the OnException method on the attribute:
filterContext.ExceptionHandled = true;
For completeness, this is the complete code for the custom error handling attribute I am using:
public class CustomHandleErrorAttribute: HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
if(filterContext.HttpContext.Request.IsAjaxRequest()) {
filterContext.HttpContext.Response.StatusCode =
(int)HttpStatusCode.InternalServerError;
filterContext.Result = new ContentResult() {
Content = "Server error",
ContentType = "text/plain"
};
}
else {
filterContext.Result = new RedirectToRouteResult(
"Default",
new System.Web.Routing.RouteValueDictionary(new
{
controller = "Error",
action = "ApplicationError"
}));
}
}
}

User.Identity.Name is null after authenticate via WIF

I'm using WIF to log in my appication. Everything seems to be ok (logging,redirecting to site etc),but when i try use User.Identity.Name in my cod exception is being thrown-User is null.Any ideas what i'm doing wrong? I work on VS 2012. Generated part in web.config looks like below:
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="http://xxx/" />
</audienceUris>
<issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<trustedIssuers>
<add thumbprint="yyyy" name="https://zzz" />
</trustedIssuers>
</issuerNameRegistry>
</identityConfiguration>
</system.identityModel>
and:
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="false" />
<wsFederation passiveRedirectEnabled="true" issuer="https://zzz/Secure/FederatedLogin.ashx" realm="http://xxx" requireHttps="false" />
</federationConfiguration>
</system.identityModel.services>
When working with WIF you should use Thread.CurrentPrincipal.Identity.Name instead of User.Identity.Name.
Read more here: http://msdn.microsoft.com/en-us/magazine/ff872350.aspx to learn more about Windows Identity Foundation
Check that the STS includes a Name claim for the user, else User.Identity.Name will be null.
Instead I used:
namespace System.Security.Claims
{
public static class System_Security_Claims_Extensions
{
public static string getName(this ClaimsIdentity ci)
{
foreach (Claim c in ci.Claims)
{
if (c.Type == ClaimTypes.Name)
{
return c.Value;
}
}
return string.Empty;
}
}
}
And used in this context
((ClaimsIdentity)Thread.CurrentPrincipal.Identity).getName()

Removing headers from the response

I need to cloak certain headers generated by ASP.NET and IIS and returned in the responses from a ASP.NET WebAPI service. The headers I need to cloak are:
Server
X-AspNet-Version
X-AspNetMvc-Version
X-Powered-By
The service was earlier hosted in WCF, and the cloaking was done in an HttpModule by subscribing to PreSendRequestHeaders and manipulating HttpContext.Current.Response.Headers. With ASP.NET WebAPI everything is now task based, so HttpContext.Current is null. I tried to insert a message handler and manipulate the returned HttpResponseMessage, but the headers were not present on that stage. X-Powered-By can be removed in the IIS settings, but what is the suggested way to remove the rest of them?
The problem is each one is added at a different point:
Server: added by IIS. Not exactly sure if it can be turned off although you seem to have been to remove it using HttpModule .
X-AspNet-Version: added by System.Web.dll at the time of Flush in HttpResponse class
X-AspNetMvc-Version: Added by MvcHandler in System.Web.dll. It can be overridden so this one should be OK.
X-Powered-By by IIS but can be turned off as you said.
I think your best bet is still using HttpModules.
For the benefit of those who land here through a google/bing search::
Here's the summary of steps:
Step 1: Create a class that derives from IHttpModule (and IDisposable to clean up when we're done):
public class MyCustomModule : IHttpModule, IDisposable
{
private HttpApplication _httpApplication
private static readonly List<string> HeadersToCloak = new List<string>
{
"Server",
"X-AspNet-Version",
"X-AspNetMvc-Version",
"X-Powered-By"
};
..
}
Step 2: Get a reference to the intrinsic context in the IHttpModule.Init method, and assign an event handler to the PreSendRequestHeaders event:
public void Init(HttpApplication context)
{
_httpApplication = context;
context.PreSendRequestHeaders += OnPreSendRequestHeaders;
}
Step 3: Now the headers can be removed like so:
private void OnPreSendRequestHeaders(object sender, EventArgs e)
{
if (null == _httpApplication)
{
return;
}
if (_httpApplication.Context != null)
{
var response = _httpApplication.Response;
HeadersToCloak.ForEach(header => response.Headers.Remove(header));
}
}
Step 4: Now register this module in your root web.config under the system.webserver (if running IIS 7.0 integrated mode more details here):
<configuration>
<system.webServer>
<modules>
<add name="MyCustomModule" type="<namespace>.MyCustomModule "/>
</modules>
</system.webServer>
</configuration>
Hope this helps!
If you're using IIS7 / Azure then have a look at this:
Removing/Hiding/Disabling excessive HTTP response headers in Azure/IIS7 without UrlScan
It shows the best way to disable these headers without using HttpModules.
if you like to remove version go to web.config file
and add these lines
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<!--enableVersionHeader remove the header-->
<httpRuntime targetFramework="4.5.2" enableVersionHeader = "false"/>
also, add these
<httpProtocol>
<customHeaders>
<!--enableVersionHeader remove the header-->
<remove name ="X-Powered-By"/>
</customHeaders>
</httpProtocol>

When using MVC3 + SQL CE I get 404 on all pages with scaffolding against the SQL CE Database

The problem only occurs on a server with Windows 2008 Server, locally I run the application and have no issues. I've used the "bin deploy" and "Add Deployable Dependencies..." options and still no luck. Some more context...
The security settings in IIS are set for Windows Authentication, the web.config has a small exclude of anonymous users (not sure this even makes a difference in this scenario).
<authentication mode="Windows" />
In the Global.asax.cs file I have the standard template generated code.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("elmah.axd");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
The only addition I've made is for elmah and the favicon. I'm not sure what else to look at from this point forward, so any help would be appreciated.
Also, my connection string to the SQL CE looks like this:
<add name="BillingLogDbEntities" connectionString="metadata=res://*/Models.BillingLog.csdl|res://*/Models.BillingLog.ssdl|res://*/Models.BillingLog.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\BillingLogDb.sdf"" providerName="System.Data.EntityClient" />
<add name="BillingLocalDbEntities" connectionString="metadata=res://*/Models.BillingLocal.csdl|res://*/Models.BillingLocal.ssdl|res://*/Models.BillingLocal.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\BillingLocalDb.sdf"" providerName="System.Data.EntityClient" />
<add name="OverlayServicesDbEntities" connectionString="metadata=res://*/Models.OverlayServices.csdl|res://*/Models.OverlayServices.ssdl|res://*/Models.OverlayServices.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\OverlayServicesDb.sdf"" providerName="System.Data.EntityClient" />
The solution was a combination of two things:
I needed to set the appropriate permissions on the directory that the SQL Server CE files were located inside of.
The Entity Framework needed regenerated to point a the SQL CE databases again. For some reason the application was actually swallowing the errors that were simply a "couldn't connect to the X database" Something in some of the generated code had gotten out of sync.

Configuring session on windows azure

I m using the local system to test session on windows azure. I have done the following config in web.config
<appSettings>
<!-- account configuration -->
<add key="TableStorageEndpoint" value="http://127.0.0.1:10002/devstoreaccount1/" />
<add key="BlobStorageEndpoint" value="http://127.0.0.1:10000/devstoreaccount1/" />
<add key="AccountName" value="devstoreaccount1" />
<add key="AccountSharedKey" value="Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==" />
<add key="DefaultMembershipTableName" value="Membership" />
<add key="DefaultRoleTableName" value="Roles" />
<add key="DefaultSessionTableName" value="Sessions" />
<add key="DefaultProviderApplicationName" value="ProviderTest" />
<add key="DefaultProfileContainerName" />
<add key="DefaultSessionContainerName" />
</appSettings>
<system.web>
<sessionState mode="Custom" customProvider="TableStorageSessionStateProvider">
<providers>
<clear />
<add name="TableStorageSessionStateProvider" type="Microsoft.Samples.ServiceHosting.AspProviders.TableStorageSessionStateProvider" />
</providers>
</sessionState>
</system.web>
but now i an getting the following error
Configuration Error Description: An
error occurred during the processing
of a configuration file required to
service this request. Please review
the specific error details below and
modify your configuration file
appropriately.
Parser Error Message: Exception has
been thrown by the target of an
invocation.
Source Error:
Line 39: Line 40:
Line 41: Line 42: Line
43:
Source File:
C:\Users\GizaKarthik\Desktop\SessionDemo\SessionDemo\SessionDemo_WebRole\web.config
Line: 41
Assembly Load Trace: The following
information can be helpful to
determine why the assembly
'Microsoft.WindowsAzure.StorageClient,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' could
not be loaded.
WRN: Assembly binding logging is
turned OFF. To enable assembly bind
failure logging, set the registry
value
[HKLM\Software\Microsoft\Fusion!EnableLog]
(DWORD) to 1. Note: There is some
performance penalty associated with
assembly bind failure logging. To turn
this feature off, remove the registry
value
[HKLM\Software\Microsoft\Fusion!EnableLog].
The reason for the exeption is that i used a corrupted dll. Download the additional c# examples from here . Find asp provides project edit the code in TableStorageSessionstateProvider
find this code
else
{
byte[] items = Convert.FromBase64String(reader.ReadLine());
byte[] statics = Convert.FromBase64String(reader.ReadLine());
int timeout = session.Timeout;
// Deserialize the session
result = DeserializeSession(items, statics, timeout);
}
replace the above code with this
else
{
try // Added try statement
{
// Read Items, StaticObjects, and Timeout from the file
byte[] items = Convert.FromBase64String(reader.ReadLine());
byte[] statics = Convert.FromBase64String(reader.ReadLine());
int timeout = session.Timeout;
// Deserialize the session
result = DeserializeSession(items, statics, timeout);
}
catch (Exception e) // Added catch statement
{
// Return an empty SessionStateStoreData
result = new SessionStateStoreData(new SessionStateItemCollection(),
SessionStateUtility.GetSessionStaticObjects(context),
session.Timeout);
}
}
Then compile and use the dll. It should work like a champ. happy coding!!

Resources