Skip to main content
Solved

EnvelopesApi's create_envelope responds USER_AUTHENTICATION_FAILED: One or both of Username and Password are invalid. Invalid access token

  • August 18, 2024
  • 3 replies
  • 420 views

Forum|alt.badge.img+3

I’m getting “USER_AUTHENTICATION_FAILED: One or both of Username and Password are invalid. Invalid access token” when I call create_envelope.

I know the access token is correct after it’s generated because “get_user_info” is returning the correct account id and username, but by the time I try to create the envelope, it says the access token is invalid.

in the code below, after “request_jwt_user_token”, the print commands are displaying the correct account id and username.

I have been stuck on this issue for a few days now and any help would be GREATLY appreciated!

Code:

import base64
from cryptography.hazmat.primitives import serialization
from docusign_esign import (
    ApiClient,
    EnvelopesApi,
    EnvelopeDefinition,
    Signer,
    Tabs,
    SignHere,
    InitialHere,
    Recipients,
    Document,
)
from docusign_esign.client.api_exception import ApiException
from django.conf import settings


scopes = ["signature", "impersonation"]
base_url = settings.DOCUSIGN_BASE_URL
integration_key = settings.DOCUSIGN_INTEGRATION_KEY


def get_api_client(access_token=None):
    api_client = ApiClient()
    api_client.set_oauth_host_name(base_url)
    api_client.set_base_path(base_url)
    if access_token:
        api_client.set_default_header(
            header_name="Authorization", 
            header_value=f"Bearer {access_token}"
        )
    return api_client


def load_private_key():
    with open(settings.DOCUSIGN_PRIVATE_KEY_PATH, "rb") as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(),
            password=None,
        )
    return private_key


def get_access_token(api_client, docusign_user_id):
    """
    Generates the access token using JWT and retrieves user information.
    """
    try:
        private_key_obj = load_private_key()
        private_key_bytes = private_key_obj.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        )

        # generate access token
        token_response = api_client.request_jwt_user_token(
            client_id=integration_key,
            user_id=docusign_user_id,
            oauth_host_name=base_url,
            private_key_bytes=private_key_bytes,
            expires_in=3600,
            scopes=scopes,
        )

        access_token = token_response.access_token
        api_client.set_default_header(
            header_name="Authorization", 
            header_value=f"Bearer {access_token}"
        )

        # retrieve user info to validate token and get account details
        user_info = api_client.get_user_info(access_token)
        accounts = user_info.get_accounts()
        api_account_id = accounts[0].account_id
        base_path = accounts[0].base_uri + "/restapi"

        print(f"Authenticated user: {user_info.name}")
        print(f"Account ID: {api_account_id}")

        return access_token, api_account_id, base_path
    except ApiException as e:
        handle_api_exception(e)
    except Exception as ex:
        handle_general_exception(ex)


def get_consent_url():
    """
    Construct the consent URL needed for DocuSign API usage
    """
    url_scopes = "+".join(scopes)
    redirect_uri = "https://developers.docusign.com/platform/auth/consent"
    consent_url = (
        f"https://account-d.docusign.com/oauth/auth?response_type=code&"
        f"scope={url_scopes}&client_id={integration_key}&redirect_uri={redirect_uri}"
    )
    return consent_url


def create_envelope_with_pdf(api_client, api_account_id, pdf_bytes, recipients, deal_data, in_person_signing=False):
    """
    Create and send envelope with the provided PDF and recipients
    """
    try:
        # print(f"API Account ID in Create: {api_account_id}")
        # print(f"API Client Headers in Create: {api_client.default_headers}")

        envelope_api = EnvelopesApi(api_client)

        document = Document(
            document_base64=base64.b64encode(pdf_bytes).decode("utf-8"),
            name="Deal Document",
            file_extension="pdf",
            document_id="1"
        )

        signers = build_signers(recipients, in_person_signing)

        envelope_definition = EnvelopeDefinition(
            email_subject="Please sign this document",
            documents=[document],
            recipients=Recipients(signers=signers),
            status="sent",
        )

        # authentication error occurring at create_envelope:
        response = envelope_api.create_envelope(account_id=api_account_id, envelope_definition=envelope_definition)

        return response.envelope_id
    except ApiException as e:
        handle_api_exception(e)
    except Exception as ex:
        handle_general_exception(ex)

 

Best answer by sammy_rabiei

I figured this out. I had to set the host in request_jwt_user_token

View Original
Is this content helpful?

3 replies

Forum|alt.badge.img+3
  • Author
  • New Voice
  • 9 replies
  • Answer
  • August 19, 2024

I figured this out. I had to set the host in request_jwt_user_token


Forum|alt.badge.img+1
  • Newcomer
  • 2 replies
  • March 7, 2025

Hi ​@sammy_rabiei  could you please details the solution? I have same error, with correct correct account id and username from the access token and i cannot figure it out. Thank you!


Forum|alt.badge.img+3
  • Author
  • New Voice
  • 9 replies
  • March 11, 2025

@dgh11 i had to add the following line in get_api_token:

api_client.host = settings.DOCUSIGN_API_HOST

here’s how it looked after the change:

def get_api_client(access_token=None):
    api_client = ApiClient()
    api_client.host = settings.DOCUSIGN_API_HOST
    api_client.set_oauth_host_name(base_url)
    api_client.set_base_path(base_url)
    if access_token:
        api_client.set_default_header(header_name="Authorization", header_value=f"Bearer {access_token}")
    return api_client