JWT authentication concept

前端 未结 3 1629
野趣味
野趣味 2021-02-04 11:08

I am currently working on an interaction between Angular JS app and Node.js Server (as API) with an authentication based on JSON Web Token.

But I have a question I can\'

3条回答
  •  暖寄归人
    2021-02-04 11:39

    You retrieve the user's info by decoding the token on each request. So in your example after the token is returned to the client, the client makes a request to the server to grab the user's first and last name using the data stored in the encoded token which is sent along with the request back to the server. When making this GET request, you can send the token as a parameter. I'll use a non-cookie stored example. Here's how it goes down:

    1. The user signs in with their password and username
    2. The server encodes a json web token payload that contains the unique identifier (i.e. user_id) of the user that signed in using the secret_key. An example function call may look something like this.

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

    1. Return the user_token to the client and store said token in a hidden html tag or in a localStorage variable. Using Angular, I'd store it in localStorage.

    2. Now that the user is signed_in and the token is client-side, you can submit a GET request that contains the user_token as a parameter. Remember, this user_token payload contains the user_id.

    3. The server gets the parameter and decodes the user_token to get the user_id from the payload.

    4. You query the database with the user_id and return the data (first and last name) as plain json, NOT ENCODED.

    It's important to remember the only thing to encode in your example is the unique identifier (user_id). On each request you decode the token which itself is the authentication mechanism.

提交回复
热议问题