What is the aud claim in identity, authentication, and authorization?
The “aud” claim tells the system which recipient the token is meant for.
Imagine logging into a service, and your system sends a token to prove who you are. How does that token ensure it only works for the right service? That’s where the “aud” (audience) claim comes in.
The “aud” claim tells the system which recipient the token is meant for. It’s like writing the recipient’s name on an envelope to ensure the wrong person doesn’t open the letter.
How the “aud” claim works
When an authentication server creates a token (usually a JSON Web Token or JWT), it includes the “aud” claim. When a service receives this token, it checks the “aud” field. If the token says it’s for a different service, the token will be rejected.
This helps prevent unauthorized access by ensuring that even if someone intercepts the token, they can’t use it on a system it wasn’t intended for.
Example JWT payload
Here’s a simple example of a JWT payload that includes the “aud” claim:
{
"iss": "https://auth.example.com",
"sub": "user123",
"aud": "https://api.example.com",
"iat": 1679990000,
"exp": 1680000000
}
- iss: Who issued the token.
- sub: Who is the token about (the user)?
- aud: The intended recipient (in this case, the API).
- iat: When the token was issued.
- exp: When the token expires.
Creating a JWT with an “aud” claim
Below is a basic Node.js example using the jsonwebtoken
library to create a JWT that includes an “aud” claim:
const jwt = require('jsonwebtoken');
const payload = {
iss: 'https://auth.example.com',
sub: 'user123',
aud: 'https://api.example.com',
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 3600 // Valid for 1 hour
};
const secretKey = 'your-secret-key';
const token = jwt.sign(payload, secretKey);
console.log("Generated JWT:", token);
This code creates a token that tells the API it’s the intended recipient.
Verifying the “aud” Claim
When the API receives the token, it should check the “aud” claim to confirm it’s the right audience. Here’s how you might do that:
const jwt = require('jsonwebtoken');
const token = 'received.jwt.token.here'; // The token from the client
const secretKey = 'your-secret-key';
const expectedAudience = 'https://api.example.com';
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
console.error("Token verification failed:", err);
return;
}
if (decoded.aud !== expectedAudience) {
console.error("Invalid audience. Expected:", expectedAudience, "but got:", decoded.aud);
return;
}
console.log("Token is valid and intended for this API:", decoded);
});
This code checks that the token’s “aud” claim matches the API’s expected value before accepting the token.
In summary
- Purpose: The “aud” claim specifies the intended recipient of the token.
- Usage: It helps ensure that a token can only be used by the system it was meant for.
- Implementation: Always include the “aud” claim when creating tokens and validate it on the receiving end.