JSON Web Token (JWT) : Authorization vs Authentication
Solution 1
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
}
Solution 2
JWT can be used for two purpose:
- Authentication (as you said)
- 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.
Solution 3
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
Rohan Kadu
Currently Working ---> JAVA REST API , Angular2 , Ionic2 , HTML5 ,CSS3, Spring , Hibernate etc. Previously Used ---> Android, iOS Swift etc. Interested In --> Big Data , Hadoop etc.
Updated on July 03, 2022Comments
-
Rohan Kadu almost 2 years
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.
-
Ayush Gupta over 6 yearsread this too: docs.aws.amazon.com/cognito/latest/developerguide/…
-
-
Rohan Kadu over 6 yearsSo is there any standards for this payload or it can be any custom json ?
-
JEY over 6 yearsyou can do whatever you want but iana.org/assignments/jwt/jwt.xhtml defined standard public clain and tools.ietf.org/html/rfc7519 define registered claim
-
Rohan Kadu over 6 yearsThis 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 ??
-
JEY over 6 yearsYes in order to modify the content you need to know the private key or the secret (depending on the algorithm used).
-
Rohan Kadu over 6 yearsThanks for your reply . It helped me.
-
Olasunkanmi about 5 yearsDoes it mean, I have to generate different web tokens for different roles or privileges ?
-
JEY about 5 yearsWhat do you mean. A token can have multiple roles or privilege in it. But each user should have its own.