3
2

[AWS]CognitoのTokenを扱うライブラリ

Posted at

Amazon Cognitoのトークンを操作するためのモジュールです。このモジュールは、トークンのデコードや有効期限の確認、アクセストークンの更新など、Amazon Cognitoのトークンに関する一般的な操作をサポートします。

インポート

import jwt
import time
import boto3

クラス

1. CognitoAccessToken

アクセストークンを扱うためのクラスです。トークンをデコードし、有効期限の情報を取得します。

コンストラクタ

def __init__(self, token):
  • パラメータ: token (str) - デコードするアクセストークン。

メソッド

def is_expired(self):
  • 戻り値: トークンの有効期限が切れていればTrue、それ以外の場合はFalse。

2. CognitoIdToken

IDトークンを扱うためのクラスです。トークンをデコードし、有効期限の情報を取得します。

コンストラクタ

def __init__(self, token):
  • パラメータ: token (str) - デコードするIDトークン。

メソッド

def is_expired(self):
  • 戻り値: トークンの有効期限が切れていればTrue、それ以外の場合はFalse。

関数

refresh_access_token

Amazon Cognitoのリフレッシュトークンを使用して、新しいアクセストークンを取得する関数です。

def refresh_access_token(refresh_token, client_id):
  • パラメータ:

    • refresh_token (str) - 使用するリフレッシュトークン。
    • client_id (str) - CognitoユーザープールのクライアントID。
  • 戻り値: 新しいアクセストークン。

このモジュールを利用することで、Amazon Cognitoのトークンの操作を簡単かつ効率的に行うことができます。適切な方法で利用してください。

ソースコード

import jwt
import time
import boto3


class CognitoAccessToken:
    """Represents a decoded Cognito access token.
    
    Attributes:
        token (str): The raw access token.
        payload (dict): The decoded payload of the token.
        sub (str): The subject of the token, typically the user's ID.
        username (str): The username associated with the token.
    """

    def __init__(self, token):
        """Initialize the CognitoAccessToken object with the provided token.
        
        Args:
            token (str): The access token to decode.
        """
        self.token = token
        self.payload = jwt.decode(token, options={"verify_signature": False})
        self.sub = self.payload["sub"]
        self.username = self.payload["username"]

    def is_expired(self):
        """Determine if the access token has expired.
        
        Returns:
            bool: True if the token has expired, otherwise False.
        """
        current_time = int(time.time())
        return current_time > self.payload["exp"]

def refresh_access_token(refresh_token, client_id):
    """Refresh the Cognito access token using the provided refresh token and client ID.
    
    Args:
        refresh_token (str): The refresh token.
        client_id (str): The client ID associated with the Cognito user pool.
        
    Returns:
        str: The new access token.
    """
    client = boto3.client("cognito-idp")
    response = client.initiate_auth(
        AuthFlow="REFRESH_TOKEN_AUTH",
        AuthParameters={"REFRESH_TOKEN": refresh_token},
        ClientId=client_id,
    )
    access_token = response["AuthenticationResult"]["AccessToken"]
    return access_token

class CognitoIdToken:
    """Represents a decoded Cognito ID token.
    
    Attributes:
        token (str): The raw ID token.
        payload (dict): The decoded payload of the token.
        sub (str): The subject of the token, typically the user's ID.
    """

    def __init__(self, token):
        """Initialize the CognitoIdToken object with the provided token.
        
        Args:
            token (str): The ID token to decode.
        """
        self.token = token
        self.payload = jwt.decode(token, options={"verify_signature": False})
        self.sub = self.payload["sub"]

    def is_expired(self):
        """Determine if the ID token has expired.
        
        Returns:
            bool: True if the token has expired, otherwise False.
        """
        current_time = int(time.time())
        return current_time > self.payload["exp"]

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2