[Python] Authorization code with PKCE returning invalid code verifier

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to generate an access token to use with Spotify's API using an authorization code with PKCE. After completing a post request, the response I get is that the code verifier is invalid. I'm fairly new to this, so I appreciate some of my code is not the most efficient way of doing things.

    from dotenv import load_dotenv
    import os
    import base64
    import requests
    import random
    import hashlib
    from urllib.parse import urlparse, urlunparse, urlencode

    load_dotenv()
    #retrieves client id and secret from .env file

    client_ID = os.getenv("CLIENT_ID")
    client_secret = os.getenv("CLIENT_SECRET")


    def Generate_Random_String(length):
    possible_Values = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
    values = []
    while len(values) < length:
    index = random.randint(0,65)
    random_Value = (possible_Values[index])
    values.append(random_Value)
    values = str(values)
    return (values)
    #create an array of random values of length given by parameter


    code_Verifier = Generate_Random_String(64)
    perm_code_verifier = open("Code Verifier.txt","w")
    perm_code_verifier.write(code_Verifier)
    #stores code verifier in a text file for more permanent access

    def code_hash(plain):
    #will use sha256 hash to encode a value
    plaintext = str(plain)
    object = hashlib.sha256(plaintext.encode("utf-8"))
    hex_dig = object.hexdigest()
    return(hex_dig)


    def base64encode(hashed):
    #encodes this in base64
    hashed = str(hashed)
    auth_bytes = hashed.encode("utf-8")
    auth_base64 = str(base64.b64encode(auth_bytes),"utf-8")
    array = auth_base64
    array = array.replace("+","-")
    array = array.replace("/","_")
    array = array.rstrip("=")
    #replaces these characters so it can be used in a url
    return array
    `

    hashed = code_hash(code_Verifier)
    codeChallenge = base64encode(hashed)
    #retrieves the code challenge

    scope = "user-read-private user-read-email"
    authURL = urlparse("https://accounts.spotify.com/authorize")
    redirectURI = "http://localhost:3000"
    #scope user agrees to and url for general spotify log in page



    parameters = {
    "response_type": "code",
    "client_id": client_ID,
    "scope": scope,
    "code_challenge_method": "S256",
    "code_challenge": codeChallenge,
    "redirect_uri" : redirectURI,
    }

    authUrl_incl_params = authURL._replace(query=urlencode(parameters))
    final_url = urlunparse(authUrl_incl_params)
    #creates final url for my program to allow them to log in using appropriate scopes

    print("Go to ", final_url, "to authenticate")
    code = input("Enter code recieved:")


    def get_token(code):
    file = open("Code Verifier.txt")
    codeVerifier = file.read()

    url = "https://accounts.spotify.com/api/token"

    payload = {
    "client_id": client_ID,
    "grant_type": "authorization_code",
    "code": code,
    "redirect_uri": redirectURI,
    "code_verifier":codeVerifier,
    }

    headers = {
    "Content-Type": "application/x-www-form-urlencoded",
    }

    try:
    response = requests.post(url,data=payload,headers = headers)
    response_ans = response.json()
    print (response_ans)
    token = response_ans.get("access_token")
    return(token)

    except:
    print("Error with code")


    token = get_token(code)
    print (token)


    My value for the token always comes back as none, and I get response_ans coming back as saying that code_verifier is invalid.

    Continue reading...

Compartilhe esta Página