fastapi-azure-auth icon indicating copy to clipboard operation
fastapi-azure-auth copied to clipboard

Scopes missing in /docs at each endpoint padlock

Open Pkumar-1988 opened this issue 3 years ago โ€ข 15 comments

Describe the bug Scopes are missing if we select padlock symbol next to each api endpoint while trying to authorize. they do appear when we select authorize button at the top.

To Reproduce use below azure scheme

azure_scheme = SingleTenantAzureAuthorizationCodeBearer(
    app_client_id=settings.APP_CLIENT_ID,
    tenant_id=settings.TENANT_ID,
    scopes={
        f'api://{settings.APP_CLIENT_ID}/user_impersonation': 'user_impersonation',
    }
)

use this scheme as a dependency to your endpoint

app.include_router(api_router, prefix=settings.API_V1_STR, dependencies=[Security(azure_scheme, scopes=['user_impersonation'])])

go to /docs image

you can see scopes when you click authorize button

image

if you click on padlock below scopes are missing

image image

and unable to authorize as I am getting below error..

image

Pkumar-1988 avatar Nov 07 '22 12:11 Pkumar-1988

Huh, good catch. I didnโ€™t know this was a feature in Swagger, honestly. Would you like to look into how to implement it? Pull requests welcome ๐Ÿ˜Š

JonasKs avatar Nov 07 '22 16:11 JonasKs

Looked into it and found:

JonasKs avatar Nov 10 '22 18:11 JonasKs

I've submitted a PR here https://github.com/tiangolo/fastapi/pull/5614. I'll update this thread whenever I get a reply there.

JonasKs avatar Nov 10 '22 19:11 JonasKs

wow.. that was too quick.. thank you for the PR.. do you know when it will be pushed to artifactory

Pkumar-1988 avatar Nov 11 '22 10:11 Pkumar-1988

@Pkumar-1988 , we have to wait for FastAPI maintainers (tiangolo specifically) to respond first. If they accept and merge, I'll have to edit how we handle scopes in this package, since Azure don't accept and respond with the same kind of scopes (unfortunately).

In other words: I have no idea, it is in FastAPIs hands now. ๐Ÿ˜Š

JonasKs avatar Nov 11 '22 11:11 JonasKs

If you preset the scope in the swagger_ui_init_oauth option, then you have the checkbox ticked automatically.

rhuanbarreto avatar Oct 04 '23 07:10 rhuanbarreto

That's interesting, thanks! I'm tempted to close this with that solution, since the PR isn't going anywhere.

JonasKs avatar Oct 04 '23 08:10 JonasKs

With @rhuanbarreto 's hint I can confirm the tickbox is selected automatically and it's possible to auth in endpoints directly.

Here's what I do for B2C:

SCOPE_NAME = f'https://{settings.TENANT_NAME}.onmicrosoft.com/{settings.APP_CLIENT_ID}/user_impersonation'
SCOPE_DESCRIPTION = 'user_impersonation'
SCOPES = {SCOPE_NAME: SCOPE_DESCRIPTION}

azure_scheme = B2CMultiTenantAuthorizationCodeBearer(
    app_client_id=settings.APP_CLIENT_ID,
    openid_config_url=OPENID_CONFIG_URL,
    openapi_authorization_url=OPENID_AUTH_URL,
    openapi_token_url=OPENID_TOKEN_URL,
    scopes=SCOPES,
    validate_iss=False,
    auto_error=False,
)

Then use the scope in the FastAPI.app instance:

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

davidhuser avatar Oct 12 '23 08:10 davidhuser

Thank you so much.

I think we could add this to all the docs, and then close this issue. I'll see if we can do it together with #150.

JonasKs avatar Oct 12 '23 08:10 JonasKs

@JonasKs @davidhuser

What would you think about integrating the generated information in the settings using computed_fields? Because this would be a bigger change I would personally like to split #154 and the PR for this issue? We could also apply this to the openapi_authorization_url and openapi_token_url?

import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import AnyHttpUrl, computed_field
from pydantic_settings import BaseSettings, SettingsConfigDict
from fastapi_azure_auth import B2CMultiTenantAuthorizationCodeBearer



class Settings(BaseSettings):
    BACKEND_CORS_ORIGINS: list[str | AnyHttpUrl] = ['http://localhost:8000']
    TENANT_NAME: str = ""
    APP_CLIENT_ID: str = ""
    OPENAPI_CLIENT_ID: str = ""
    AUTH_POLICY_NAME: str = ""
    SCOPE_DESCRIPTION: str = "user_impersonation"
    
    @computed_field
    @property
    def SCOPE_NAME(self) -> str:
        return f'https://{self.TENANT_NAME}.onmicrosoft.com/{self.APP_CLIENT_ID}/{self.SCOPE_DESCRIPTION}'

    @computed_field
    @property
    def SCOPES(self) -> dict:
        return {
            self.SCOPE_NAME: self.SCOPE_DESCRIPTION
        }
    
    @computed_field
    @property
    def OPENID_CONFIG_URL(self) -> dict:
        return f'https://{self.TENANT_NAME}.b2clogin.com/{self.TENANT_NAME}.onmicrosoft.com/{self.AUTH_POLICY_NAME}/v2.0/.well-known/openid-configuration'

    model_config = SettingsConfigDict(
        env_file='.env',
        env_file_encoding='utf-8',
        case_sensitive=True
    )

settings = Settings()

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

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 = B2CMultiTenantAuthorizationCodeBearer(
    app_client_id=settings.APP_CLIENT_ID,
    openid_config_url=settings.OPENID_CONFIG_URL,
    openapi_authorization_url=f'https://{settings.TENANT_NAME}.b2clogin.com/{settings.TENANT_NAME}.onmicrosoft.com/{settings.AUTH_POLICY_NAME}/oauth2/v2.0/authorize',
    openapi_token_url=f'https://{settings.TENANT_NAME}.b2clogin.com/{settings.TENANT_NAME}.onmicrosoft.com/{settings.AUTH_POLICY_NAME}/oauth2/v2.0/token',
    scopes={
        settings.SCOPES
    },
    validate_iss=False,
)


@app.get("/")
async def root():
    return {"message": "Hello World"}


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

nikstuckenbrock avatar Oct 12 '23 09:10 nikstuckenbrock

I like the idea but this would be a breaking change I think as it was introduced with v2

davidhuser avatar Oct 12 '23 09:10 davidhuser

@davidhuser But this shouldn't be a problem? Using pydantic-settings enforces pydantic to be version 2.0.1 or higher. This version includes the computed_field field property.

nikstuckenbrock avatar Oct 13 '23 05:10 nikstuckenbrock

Right now both pydantic v1 and v2 works. How ever, as stated in other issues, I don't really plan on supporting v1 pydantic other than on a backport branch for security releases.

Pydantic v1 is no longer actively developed and will only receive security fixes. I know fastapi supports both and probably will for some time, but there's no reason for every single package out there to support both, in my opinion.
Please let me know if you disagree.

JonasKs avatar Oct 13 '23 05:10 JonasKs

I'll provide a PR for the changes :)

nikstuckenbrock avatar Oct 13 '23 06:10 nikstuckenbrock

Awesome, thanks. I'll do my best to get to your PRs this weekend. ๐Ÿ˜Š

JonasKs avatar Oct 13 '23 22:10 JonasKs

I'm closing this - it's really a feature request to FastAPI, and I've tried to submit a PR which hasn't been accepted for years.

Sorry!

JonasKs avatar Jun 13 '24 16:06 JonasKs