SignalR in OWIN hosted site? - visual-studio-2013

I get this error when trying to run my web site in UltiDev (version 2.0.20) or in a CassiniDev4 server.
This operation requires IIS integrated pipeline mode.
at System.Web.HttpResponse.get_Headers()
at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders..ctor(HttpResponseBase response)
at Microsoft.Owin.Host.SystemWeb.OwinCallContext.CreateEnvironment()
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.GetInitialEnvironment(HttpApplication application)
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.PrepareInitialContext(HttpApplication application)
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.BeginEvent(Object sender, EventArgs e, AsyncCallback cb, Object extradata)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Here is similar related (unsolved) question: Testing SignalR App in IIS Express.
Is there any way to determine which headers are involved in this problem?

With ASP.NET Core, this is no longer an issue as I don't need to use UltiDev or CassiniDev4.

Related

Web API Corruption in Service Fabric

I've encountered two oddities concerning a Web API stateless service in my service fabric cluster. The first regarding missing properties on the response to a call to a stateful service. The second being a critical error when a response to GET was changed from a class to a struct. Details below.
Issue #1 - Missing Properties
I have a three projects:
A class library with a class called Person. The two projects below utilize this library view a private nuget package.
A Stateless Web API, which has a GET to retrieve all Persons.
A Stateful Service, implementing a ReliableDictionary which holds all persons. The Stateless Web API calls a method which returns all person from this dictionary.
The issue is that I've recently updated my class library to give Person some new properties (say, CreatedOn). Both the Stateless Web API and Stateful Service have the latest version of this package and were deployed (overridding, not upgrading). The Stateful Service correctly recognizes and stores these new properties. However, the Web API is somehow not creating an object without those new properties. It's not like they are null, they just simply do not exist!
I've tried uninstalling/reinstalling nuget package, as well as, clearing out bin/obj folders. Neither works. However, creating a new Web API Service fabric project, does work.
Any ideas, or has my project somehow been corrupted?
Pictures of properties:
Issue #2 - Struct Crashing Web API
This may be related to the first issue, and uses the same libraries and services. I tried changing the Person object to a struct, but any call to the api then throws the following error:
{
"Message": "An error has occurred.",
"ExceptionMessage": "The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup code after all other initialization code.",
"ExceptionType": "System.InvalidOperationException",
"StackTrace": " at System.Web.Http.Routing.RouteCollectionRoute.get_SubRoutes()\r\n at System.Web.Http.Routing.RouteCollectionRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request)\r\n at System.Web.Http.HttpRouteCollection.GetRouteData(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Net.Http.DelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\r\n at System.Web.Http.HttpServer.d__0.MoveNext()"
}
Again, trying this in another, identical Web API project works just fine.
Thoughts?
I got same when I used badly formatted route
example
[Route("/api/info")]
correct is
[Route("api/info")]

OAUth2 ASP.NET invalid_grant

I am trying to implement OAUTH2 for my web application but even though signing in to the application works, refresh tokens result in an HTTP 400 "invalid_grant".
Specifically, the project is an ASP.NET WebAPI with OWIN OAuth provider. This has been killing me for days without luck so any help will be appreciated :)
Have you correctly set OAuthAuthorizationServerOptions.RefreshTokenProvider?
If you need a sample, Katana's sandbox project contains a minimal implementation showing how you can easily configure it to protect and serialize refresh tokens using the data protection block (machine keys on IIS): https://github.com/jchannon/katanaproject/blob/master/tests/Katana.Sandbox.WebServer/Startup.cs#L169-L173
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions {
RefreshTokenProvider = new AuthenticationTokenProvider {
OnCreate = CreateRefreshToken,
OnReceive = ReceiveRefreshToken,
}
});
private void CreateRefreshToken(AuthenticationTokenCreateContext context) {
context.SetToken(context.SerializeTicket());
}
private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context) {
context.DeserializeTicket(context.Token);
}
If it still doesn't work, try enabling tracing to determine the root cause of the invalid_grant error: http://katanaproject.codeplex.com/wikipage?title=Debugging&referringTitle=Documentation
We were getting the same issue when deploying the AuthorizationServer on Azure and trying to access it through localhost.
Later we deployed all 3:
AuthorizationServer
AuthrizationCodeGrant
Resource Server
Made required changes in the Constants\Paths.cs for the deployed URLs.
Even after this it did not work. But once we changed all the paths to HTTPS it all started working smoothly.
Please try that in case you are still stuck.

In ASP.NET is there an event fired on a Windows Authentication log in failure? (Logging the details of a Windows Authentication failure)

