Skip to content

Commit

Permalink
Add: Documentation about validating JWTs and extracting information f…
Browse files Browse the repository at this point in the history
…rom them (#96)
  • Loading branch information
steven-noorbergen committed Dec 31, 2024
1 parent f22da72 commit 40c47d7
Show file tree
Hide file tree
Showing 3 changed files with 123 additions and 1 deletion.
4 changes: 4 additions & 0 deletions docs/assets/stylesheet/theme.css
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,10 @@ body::before {
box-shadow: inherit;
}

.md-typeset :target {
--md-scroll-margin: 4.2rem;
}

.esi-nav-container {
display: flex;
flex-direction: row;
Expand Down
34 changes: 33 additions & 1 deletion docs/services/sso/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ sequenceDiagram
sso-->>app: Responds with an access token and refresh token
```

## Terms and important notes
<h2>Terms and important notes</h2>

- **Client ID and Secret**: The client ID and secret are used to authenticate the application with the SSO service.
The Client ID is public and can be shared, but the secret must be kept private.
Expand Down Expand Up @@ -172,3 +172,35 @@ To create a code challenge, hash the code verifier using the SHA-256 algorithm,
<h4>Example</h4>

--8<-- "snippets/sso/authorization-code-pkce.md"

## Validating JWT Tokens

Once you have obtained an access token from the EVE SSO, you can use it to authenticate requests to ESI. The access token is a JWT (JSON Web Token) that contains information about the user and the scopes that have been granted. If you want to ensure that the token is valid and issued by the EVE SSO, you need to verify the signature, check the expiration time, and ensure that the token is intended for your application.

<h3>Signature Verification</h3>

The access token is a JWT that is signed by the EVE SSO using an RSA key. To verify the signature, you need to fetch the public key from the SSO's JWKS (JSON Web Key Set) endpoint and use it to validate the token.

The SSO serivce has a [metadata endpoint](https://login.eveonline.com/.well-known/oauth-authorization-server) that provides the URL to the JWKS endpoint. If you want to verify the signature of the access token, be sure to fetch the metadata information first, and then fetch the public key from the JWKS endpoint. While the JWKS endpoint is unlikely to change, it is not guaranteed to be static, so it is recommended to fetch it from the metadata endpoint each time you need it.

<h3>Issuer Verification</h3>

The `iss` claim in the JWT token should match the issuer URL of the SSO service. This is the URL that the token was issued by, and should be `https://login.eveonline.com/`. In some cases, `login.eveonline.com` may be used as the issuer, so it is recommended to check for both, and reject tokens that do not match.

<h3>Audience</h3>

The `aud` claim in the JWT token is the audience of the token. This should be an array, with one value being the `client_id` of your application, and the other a static `"EVE Online"` value. You should check that the `aud` claim contains both of these values, and reject tokens that do not match.

<h3>Expiration Time</h3>

The `exp` claim in the JWT token is the expiration time of the token, represented as a Unix timestamp. You should check this claim to ensure that the token has not expired. If the token has expired, you should request a new token using the refresh token. Most `jose`-compatible libraries will automatically check the expiration time for you, and have an optional setting to allow for a grace period.

<h4>Example</h4>

--8<-- "snippets/sso/validate-jwt-token.md"

## JWT Token Claims

Now that you have verified the JWT Token, you can use the claims belonging to the token to get more information about the access the token has, and for whom it was issued.

The `sub` claim in the JWT token is in the format of `EVE:CHARACTER:<character-id>` and can be used to get the current character's ID. The `name` claim contains the character's name, and the `scp` claim is an array of scopes that have been granted to this token.
86 changes: 86 additions & 0 deletions snippets/sso/validate-jwt-token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import requests
import time

from jose import jwt
from jose.exceptions import ExpiredSignatureError, JWTError

METADATA_URL = "https://login.eveonline.com/.well-known/oauth-authorization-server"
METADATA_CACHE_TIME = 300 # 5 minutes
ACCEPTED_ISSUERS = ("logineveonline.com", "https://login.eveonline.com")
EXPECTED_AUDIENCE = "EVE Online"

client_id = "your_client_id"

# We don't want to fetch the jwks data on every request, so we cache it for a short period
jwks_metadata = None
jwks_metadata_ttl = 0


def fetch_jwks_metadata():
"""
Fetches the JWKS metadata from the SSO server.
:returns: The JWKS metadata
"""
global jwks_metadata, jwks_metadata_ttl
if jwks_metadata is None or jwks_metadata_ttl < time.time():
resp = requests.get(METADATA_URL)
resp.raise_for_status()
metadata = resp.json()

jwks_uri = metadata["jwks_uri"]

resp = requests.get(jwks_uri)
resp.raise_for_status()

jwks_metadata = resp.json()
jwks_metadata_ttl = time.time() + METADATA_CACHE_TIME
return jwks_metadata


def validate_jwt_token(token):
"""
Validates a JWT Token.
:param str token: The JWT token to validate
:returns: The content of the validated JWT access token
:raises ExpiredSignatureError: If the token has expired
:raises JWTError: If the token is invalid
"""
metadata = fetch_jwks_metadata()
keys = metadata["keys"]
# Fetch the key algorithm and key idfentifier from the token header
header = jwt.get_unverified_header(token)
key = [
item
for item in keys
if item["kid"] == header["kid"] and item["alg"] == header["alg"]
].pop()
return jwt.decode(
token,
key=key,
algorithms=header["alg"],
issuer=ACCEPTED_ISSUERS,
audience=EXPECTED_AUDIENCE,
)


def is_token_valid(token):
"""
Simple check if the token is valid or not.
:returns: True if the token is valid, False otherwise
"""
try:
claims = validate_jwt_token(token)
# If our client_id is in the audience list, the token is valid, otherwise, we got a token for another client.
return client_id in claims["aud"]
except ExpiredSignatureError:
# The token has expired
return False
except JWTError:
# The token is invalid
return False
except Exception:
# Something went wrong
return False

0 comments on commit 40c47d7

Please sign in to comment.