0

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

  • I want the web app to use cookies-based authentication because it's easy to add.
  • But when I call an API from the ApiAuth project I want to be authenticated to use it.

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?

1
  • We can’t guess what your code has written in it. Have you added authentication in the way the error describes? Commented Apr 1, 2021 at 15:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.