简体   繁体   中英

Authorization of .NET 5 Core MVC web application using .NET Web Api

I have two main projects in my solution, one is a .NET 5 Core MVC web application that is used as our front-end application with Identity for authentication and authorization, and it is currently directly connected to a Database layer(different project) that is responsible for CRUD operations using Entity Framework.

The other project is a .NET 5 Web API application. And we would like to move our controllers' logic from the MVC app to the Web API app, so that only the API project will have access to the database layer.

I'm not really experienced with authorization techniques apart from some basic stuff, so I'm stuck with an issue right now. How can I move the Identity authorization to the Web API project? I understand that on the MVC app, a Cookie is used to handle the authorizations but as I've seen the recommended approach for most Web API apps, is to use a JWT to authorize requests. However, in my scenario, since I would like to authorize the user(from the browser) on each request, would a Cookie authorization be possible ? Or should I store a JWT token on the browser and pass it along on each request?

Thank you

Why do you need to move the MVC controller to the Web API Project? If the controllers are separate than that is even better!

Here in short how JWT based authentication works:

  • The JWT token has tow components - an Auth token and a Refresh token.
  • The Auth token is used to authorize the requests and the Refresh token is used to renew the Auth token when it expires.
  • The Auth token also contains some user claims like Name, Id, Email etc.
  • You make the user re-login when both the Auth and Refresh token expires.

For Web API JWT authentication is best. Use your MVC controllers to render and handle the page flows and the Web API controllers to return data from the Database. For your current structure you can do the followings:

  • Have the MVC Auth controller consume an API from the Web API project and then maintain the Identity cookie as is now. The API will return a token if username and password works.
  • The Web API project will parse and validate the token. All you have to do is to check if Web API is returning a 401 or not. 401 would be when the token is invalid or expired
  • In your MVC project, switch from Asp.net Identity cookie to store the JWT token on the client side (From MVC project). And pass it along all requests to the Web API controllers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM