Thomas Segato
Thomas Segato

Reputation: 5221

FastAPI Azure Auth - Proof Key for Code Exchange is required for cross-origin authorization code redemption

I have followed this sample as is: https://intility.github.io/fastapi-azure-auth/

However I get following error: AADSTS9002325: Proof Key for Code Exchange is required for cross-origin authorization code redemption.

As far as I can read this is related to the redirects uris not matching.

Fast API Open app reg: enter image description here

Fast API app reg: enter image description here

However those should match. And ideas how to solve or troubleshoot this? enter image description here

Code:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi_azure_auth import SingleTenantAzureAuthorizationCodeBearer
from pydantic import AnyHttpUrl, computed_field
import uvicorn
from fastapi import FastAPI, Security

from pydantic import AnyHttpUrl
from pydantic_settings import BaseSettings

from contextlib import asynccontextmanager
from typing import AsyncGenerator


class Settings(BaseSettings):
    BACKEND_CORS_ORIGINS: list[str | AnyHttpUrl] = ['http://localhost:8000']
    OPENAPI_CLIENT_ID: str = "  "
    APP_CLIENT_ID: str = "xxx"
    TENANT_ID: str = "xxx"
    SCOPE_DESCRIPTION: str = "user_impersonation"

    @computed_field
    @property
    def SCOPE_NAME(self) -> str:
        return f'api://{self.APP_CLIENT_ID}/{self.SCOPE_DESCRIPTION}'

    @computed_field
    @property
    def SCOPES(self) -> dict:
        return {
            self.SCOPE_NAME: self.SCOPE_DESCRIPTION,
        }

    class Config:
        env_file = '.env'
        env_file_encoding = 'utf-8'
        case_sensitive = True

settings = Settings()

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
    """
    Load OpenID config on startup.
    """
    await azure_scheme.openid_config.load_config()
    yield


app = FastAPI(
    swagger_ui_oauth2_redirect_url='/oauth2-redirect',
    swagger_ui_init_oauth={
        'usePkceWithAuthorizationCodeGrant': True,
        'clientId': settings.OPENAPI_CLIENT_ID,
    },
)

app = FastAPI()

if settings.BACKEND_CORS_ORIGINS:
    app.add_middleware(
        CORSMiddleware,
        allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
        allow_credentials=True,
        allow_methods=['*'],
        allow_headers=['*'],
    )

azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
    app_client_id=settings.APP_CLIENT_ID,
    tenant_id=settings.TENANT_ID,
    scopes=settings.SCOPES,
)


@app.get("/", dependencies=[Security(azure_scheme)])
async def root():
    return {"whoIsTheBest": "DNA Team is"}

if __name__ == '__main__':
    uvicorn.run('main:app', reload=True)

Upvotes: 2

Views: 143

Answers (1)

Aslesha Kantamsetti
Aslesha Kantamsetti

Reputation: 1408

I get following error: AADSTS9002325: Proof Key for Code Exchange is required for cross-origin authorization code redemption.

To resolve the above issue, I added the below redirect URL to the Web Platform in the Api App registration.

http://localhost:8000/docs

enter image description here

After adding the redirect URL, I ran the application.

enter image description here

After clicking the Authorize button, I selected my account.

enter image description here

I successfully logged in without any issues.

enter image description here

Upvotes: 0

Related Questions