Asynchronous Post with HttpWebRequest in MVC3 - asp.net-mvc-3

I've run come across a behavior with HttpWebRequest that I believe is intended, but as I have not been able to find any source that definitively says this is correct, I thought I would post it as a question and see if anyone has encountered this and/or can verify this is correct.
For starters I have an MVC3 app running on IIS 7.5. It has 1 controller and supports 1 post method. I have Windows Auth and ASP.NET Impersonation enabled within IIS. The idea behind the MVC3 app is just to have a simple service that can be used for logging information from a variety of client applications(console apps, silverlight, asp.net, AJAX, etc). One of the things the service does is uses the User property from the controller to also log who the person who posted data to this service.
To simplify the processing for the consuming applications I created some client libraries, Silverlight, DotNet, and a js library.
This all worked out as expected except when using the DotNet library within another MVC3 application. For the DotNet library I'm using an HttpWebRequest and using the asynchronous methods (Begin/EndGetRequestStream)/(Begin/EndGetResponse) to post the request. I'm also setting the .Credentials on the request to CredentialCache.DefaultCredentials, but when the logging application starts the processing of the request from another MVC3 app it shows the User as the service account of the app pool from which the post was received.
When I found this I added a synchronous version of the post to the DotNet library and found that the logging service was using my personal credentials.
I assume that HttpWebRequest could be using different DefaultCredentials depending on the context in which it is used. Since this is asp.net and the async method of the request are being called, my library code may not have even finished before the client MVC3 app has returned a response.
What I haven't been able to find is if this is definitively the case or not. If anyone has and answer or or an article that could point me in the right direction I would greatly appreciate it.
Thanks in advance

What I was encountering was intended behavior. The root of the problem comes down to under which identity do threads from the .Net thread pool execute when servicing the asynchronous requests. In my case the threads were executing as the owner of the app domain that was created by the app pool. In my case it was a service account.
I was able to capture the identity of the impersonated user prior to the start of any asychronous processing and use the WindowsImpersonationContext to force my library code to run as the impersonated user. By doing this CredentialsCache.DefaultCredentials used my credentials(impersonated user) instead of the account running the app pool when setting it on the HttpWebRequest instance.

Related

OWIN Self-hosted Security Token Service (STS)

