Slim yaw
Slim yaw

Reputation: 79

Asp.net core 3.1 securing API and web app

I have an ASP.net core solution that contains 2 projects and I want to add authentication for both of them:

enter image description here

WebAuth project contains the basic authentication (login, register...) but I can call ApiAuth project Apis without being authenticated. how can protect the ApiAuth project APIs? I tried adding [Authorize] decorator but I am getting this error:

enter image description here

So I am thinking about adding a JWT authentication but I don't know if it's the correct thing to do or not? Any suggestions, please?

Upvotes: 0

Views: 126

Answers (1)

Noah Stahl
Noah Stahl

Reputation: 7553

If the API requests will come from the web app which was served with a cookie, and if the web and API share the same domain, you can use the same cookie for both. This is preferable to JWTs given that it also has the advantage of using secure, HTTP-only cookies which aren't susceptible to malicious JavaScript.

On the API, you'll add cookie authentication:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

Requests from the web app should carry the cookie as long as both use the same domain, like myapp.com/app and myapp.com/api.

This also requires both apps have the same Data Protection configuration, so they are both able to read the encrypted cookie with shared keys.

Upvotes: 1

Related Questions