I have a project in MVC using .NET Framework v4.7 with some WebApi on it. What I need to know is how to use a middleware between then to authorize a JWT for HTTP requests and MVC Action requests.
I've searched everywhere looking for a solution sample, but I couldn't find anything.
If anyone could help, I would be grateful.
Sorry for the English.
See what I understand from your question You want to use JWT Token for your WebApi and normal process for your MVC, as for later View generated from server and its not dependent on JWT Token.
I have seen this problem. In one of my application I am hosting both MVC views and webapi, whereas MVC view rely on cookie based authentication and authorization. and WebApi call depend upon JWT token for authorization and authentication.
Sorry this solution is from .net core. you need to configure both Cookie and JWT authentication like this
Here default would be your cookie authentication. Now to enable jwt token for your webapi you need to decorate webapi with following attribute
Hope that's answer your question.
If I grasped your problem statement, I think OWIN might be an option: you decouple your application from underlying hosting and get an extensible pipeline that you can inject middleware into (pretty much like .net core works out of the box).
Even better - it comes with JWT support out of the box (well, you need to install a few nuget packages - see below). Then you simply enable it on your
IAppBuilder
and roll with standard[Authorize]
attributes.To demo this setup, I've put together a working GitHub repo here to illustrate WebApi middleware.
Apart from
Microsoft.AspNet.WebApi.Owin
,Microsoft.Owin.Host.SystemWeb
andMicrosoft.Owin.Security.Jwt
nuget packages, it's pretty much a stock standard asp.net WebApi project with the following files changed:/Startup.cs
/Controllers/ProtectedValuesController.cs
/Controllers/ObtainJwtController.cs
This appears to work for MVC too
I have added a few extra nuget packages to do with ASP.NET Identity, which seems to have enabled me to successfully protect the following controller:
/Controllers/Home.cs
Hopefully that gives you some options to explore