I'm looking for suggestions regarding methods of hosting a 'custom STS' within a self-hosted OWIN pipeline.
It seems that the current documentation on custom claims providers has changed very little in the few years since I created a custom-STS with WIF 3.5, and I'd like to bring the implementation up-to-date for use with ADFS 3.1 (Windows Server 2012 R2).
I'm aware that the SecurityTokenService has moved to the System.IdentityModel namespace in 4.5, and ideally I'd like to encapsulate an STS within an OWIN-self hosted WebAPI, but I would be happy to use something like Nancy instead if necessary (since MVC does not appear to run in OWIN owing to it's reliance on System.Web), but I am struggling to find a way to utilise my implementation of SecurityTokenService from my WebAPI's DelegatingHandler since the wrapper functions in System.IdentityModel.Service.FederatedPassiveSecurityTokenServiceOperations also appear to be reliant on System.web, and hence IIS.
I plan on presenting the required input form elements to the user by manually crafting the response stream and parsing the POST - I realise this is a terrible idea compared to using ASP.Net or MVC, but at this stage this is really just a proof of concept for me, I'll be letting ADFS handle the cookies, since this will just be registered as a custom claims provider.
Should I drop the SecurityTokenService class in favour of a better token-generation implementation, or should I drop the wrapper class and manage requests to the STS manually using the IOwinContext's Request and Response objects, but if so, how?
Many thanks

Api and consumer flow

I am developing an API for a social network website. This API will basically get all the requests from the users (get friend list, post a status update etc) and reply back if necessary.
We will implement OAuth 2.0 protocol for authentication. Consumer (our php project) has API id and secret.
Basic scenario:
Client wants to log in
API Consumer (php web project) takes this request, directs user to API
User send his/her user credentials to the api, gets the token.
User comes back to our website, pass token to the consumer.
Consumer goes to the api server, gets the access token.
Now consumer (php project) has access to user's private information.
Since this is a social network website, we want app developers to be able to use our API in the future.
I am not experienced in API-design. Does that flow make sense? I guess the simplest authentication would be accessing user information through php project. But we don't want to access database in php code. We will use ajax in client side and send a request to the API. And I believe there should be a better solution, what would you suggest?
Sure, API design is basically point where you need to choose technology.
Either it can be PHP or .net or Java.
I would prefer either PHP or .Net as we get lot of flexibility in it.
API will return XML or Json depending upon the request.
There are lot of CMS in php which can be helped.
.net we have Service Stack to help you.
API's had to be fully independent from other world as well as within API method as well.
If you are able to achieve this, then you will surely create a good architecture.

Using MvcMailer in non-MVC project

I have a windows service that is supposed to send e-mails periodically.
Next to the windows service project there is an MVC 3 project that is sending e-mails with MvcMailer (beautifully).
I want to use the same engine to send e-mails for the windows service.
How should I do it?
Import the MVC binaries and create one controller and new views for this purpose? Will it work?
Saving it in the database and requesting my web project to send the e-mail might not be the best solution because the information is the result of a query and is too big to be sent in the request.
The only other option I see is to simply request the web project to do all the work but this way it wouldn't be beneficial to place the windows service in another service to save the site application resources.
How would you do it?
As an alternative to MVC Mail, ActionMailer.NET can now be used stand-alone outside of MVC.
The details are covered here
http://geeksharp.com/2011/07/06/actionmailer-0-6-released/
I would argue that calling a mvc mailer from the service might be an overkill. If the mvc project is supposed to expose sending the email API for all of your other solutions, then building a REST api might make sense. However, if you just want to bring the functionality of the action method to the windows service, then i would choose an in-process functional component. If you can refactor the logic of the mvcmailer action method into another assembly why not just do that and then include that assemlby as a depedency in your windows service solution.
If you can provide the over all purpose of the mailer and how it's used in the web scenario, it may help us to provide a better architecture.
Why do you think the query to send to mvcmailer us too large? If you have the mailer MVC project already working and exposed via a restful URL, that becomes your email service and simply call it as a web request from your service.
You can get around size constraints in your request That shouldnt be an issue.

WF4 - How to consume external web service?

I'm having a really hard time trying to find a resource or online tutorial that explicitly walks you through setting up a WF4 workflow activity that can call out to an external web service. All the videos and online samples I've come across simply demonstrate how to consume a web service that's part of your Visual Studio solution, but my situation entails calling out to a web service on a non-Microsoft server.
I have a service reference added to my VS2010 workflow console project for the web service in question, and it's pointing to the WSDL of the external web service. So far, so good (I think). I have a very basic workflow sequence, using a SendAndReceiveReply workflow control to communicate with the external server, and I believe I have the Send piece configured correctly. The ReceiveReplyForSend is giving me trouble, however, and I'm not sure if I have its Content options set up the right way. I'm invoking an operation called FileCheck, which at the moment for testing purposes always returns a value of 1 like this:
<SOAP-ENV:Envelope>
<SOAP-ENV:Body>
<FileCheckResponse>
<FileCheckResult>1</FileCheckResult>
</FileCheckResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
If I try to run this, however, I get the error "Badly formed SOAP message." For what it's worth, my ReceiveReplyForSend has a single parameter set up called FileCheckResult, though I don't know if that's the correct way to get the above value.
I can put a breakpoint at either activity, but I have no idea how to see what the SOAP call looks like at that point. Can someone either give me some workflow Send/Reply debugging tips or point me in the direction of an excellent step-by-step tutorial of how to consume an external web service in WF4?
Update on Feb. 2, 2011: Thanks to Maurice's suggestion, I see exactly what is failing now. The web service call in my workflow is failing because Visual Studio is generating a reference to the wrong namespace in my workflow Send call. Here is the single bit of XML that is wrong in the SOAP message - I'll leave off the rest of the SOAP envelope for succinctness:
<FileCheck xmlns="http://tempuri.org/">
This is what the WCF Test Client generates, which gets a successful message in return:
<FileCheck xmlns="http://someserver.org/test/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
This is probably a really newbie question, but is there a setting somewhere that I'm overlooking that adjusts the xmlns value? I tried searching for "tempuri" in my project, but it's nowhere to be found, so I bet I'm overlooking a default setting somewhere.
Update on February 8, 2011: Maurice's latest tip did the trick! I needed to add the proper namespace to the ServiceContractName property for my Send workflow activity.
Adding a reference to an external web service is not much harder than one that is part of the same VS2010 solution. Only in this case you need to provide the URL where VS2010 can find the web service WSDL. As the communications mechanism is standard WSDL and SOAP there should not be a problem in calling the other service.
If you want to debug messages the best tool to use is Fiddler. It will let you see messages on the wire and even build request on the fly. If you have an existing client that can work with the service in question you can monitor its messages and compare them with the messages you are sending. Provided the service doesn't use complex and custom data types the WCF Test Client is a good way to check if the service responds with a standard .NET client app.
The SOAP namepsace is part of the ServiceContractName. Use the following syntax
{http://someserver.org/test/}FileService

Exception in brand new Silverlight project

I am getting the following exception message when I try to run my newly created Silverlight app:
An error occurred while trying to make a request to URI 'http://localhost:8732/Design_Time_Addresses/IsAProgrammer.Service/Service1/'. This could be due to attempting to access a service in a cross-domain way without a proper cross-domain policy in place, or a policy that is unsuitable for SOAP services. You may need to contact the owner of the service to publish a cross-domain policy file and to ensure it allows SOAP-related HTTP headers to be sent. This error may also be caused by using internal types in the web service proxy without using the InternalsVisibleToAttribute attribute. Please see the inner exception for more details.
This is what I have done. I started with a silverlight app. That created 2 projects. My actual silverlight app and one called MySolutionName.web (not sure what that does except host my silverlight page).
I then made a WCF project so I could have some services for my Silverlight app to consume. I made my services and then added a Service Reference to the silverlight project. I then changed the binding to be basicHttpBinding for my services. (I subsequently refreshed my Service Resource reference in the Silverlight app.)
I reading about this error, I have found that I need a clientaccesspolicy.xml and a CrossDomain.xml file to fix it. I found a generic copy of each of these and added them to both my MySolutionName.Web project and my WCF project.
Any other ideas would be great.
I don't do a lot of WCF myself but it sounds like you've created yourself 2 web applications, one where the Silveright app is host and one service the WCF. Was this intentional?
At a guess I think you should have just added a WCF Service item to the existing host web application.
When u r playing with wcf sevice for the first time with silverlight or wpf these errors are bound to come :). The below link will help you to put your crossdomain policy in right place.
Where to place ClientAccessPolicy.xml for Local WCF Service?

Resources