Why a MiddleWare and not a Controller?
I am currently integrating your token provider into my own SPA application. I really like it because it is small enough for me to understand and integrate, unlike all those humongous packages like IdentityServer4 ;-) But I am wondering why you chose to implement the TokenProviderMiddleware class as a middleware and not as a controller? After all, all it does is wait for a POST on e.g. /api/token. That task could easily be accomplished with a controller, and the ASPNetCore pipeline would save one Invoke with each request. I'm still new to ASPNetCore so there might be an obvious reason but I didn't see that. Thanks!
Thanks for checking out the code! The reasons I implemented this sample as a middleware are
- It's a common pattern in other auth libraries (like IdentityServer, OpenIddict, etc) to have the token endpoint hosted by middleware that lives up in the Startup.cs file (app pipeline) rather than in at the MVC layer (a controller)
- This is mainly because it's easy to reuse a piece of middleware by plugging it into your Startup file, compared to writing or copy/pasting a controller into your project
- At the time, there weren't a lot of examples of how to write ASP.NET Core middleware, so I wanted to show how it was done 😄
In your own project, you definitely could implement this endpoint as a controller if you want.
The problem I am getting using the MiddleWare component is related to CORs. In my controllers I can simply add an [EnableCors("MyPolicy")] attribute. I cannot work out how to do the same when it is a MiddleWare component.
Thoughts?
ps - to provide more background, the call works fine when executed from Postman, however I get the CORs error when trying to make the authentication call from within my Angular application.
Ok never mind, simply had to enable CORs globally instead of at the Controller level... 👍