User.Identity.Name is null after authenticate via WIF - asp.net-mvc-3

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()

Related

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>

MVC 3 FormsAuthentication Not working when deployed

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

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.

ASP.NET MVC 3 - DotNetOpenAuth - System.Security.SecurityException

I am trying to set up a simple website which uses DotNetOpenAuth as its membership provider. Everything was going great until I ran into the following exception.
[SecurityException: Request for the permission of type 'System.Net.WebPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark) +31
System.Security.CodeAccessPermission.Demand() +46
System.Net.Configuration.DefaultProxySection.PostDeserialize() +103
The code is below. Unfortunately I cannot reproduce the problem on my local machine. This is being hosted on GoDaddy shared hosting. The line which causes the exception is openid.CreateRequest(id):
public virtual ActionResult Authenticate(OpenIdAuthenticationViewModel model, string returnUrl)
{
OpenIdRelyingParty openid = new OpenIdRelyingParty();
var response = openid.GetResponse();
if (response == null)
{
Identifier id;
if (Identifier.TryParse(model.OpenIdUrl, out id))
{
try
{
var openIdRequest = openid.CreateRequest(id);
var result = openIdRequest.RedirectingResponse.AsActionResult();
return result;
}
catch (ProtocolException pe)
{
ViewData["OpenIdMessage"] = pe.Message;
return View(model);
}
}
else
{
ViewData["OpenIdMessage"] = "Invalid Identifier";
return View(model);
}
}
// code that handles response
}
I've tried changing the requirePermission attribute of
<section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true" />
but that only caused a different root for the exception stack trace. There is very little information to be found on this exact exception on the web.
This looks like it's because you've got a web.config with the following snippet:
<system.net>
<defaultProxy enabled="true" />
</system.net>
Try removing the <defaultProxy> tag, which shouldn't be necessary on GoDaddy anyway.

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