26

JWT terminology has been bothering me for a few reasons. Is JWT suitable for Authorization or is it only for Authentication?

Correct me if I'm wrong but I have always read Authorization as being the act of allowing someone access to a resource yet JWT doesn't seem to have any implementation that actually allows access to users to a given resource. All JWT implementations talk about is providing a user a token. This token is then passed with every call to a back-end service endpoint where it is checked for validity and if valid access is granted. So we can use JWT for Authentication of any user but how can we restrict the access to particular valid users ?

How can we use JWT for restricting a few users depending on roles they have? Do JWT provide any type of Authorization details as well or does it just provide us Authentication ?

Thanks in advance for your help and reading my doubt patiently.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Rohan Kadu
  • 1,311
  • 2
  • 12
  • 22
  • read this too: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html – Ayush Gupta Jan 22 '18 at 17:12

4 Answers4

20

Authorization with JWT can be achieved using the token specific claims.

As many other user information packaged as claims in the Json Web Token the specific permissions can be pre-filled in the token and can be intercepted later on by an authorization service.

Typically the authorization would be permission based where permissions are used to restrict access to an api endpoint (may also be used to grant users access to views on the frontend apps).

Here down a sample JWT token having a permission element:

{
  "UserInfo": {
    "id": "#{USER_ID}",
    "roles": {
      "#{ROLE_NAME}": "#{ROLE_ID}"
    },
    "permissions": {
      "#{PERMISSION_NAME}": "#{PERMISSION_ID}",
    }
  },
  "exp": 1488888888
}
Community
  • 1
  • 1
tmarwen
  • 15,750
  • 5
  • 43
  • 62
13

JWT can be used for two purpose:

  1. Authentication (as you said)
  2. Information Exchange.

The second part is the interesting one. A JWT contains:

  • a header: contains algorithm and token type
  • a payload: Which are statements about an entity (typically, the user) and additional metadata. There are three types of claims: registered, public, and private claims.
  • a signature: The signature is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn't changed along the way.

The payload can contains information about a user such as a list of rights. This way you can use it for Authorization.

Example from jwt.io:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

which contains:

{
  "alg": "HS256",
  "typ": "JWT"
}
{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

you can see that the payload contains the identity and information about the administration right. You can trust theses data because of the payload signature.

JEY
  • 6,973
  • 1
  • 36
  • 51
  • So is there any standards for this payload or it can be any custom json ? – Rohan Kadu Jan 22 '18 at 16:57
  • 2
    you can do whatever you want but https://www.iana.org/assignments/jwt/jwt.xhtml defined standard public clain and https://tools.ietf.org/html/rfc7519 define registered claim – JEY Jan 22 '18 at 16:58
  • This headers can't be modified in between as they are encoded and signed . Do I got it correctly ? So it will be safe to transfer role specific information in headers . Ryt ?? – Rohan Kadu Jan 22 '18 at 17:04
  • Yes in order to modify the content you need to know the private key or the secret (depending on the algorithm used). – JEY Jan 22 '18 at 17:05
  • Does it mean, I have to generate different web tokens for different roles or privileges ? – Olasunkanmi Apr 10 '19 at 23:34
  • What do you mean. A token can have multiple roles or privilege in it. But each user should have its own. – JEY Apr 11 '19 at 07:30
2

User logins first. Once user pass the login process, or we say once user is authenticated, you sign a jwt token and send it to the user. this is node.js snippet

async postLogin(req, res, next) {
    // parse the req.body, get the email,password
    // check if the email exist, if exists check the passord
    // now you are sure credentials are true, create the jwt.
    const token = jwt.sign({ _id: this._id, email: this.email }, "this-is-secret", {
  expiresIn: "1h",
  res
    .status(200)
    .header("x-auth-token", token)
    .json({ token, userId: existingUser._id.toString() });
   });
  }

now client will takes it save it to localStorage. (for simplicity i m using localStorage). IN the client side, user sends post request to login and gets what I sent above. It will take the token, and save it. since it is async request, it will be like this. this is a little react code to demonstrate:

  .then(resData => {
    localStorage.setItem('token', resData.token);
    localStorage.setItem('userId', resData.userId);

One thing about tokens, browser does not send it automatically, so client will manually attach it to the request.

fetch(url, {
      method: "post",
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      }
    })

Once your server gets the request, you check the incoming token, if it is a valid token you will authorize the user to access certain routes or services. So user will be Authorized.

Authentication is the process of identifying users and validating who they claim to be. One of the most common and obvious factors to authenticate identity is a password. If the user name matches the password credential, it means the identity is valid, and the system grants access to the user, so we say user is authenticated

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
0

Is JWT suitable for Authorization or is it only for Authentication?

The answer to this question is lying in the following lines of RFC7519 Standard:

JSON Web Token (JWT) is a compact claims representation format intended for space constrained environments such as HTTP Authorization headers and URI query parameters.

JWT doesn't seem to have any implementation that actually allows access to users to a given resource.

I would say this part of your understanding needs a bit of polishing ;-) Indeed JWT has a structure called Claims and there you can find topics related to authorization.

The remaining part of your understanding is not following a correct sequence. In fact, there is a missing piece called Token Issuer. This guy is responsible to Authenticate JWT token requester and issue a JWT token if and only if the authentication process was successful and the requester was authorized. Then the issued JWT token could be verified by checking the signature, meaning that, the token that has been issued via a token issuer like an Identity Server will contain a hash code of message which will allow the consumer of the token to double-check the signature (hash code) to make sure the token has not been modified via unauthorized access during the transitions between client-server. Then if the token was a valid token the consumer at the next step can extract token (JWT) claims to process the authorization part.

Community
  • 1
  • 1
Aydin Homay
  • 315
  • 3
  • 14