I want to host, mutiple self-hosted webapi's along with the web-site on the same machine / windows 2k8 server. For hosting the website I am using IIS. and for webapi's I would be using self-hosted webapi 2. How do I configure using self-hosted webapi, so that everything can work in sync on same server.
So lets say I will host the website at http://example.com/mysite and I will be hosting the webapi at http://example.com/apiws and http://example.com/apiui
I am using windows service for the configuration. This is how the web-api self hosting looks like as of now - for first webapi.
protected override void OnStart(string[] args)
{
_config = new HttpSelfHostConfiguration(ServiceAddress);
_config.MapHttpAttributeRoutes();
_config.Routes.MapHttpRoute("DefaultApi",
"apiws/{controller}/{id}",
new { id = RouteParameter.Optional });
_server = new HttpSelfHostServer(_config);
_server.OpenAsync().Wait();
}
the configuration is almost same for the second server as well.
My question is having all of them working on the same port, is it possible? are there any issues which might arise? etc?
you are confusing web-api with mvc.
MVC/IIS/websites needs hosting on domain on sub-domain.
webapi are just for listening to the request and providing the data response.
Related
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I consider my self a rank beginner to OWIN and after reading a lot of documentation I have only gotten more confused with conflicting notions than before I began. I know these are multiple questions, but I feel answering these will clear most fundamental doubts regarding OWIN and how to best use it. Here are my questions:
What can I use OWIN middleware for that I couldn't already do using
message handlers or HTTP modules? Or are they both the same thing
except that the latter two are tightly coupled with IIS?
A lot of the documentation says OWIN allows for decoupling between
the web server and web application ie. removing dependency on IIS
for hosting say Web API applications. But I have yet to see an
example of some web application or web api that used OWIN and was
successfully ported from being hosted on IIS and then some other web
server. So is IIS and self hosting the only way to go for this
decoupling between web server and web app?
When I searched for OWIN middleware examples, I only got Katana and
Helios which are the only two implementations of the OWIN spec.
Katana is almost done with and wont go beyond revision3 and Helios is not yet supported by
Microsoft as per some articles. So what is the future of OWIN in
that case?
The only detailed practical usage I have seen so far is that of
using OWIN for authentication using OAuth 2. Any other such usages
of keeping an OWIN implementation in the middle?
In my startup class's Configuration method I tried to chain simple
middleware code snippets as below and to be able to see the request
being sent in :-
but got errors:
How do I see the request coming in and modify it for the next component in the middleware?
What are the various kinds of middle ware that you have plugged-in
in your projects between the web server and application?
Thanks for answering any or all of these above.
What can I use OWIN middleware for that I couldn't already do using message handlers or HTTP modules? Or are they both the same thing except that the latter two are tightly coupled with IIS?
Decoupling with IIS is part of it. OWIN middleware is a pipeline that allows certain things that are "OWIN aware" to be involved in the request, if they choose. IHttpHandler's handle a single thing - they were not chain-able. I like to compare the pipeline more to Global.asax. I've seen a lot of stuffed Global.asax handlers doing all sorts of things like authentication, authorization, spitting out HTTP headers like P3P policies, X-Frame-Options, etc. Part of the problem with this is developing reusable components from that was difficult and depended on IIS. OWIN attempts to remove those issues.
A lot of the documentation says OWIN allows for decoupling between the web server and web application ie. removing dependency on IIS for hosting say Web API applications. But I have yet to see an example of some web application or web api that used OWIN and was successfully ported from being hosted on IIS and then some other web server. So is IIS and self hosting the only way to go for this decoupling between web server and web app?
That's true for WebAPI 2 and SignalR 2. MVC 5 and older can't really be decoupled from IIS at the moment. MVC 6 will resolve this issue and is a pretty big overhaul. The ASP.NET Website has a tutorial or two on SignalR self hosting on a Console app. You'll see in the tutorial a Startup class, just as if it were running on IIS or IIS Express. The only thing the Console App does differently is it is bootstrapping a server with HttpListener in the Main method.
[comment] With respect to point #2 above, what are the owin components here? Is Katana an owin component or is it the code we write using Katana or both put together?
OWIN is really not much more an an abstraction layer, really a specification, between the web application and the web server. There are different "implementations" of OWIN depending on the server you want to run on - Katana is an OWIN implementation that runs WebAPI 2 and SignalR 2. Kestrel is another example of an OWIN implementation.
When I searched for OWIN middleware examples, I only got Katana and Helios which are the only two implementations of the OWIN spec. Katana is almost done with and wont go beyond revision3 and Helios is not yet supported by Microsoft as per some articles. So what is the future of OWIN in that case?
That's still a bit up-in-the-air, but OWIN is being used to develop the Kestrel web server that allows ASP.NET 5 Core to run on Linux / OS X.
The only detailed practical usage I have seen so far is that of using OWIN for authentication using OAuth 2. Any other such usages of keeping an OWIN implementation in the middle?
SignalR and WebAPI also use OWIN. This is useful so that you can run a SignalR Hub as a Windows Service, same goes for Web API.
Any other such usages of keeping an OWIN implementation in the middle?
Platform Independence. Having OWIN in the middle means I can literally xcopy my MVC 6 Core web application from running on IIS to Kestrel on my Mac, and the OWIN implementation takes care of the rest.
In my startup class's Configuration method I tried to chain simple middleware code snippets as below and to be able to see the request being sent in.
context.Request does not have an indexer in OWIN. Use Get<> instead:
app.Use(async (context, next) =>
{
context.Response.Write("hello world 2: " + context.Request.Get<object>("owin.RequestBody"));
await next();
});
Note that owin.RequestBody is a bit of an implementation detail, the actual return type is internal. I'm not sure what you are attempting to get, if you want a query string, use Query from the request, or Headers if you want an HTTP header.
What are the various kinds of middle ware that you have plugged-in in your projects between the web server and application?
Things for handling security, like a middleware component that handled nonces in Content Security Policy, which I wrote about on my personal blog here. The gist of it was it allows me to add an HTTP header with a nonce:
public void Configuration(IAppBuilder app)
{
app.Use((context, next) =>
{
var rng = new RNGCryptoServiceProvider();
var nonceBytes = new byte[16];
rng.GetBytes(nonceBytes);
var nonce = Convert.ToBase64String(nonceBytes);
context.Set("ScriptNonce", nonce);
context.Response.Headers.Add("Content-Security-Policy",
new[] {string.Format("script-src 'self' 'nonce-{0}'", nonce)});
return next();
});
//Other configuration...
}
From there, in my Razor views I could add the nonce to <script> elements get getting the token from the owin context.
There are lots of other things it can be used for. Other frameworks can easily inject themselves into the request / response process now. The NancyFx framework can use OWIN now.
I would like to build some kind of JSON.API scheduler service to play web request later on my production server.
It should be possible to POST this to localhost/app/events on my development machine:
{
“schedule”: {
“start”:”2014-12-31”,
“repeat”:”annualy”
},
“requst”: {
“verb”:”POST” ,
“href”:“http://localhost/app/emails”,
“body”:{
“type”:”HappyNewYearWishes”
}
}
}
Given ASP.NET API as an implementation mechanism, how to parse and persist “request” part to database, so Production Server will be able to
POST /emails
{
“type”:”HappyNewYearWishes”
}
according to the schedule? The problem is that the deployment root is different for development machine and production server, so I cannot persist “href” as it is. What kind of mechanisms of ASP.NET Web API for route parsing, transformation, and persistence are useful here?
You can get the Route parameters using
RouteData.Values
Also you can get the eventual querystring parameters using
Request.Url.Query
With the results of these two objects stored, you can easily rebuild the URL.
I've got a WebAPI 2 app built on top of the OWIN/Katana stack, hosted in IIS 7.5, and I can't seem to get the WebAPI routing to work when SiteMinder tries to redirect to my API route (it returns a 404).
Siteminder is correctly installed on this web server (works fine with my MVC 5 app, which is in a sibling IIS application to my OWIN WebAPI app).
When the SiteMinder IIS7WebAgent module is removed from my WebAPI app, all is fine, and my routes are properly recognized.
However, when I add the web agent module (with runAllManagedModulesForAllRequests="true"), only requests to the WebAPI's default route work (i.e., "/myapp/" routes to my default "home" controller, but requests to "/myapp/home" all return 404).
Does anyone have any idea of how this needs to be configured?
It looks like this was caused by a bug in SiteMinder's integration with the IIS integrated pipeline.
Our issue went away after updating CA SiteMinder to r12.51.
I am working on ASP.NET 4.0 MVC3 web application that works in intranet environment. The application makes use of Windows authentication. Its application pool is run by domain user that has spn set on a domain controller. Authentication works using Kerberos (on IE and Firefox after some additional configuration).
Now I want to upload files to sharepoint, but it's important for me to upload the file as the user currently logged in into the application (so the file is created on Sharepoint with his/her credentials).
I have the following code in ResourceExists(Uri uri) function:
'...
Dim identity As System.Security.Principal.WindowsIdentity = HttpContext.User.Identity
Dim impersonationContext = identity.Impersonate()
response = request.GetResponse()
impersonationContext.Undo()
'...
This works when running locally, but when I deploy to the server I get the exception:
System.Net.WebException: The remote server returned an error: (401) Unauthorized.\r\n at WebDav.WebDavClient.ResourceExists(Uri uri)\r\n at Website.Website.WebdavController.Upload(HttpPostedFileBase file, UploadViewModel vm)
I read something about passing on the credentials, that is not possible with NTLM, but I am sure I am using Kerberos (I checked the headers with wireshark and fiddler) and I see the following:
Authorization: Negotiate YIIFpQYGKwYBBQUCoIIFmTCCBZWgJDAiBgkqhkiC9x...
Any ideas why the impersonation does not work when running on the IIS server?
I found the answer here:
http://support.microsoft.com/kb/810572
"Kerberos does not work in a load-balanced architecture and IIS drops back to NTLM authentication. Because you cannot use NTLM for delegation, any applications or services that require delegation do not work. For more information, click the following article number to view the article in the Microsoft"
And that was exactly the case. I tried now with another machine that is not load-balanced and it works.
The only thing that still surprises me is that ImpersonationLevel of the identity is still Impersonate not Delegate...
After setting <identity impersonate="true"/> in your web.config try the following:
using (((WindowsIdentity)User.Identity).Impersonate())
using (var client = new WebClient { Credentials = CredentialCache.DefaultNetworkCredentials })
{
string result = client.DownloadString("http://sharepoint");
}
you need to configure your site correctly in IIS for impersonation to work.
see Configure ASP.NET Impersonation Authentication (IIS 7)