JWT Authentication Concept

I am currently working on the interaction between an Angular JS application and Node.js Server (as an API) with JSON web token authentication.

But I have a question that I cannot answer myself: when you encode the server side of the JWT, putting the user as a payload, how do you continue to extract user information on the client side? Here is a small example to understand my question:

I am a regular user, I send my credentials to the API for authentication. In return, I get a JWT token, but I have no information about the user, since only the server has a secret key that can decode the JWT token. So should the server send me, for example, a user ID so that I can call my user / API ID to get authenticated user information?

+7
source share
3 answers

. , , , , , , . GET . cookie. , :

  • json-, ( user_id) , secret_key. .

payload = {user_id: 35} user_token = JWT.encode( , "your_secret_key" );

  • user_token html localStorage. Angular, localStorage.

  • , signed_in , GET, user_token . , user_token user_id.

  • user_token, user_id .

  • user_id ( ) json, NOT ENCODED.

, , , (user_id). , .

+6

, , JWT. - JSON.

A JWT 3 . , header payload, base64 . . , ( , , , ), - .

JWT - signature. hash header, payload , . .

, , .

+3

. , Base64 Decode , !

, :

  1. : , : .
  2. , .

  3. . JWT . token . : Header.PayLoad.Signature. , .

- Header. - :

{"typ":"JWT","alg":"HS256"}

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 Base64 Decode. , , , ! , https://www.base64decode.org/ .

header . json ( , , , , , , , admin:true, user first , , JWT , )

{"username":"user","id":3,"iat":1465032622,"exp":1465050622}

, JWT, Base64 Decode ( - ). json eyJ1c2VybmFtZSI6IjEiLCJpZCI6MywiaWF0IjoxNDY1MDMyNjIyLCJleHAiOjE0NjUwNTA2MjJ9.

Header Payload. ! :

var encodedString=base64UrlEncode(header) + "." + base64UrlEncode(payload);
//As our example base64UrlEncode(header) is eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
//and the base64UrlEncode(payload) is eyJ1c2VybmFtZSI6IjEiLCJpZCI6MywiaWF0IjoxNDY1MDMyNjIyLCJleHAiOjE0NjUwNTA2MjJ9

 var signature=HMACSHA256(encodedString, 'a secret string which is kept at server');

!! ( ). . ( , !).

,

//Header
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.
//PayLoad
eyJ1c2VybmFtZSI6IjEiLCJpZCI6MywiaWF0IjoxNDY1MDMyNjIyLCJleHAiOjE0NjUwNTA2MjJ9.
//Signature
0K8TL1YS0XKnEIfI3lYs-bu2vbWHSNZsVJkN1mXtgWg

Base64 Decoded . .

The signature is used only by the server. The client sends each request with its token, the server must be sure that the client has not changed any part of the token payload (for example, change the user ID). This is where the importance of the signature line is found out, the server double-checks the signature with its secret key for each request !

+1
source

All Articles