Althaf Muhammed
Althaf Muhammed

Reputation: 51

JWT Authentication with Airflow API

I am trying to implement a token based authentication as part of triggering an airflow dag. Is there way we can add JWT authentication to generate an access_token to trigger the API? Any help is much appreciated!

Upvotes: 5

Views: 2210

Answers (1)

smbanaei
smbanaei

Reputation: 1177

Our authentication service returns a JSON response like this :

{
    "clientToken": "322e8df6-0597-479e-984d-db6d8705ee66"
}

Here is my sample code in airflow 2.1 using SimpleHttpOperator and XCOM variable passing mechanism to overcome this problem :

    get_token = SimpleHttpOperator(
        task_id='get_token',
        method='POST',
        http_conn_id='http_service',
        data=json.dumps( {
            "username": "user_name",
            "password": "n46r4A83"
        }),
        endpoint='/authenticate',
        dag=dag,
        headers = {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        },
        response_filter=lambda response: response.json()['clientToken'],
    )

    
    get_cities = SimpleHttpOperator(
        task_id='get_cities',
        method='GET',
        http_conn_id='http_service',
        endpoint='/cities?dsCode=120',
        dag=dag,
        headers = {
        'X-CLIENT-TOKEN':'{{ ti.xcom_pull(task_ids="get_token") }}'
        }
        # response_filter=lambda response: response.json()['clientToken'],
    )

    get_token >> get_cities

Upvotes: 1

Related Questions