I am building a .NET 4.0, ASP.NET MVC 3 intranet application that runs on IIS 7.5 in integrated mode. Windows Authentication is used to govern access to the website. The Windows Authentication module is enabled and all other auth modules are disabled.
Currently when a user provides improper credentials, the Windows Authentication module correctly rejects the credentials and re-displays a login prompt. It does so 3 times, after which a standard .NET 401 Unauthorized Access page is shown. This is expected and desirable.
My goal: I would like to be able to log the details of the failed authentication attempt to my own custom event log. Particularly, to capture the user name that was used in the log in attempt. (I'll accept that capturing the password is not likely to be possible for security reasons.)
Is my goal possible?
I have already built a working an IHttpModule module and added it as an event handler to the WindowsAuthenticationModule, like this:
myWindowsAuthenticationModule.Authenticate += WindowsAuthentication_Authenticate;
But my code does not get called in the case of a failed log in attempt, presumably because WindowsAuthenticationModule has already decided that the log in is failed and so there is no point calling my module. My module does get called after a successful log in attempt, and so I am certain that my event handler is properly set up.
To the best of my knowledge, the WindowsAuthenticationModule does not expose an event that is fired when authentication fails, so that option is out.
Any ideas? Or am I barking up a tree that has no solution?
I was looking at the same issue, and looks like there is no events for windows authentication, even that Authenticate event is common for forms and windows.
But I found a solution to this!
http://www.codeproject.com/Articles/11202/Redirecting-to-custom-401-page-when-quot-Access-de
UPDATE
From original article
protected void Application_EndRequest(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context.Response.Status.Substring(0,3).Equals("401"))
{
if(User.Identity.IsAuthenticated)
{
// this means user is authenticated, but 401 still returned
// which means no access to page or whatever you are trying to access?
}
}
}
UPDATE2
I also found out that this solution doesn't work in all cases. I was testing in different environments, so was working for me, but not for others.
By default IIS will not even run this piece of code and just return it's own error page, what you want to do is tell IIS to let app handle errors.
<httpErrors existingResponse="PassThrough">
</httpErrors>
Now, with that said, IIS won't return any more of custom errors and you will need to handle them in application, ie. not only 401, but 403, 405, etc

Intermittent ProviderException from IIS or MVC: API failed due to error 'The data area passed to a system call is too small. '

Running IIS 7.5.7600.16385 on Windows Server 2008 R2 Enterprise (7601: SP1). One of our websites is set to globally log errors and we are seeing this every day or two. We're using an authorization attribute in our web.config that checks for user roles for access and whatever code IIS or MVC uses is generating this error. This is typically being triggered by a single partial view but we also see it triggered occasionally on fetching css or js resources.
System.Configuration.Provider.ProviderException: API failed due to error 'The data area passed to a system call is too small. '
at System.Web.Security.WindowsTokenRoleProvider.GetRolesForUser(String username)
at System.Web.Security.RolePrincipal.IsInRole(String role)
at System.Web.Configuration.AuthorizationRule.IsTheUserInAnyRole(StringCollection roles, IPrincipal principal)
at System.Web.Configuration.AuthorizationRule.IsUserAllowed(IPrincipal user, String verb)
at System.Web.Configuration.AuthorizationRuleCollection.IsUserAllowed(IPrincipal user, String verb)
at System.Web.Security.UrlAuthorizationModule.OnEnter(Object source, EventArgs eventArgs)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Do we maybe have some IIS setting for our website incorrect? Any idea what is going on? We can see by the username in our logs that the user is being correctly authenticated through IWA.

ASP Provider project failing in Azure environment

I'm recently getting a strange error while deploying my Azure application in a new Server. I'm using ASP Providers (supplied by microsoft with Azure SDK code samples). Regardless of several uploads i'm getting this big ugly message. Please help!
Error in '/' Application. --------------------------------------------------------------------------------
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace: [NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.Samples.ServiceHosting.AspProviders.<>c__DisplayClass5.<ResetItemTimeout>b__4() in C:\Users\upload.user\Desktop\Deployments\Deployment 2.20_A\AspProviders\TableStorageSessionStateProvider.cs:497
Microsoft.Samples.ServiceHosting.AspProviders.ProviderRetryPolicies.RetryNImpl(Action action, Int32 numberOfRetries, TimeSpan minBackoff, TimeSpan maxBackoff, TimeSpan deltaBackoff) in C:\Users\upload.user\Desktop\Deployments\Deployment 2.20_A\AspProviders\SecUtil.cs:439
Microsoft.Samples.ServiceHosting.AspProviders.<>c__DisplayClass1.<RetryN>b__0(Action action) in C:\Users\upload.user\Desktop\Deployments\Deployment 2.20_A\AspProviders\SecUtil.cs:395
System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +739 System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +114 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +370
-------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
Yes AppFabric Cache is officially released and supported by microsoft. THis link is of great help for tutorial: http://msdn.microsoft.com/en-us/gg457897
However, there's an additional billing aspect to using this approach whereas Tablestoragesessionprovider uses BlobStorage which is peanuts.
The advantage with these samples is that the code is provided so you can generally get a closer look at what's going wrong. I've taken a look and the most likely reason for you getting this error is that there is an error in the configuration of the session state provider (it might be pointing at the wrong account) or the table and container don't exist at that account.
There's a chance that there is just no session object available, but I find that unlikely.
Having said that, the Table Storage Session provider is not suitable for releasing in a production environment. You're much better off either using the SQL Server session provider or the App Fabric cache session provider.

Resources