Comments (15)
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
},
)
from fastapi-azure-auth.
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.
from fastapi-azure-auth.
@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. ๐
from fastapi-azure-auth.
If you preset the scope in the swagger_ui_init_oauth
option, then you have the checkbox ticked automatically.
from fastapi-azure-auth.
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 ๐
from fastapi-azure-auth.
Looked into it and found:
- FastAPI removes any scopes (from the padlock) that isn't a subclass of their Oauth/OIDC-class
- We cannot subclass
Oauth2
, and are forced to rather instance it inside our own class due tomypy
errors when changing return types on a superclass.
from fastapi-azure-auth.
I've submitted a PR here tiangolo/fastapi#5614. I'll update this thread whenever I get a reply there.
from fastapi-azure-auth.
wow.. that was too quick.. thank you for the PR.. do you know when it will be pushed to artifactory
from fastapi-azure-auth.
That's interesting, thanks! I'm tempted to close this with that solution, since the PR isn't going anywhere.
from fastapi-azure-auth.
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.
from fastapi-azure-auth.
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)
``ยด
from fastapi-azure-auth.
I like the idea but this would be a breaking change I think as it was introduced with v2
from fastapi-azure-auth.
@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.
from fastapi-azure-auth.
I'll provide a PR for the changes :)
from fastapi-azure-auth.
Awesome, thanks. I'll do my best to get to your PRs this weekend. ๐
from fastapi-azure-auth.
Related Issues (20)
- [Feature request] support Pydantic v2 syntax / @validator -> @field_validator HOT 5
- [BUG/Question] Fixing TypeError during WebSocket Authentication Migration from FastAPI 0.96 to 0.97 HOT 8
- Calling your APIs from Python not working HOT 22
- [Question] Middleware logging does not get request.state.user HOT 2
- Make leeway a setting available for configuration
- [Question] HOT 6
- [BUG/Question] auth_time is parsed as a string, should be int HOT 2
- [BUG/Question] Got 'Token contains invalid claims' error for the `single tenant setup example ` HOT 6
- [Question] Validate bearer token from Angular SPA (Azure AD) in FastAPI HOT 4
- [BUG/Question] Error calling openid_config.load_config with Httpx 0.25.1 HOT 4
- [Bug/Question] HOT 2
- Adding new fields for Client Secret JWT HOT 1
- [Question] Graph API call triggers "admin consent required" HOT 1
- SOLVED: CVE-2024-23342 `ecdsa` may be vulnerable to the Minerva attack HOT 3
- Facing authentication issue mentioning pkce required for cross-origin authorization code redemption HOT 1
- [BUG] got claim `acct` in type `int`, but fastapi-azure-auth is waiting for `str` HOT 1
- Add ability to specify audience and issuer to validate token claims against HOT 1
- [BUG/Question] Example use cases for scopes HOT 6
- [Feature request] Support WebSocket connections. HOT 3
- Empty raise HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ๐๐๐
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google โค๏ธ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fastapi-azure-auth.