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.
Related
There is a several options on how to secure access to resource APIs from clients(web/mobile...), And in recent years, it was common to implement OIDC for SPAs in JS / TS, and this is no longer recommended.
The recommendation for SPA is to avoid storing tokens in the browser Or using service worker, And use a BFF insted of direct connect to Identity Server.
In this approach the BFF works as proxy of Identity Server and handle all oauth requests.
What is the best practice to implement this pattern with spring BFF, Or if there is another better approach.
Perhaps you're aware of this doc which explains the options. Assuming you are using an SPA and don't want the website option, there are 2 options, identical from a security viewpoint, and which you use is a matter of preference.
WEB BACKEND
The SPA sends OAuth and API requests to a web backend first, which forwards them and implements the OAuth client. The web backend uses a runtime that issues cookies.
Pros are an easier initial developer setup and fewer components to deploy. Cons are that all developers have to run the backend, and web deployment options are limited to those that can host the runtime.
REVERSE PROXY BACKEND
The SPA sends OAuth and API requests via a reverse proxy such as NGINX. OAuth requests are forwarded to a utility API. The web backend remains static content only.
Pros are that you can get rid of the cookie issuing runtime from a developer PC, and it is easier to do things like deploy web resources to a content delivery network. Cons are that the initial developer setup is harder and that there are more moving parts.
BEHAVIOR
In both cases the SPA uses URLs like this, for static content, oauth client and API routing responsibilities.
https://www.example.com
https://www.example.com/oauth-client
https://www.example.com/api
Within the oauth-client path, the SPA calls endpoints like this. The SPA OAuth code is very light:
POST /login/start
POST /login/end
IMPLEMENTATIONS
There are quite a few out there, including components you can plug in. Search for a term like BFF OAuth and do some reading. It is a journey though - cookies are complicated little things.
I have just added a tutorial on one of my repos for configuring spring-cloud-gateway as BFF between a browser application secured with sessions (Secure HttpOnly cookie) and an OAuth2 resource-server.
This sample uses Angular as UI framework, a thin wrapper of mine around spring-boot-starter-oauth2-resource-server, and Keycloak as authorization-server, but this are implementations details are all the work is done by the BFF.
I am building an application/web API with ASP.NET Core and MediatR.
The authentication (Google account) is done in ASP.NET Core. The controllers make only thin layer that delegates all the work to MediatR and its request handlers.
Regarding authorization, currently, my approach is, I have most controllers decorated with [Authorize] attribute and also respective request handlers in MediatR's pipeline check (via a behavior) if the user was authenticated, so there is a duplicity.
My question is, would that be a bad practice to have all controllers allowing anonymous access and only check the authentication/authorization in the MediatR's pipeline?
I, for sure, need to keep it in the request handlers, since they are forming the actual application layer and I want it to be independent from the ASP.NET. Also only this layer is tested.
I would leave authorization up to the controller but that's just an opinion.
If you plan on using the handlers in other projects that don't have built in authorization capability, then leave them in the handlers.
This is an "it depends" question as it depends on your specific scenario.
I have already working ASP.net Web API (.Net Framework 4.6.1) Application, And already have some "DelegatingHandler"s and "ActionFilterAttribute"s working on it to handle Authentication, and Validation filters.
I need to change Some error Messages like 404 default message :
No HTTP resource was found that matches the request URI 'https://example.com/api/someWrongUrlAction'.
So, I read about OWIN middleware, but I'm afraid of using it, and need to know will it affect any other working functionality or hosting settings? will it affect the already exists "DelegatingHandler" MessageHandlers ? or "ActionFilterAttribute" Filters?
Note: I need to use the OWIN middleware only for that purpose, but
I'll keep hosting in IIS as it is.
To be fair I'm not really sure why do you need an owin here. You could use either IIS tools (it will manage such routes in a best way) or you could use some of fallback approaches provided by MVC framework:
MVC 6 Routing, SPA fallback + 404 Error Page
or
Fallback route for MVC Areas
or
google like 'mvc fallback route' ;-)
Regarding your question. You can host OWIN application in the IIS. You might need to switch your application to support owin pipeline. Do not think you will be able to merge both approaches inside the same application.
I currently have an asp.net web api 2 site hosted in IIS secured with windows authentication. A requirement has now come in for us to support client certificate authentication in addition to windows, and I'm struggling to find out:
- if this is possible at all
- if there are any working examples available
I thought might be able to add an additional owin middleware or messagehandler or filter, but can't see any existing ones that do this specifically for windows rather than just relying on IIS. I know thinktecture identitymodel can do client cert, but not sure if the two can be combined?
Example of forms +win that i thought might be similar is here https://techblog.dorogin.com/mixed-windows-forms-authentication-for-ajax-single-page-application-e4aaaac0424a
Right so I managed to figure it out. Thankfully, if a controller returns a 401, IIS automatically adds the negotiate/ntlm headers, so if a user is on a windows browser, it will then automatically authenticate as usual. So with that in mind, to keep windows auth working, I:
updated the site in both IIS and VS to allow anonymous AND windows auth
added the [AuthorizeAttribute] as a global action filter (which causes the 401 to be returned if the user is not authenticated by the time they hit the filter)
To get client certificate auth working, I used the magnificent Thinktecture.IdentityModel library, which allowed me to add only one line to my Startup.cs file (we're using OWIN so this was easy)
app.UseClientCertificateAuthentication();
See https://github.com/IdentityModel/Thinktecture.IdentityModel/blob/master/samples/OWIN/AuthenticationTansformation/KatanaAuthentication/Startup.cs for an example
I want to create a WebAPI service for use in my single page application but I also want it to be available for a mobile application too.
When users are using the SPA they are signed in using forms authentication and have a session cookie but if they're using the mobile application this wont be the case.
Is it possible to expose the same API controller as 2 different endpoints where one is authenticated using mutual SSL, a token or as a last resort basic auth and the other uses the session cookie?
For example take the following controller:
public class TodoController :
{
public IQueryable<TodoModel> GetTodos()
{
...
}
}
Can I add multiple routes that map to the same method?
https://myapp.example.org/api/todo
https://myapp.example.org/mutual-auth/api/todo
I want to configure IIS to use mutual SSL for the mutual auth endpoint and use forms authentication for the other endpoint.
Short answer: yes
This is a very broad question, so I won't go into excessive detail about every aspect. I think you should also take a look at BreezeJS because it makes things building these applications significantly easier.
DESIGN
Do you want to build in pure HTML and JavaScript or incorporate CSHTML? The decision is yours, but if you want to eventually create native-based applications using something such as PhoneGap Build, you'll want to stick to pure HTML and JavaScript so that you can compile the code later.
Do you want to use another JS library such as BreezeJS to make life a little easier when designing your controllers? Out of the box, your Web API controllers will be prefixed with api/{controller}/{id} in WebApiConfig. You may want to add {action} routing if you don't go with something like BreezeJS so that you can have more flexibility with your controllers.
Lastly, let's talk about the Repository Pattern and Unit of Work Pattern. This is a bit of hot-topic, but I find that usually creating a repository allows you a great deal of flexibility and it's great for dependency injection. Adding an additional repository layer to your controllers allows you to differentiate between different users or means of access such as a SPA or mobile application very easily. You can use the exact same controllers, but simply draw from different repositories.
SECURITY
You'll want to touch up a bit on [Authorize], [ValidateHttpAntiForgeryTokenAttribute], [Roles("")], and several other data annotations for starters. This is a huge topic which has a ton of reading material online -- invest in some research. Your controller can have multiple actions which have varying limitations on them, such as preventing CSRF on the SPA, but be less restricted on Mobile by either utilizing varying actions on the controller or drawing from separate repositories.
Can I add multiple routes that map to the same method?
https://myapp.example.org/api/todo
https://myapp.example.org/mutual-auth/api/todo
Yes, absolutely. You'll just have to do some extra work with your routing configuration files. With BreezeJS, you get access to not only /api/ but /~breeze/ which works very similarly.
You can secury your Web API using the way you want. For exemple, you can provide a custom Message Handler or a custom Authorization Filter to provide external authentication via token.
There's a full session from the ASP.NET Team that covers this, you just need to choose which one you will pick up:
Security issues for Web API.
Assuming you are hosting web API in IIS, if you enable the forms authentication, FormsAuthenticationModule establishes the identity. That is, if you look at HttpContext.Current.User or Thread.CurrentPrincipal after a successful authentication, the object of type IPrincipal will have the identity (which is FormsIdentity) and the IsAuthenticated property will be set to true. You can do the same thing for any other credential using a custom DelegatingHandler. All you need to do is to validate the credential (token, user id and password in basic scheme in HTTP authorization header or whatever) and set the HttpContext.Current.User and Thread.CurrentPrincipal to an object of type GenericPrincipal with GenericIdentity. After this, the same action method of a controller which is decorated with Authorize will work for both types of requests.