Home > OS >  Angular jwt authentication with HttpOnly cookie
Angular jwt authentication with HttpOnly cookie

Time:10-05

We have .Net Core 5.0 backend API which is returning a jwt token wrapped in a HttpOnly cookie when I call the login API endpoint & in the response body, it is sending me user's name & userId. My question is, as it's an HttpOnly cookie, so javascript code will not be able to handle it. Then how can Angular application understand that the login is successful ?? In the subscribe method, how to get that jwt token? And in the logout method, what should I do?

CodePudding user response:

This situation is a common one, like wrapping jwt into a http only cookie. On angular side you can really on response status code to know if login was successfully or not. In you case you are receiving even user information's back, you can use also those ones.

In another scenarios, after a successful login , front end will make a new call like "user-profile" to get extra user information's.

In this case you will not need that wrapped JWT, on every subsequent request on the same domain cookie will be sent by browser by default, so no need for http interceptor which append authorization headers to requests.

hope this help you, getting a better view.

CodePudding user response:

Although I do not know Angular, I will respond with what you should be doing.

JWT is used by passing it through the Authorization header. This usually means that the token should be provided in a way JavaScript can access it, so you can add it using this Authorization header every time you fetch().

Having said that, your login API's response code will tell the caller if the login was successful or not.

As per the HTTP standard (see this reference), an authentication method should respond with 200 OK if the authentication (log in) is successful, or 401 Unauthorized if the log in fails.

As a backend developer, I highly recommend that you adhere to the set standards. I would ditch the cookie option and simply return a response to the user that includes the user's information as well as the JWT.

  • Related