Coverage for fastapi/security/open_id_connect_url.py: 100%

19 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2025-05-05 00:03 +0000

1from typing import Optional 1abcdef

2 

3from fastapi.openapi.models import OpenIdConnect as OpenIdConnectModel 1abcdef

4from fastapi.security.base import SecurityBase 1abcdef

5from starlette.exceptions import HTTPException 1abcdef

6from starlette.requests import Request 1abcdef

7from starlette.status import HTTP_403_FORBIDDEN 1abcdef

8from typing_extensions import Annotated, Doc 1abcdef

9 

10 

11class OpenIdConnect(SecurityBase): 1abcdef

12 """ 

13 OpenID Connect authentication class. An instance of it would be used as a 

14 dependency. 

15 """ 

16 

17 def __init__( 1abcdef

18 self, 

19 *, 

20 openIdConnectUrl: Annotated[ 

21 str, 

22 Doc( 

23 """ 

24 The OpenID Connect URL. 

25 """ 

26 ), 

27 ], 

28 scheme_name: Annotated[ 

29 Optional[str], 

30 Doc( 

31 """ 

32 Security scheme name. 

33 

34 It will be included in the generated OpenAPI (e.g. visible at `/docs`). 

35 """ 

36 ), 

37 ] = None, 

38 description: Annotated[ 

39 Optional[str], 

40 Doc( 

41 """ 

42 Security scheme description. 

43 

44 It will be included in the generated OpenAPI (e.g. visible at `/docs`). 

45 """ 

46 ), 

47 ] = None, 

48 auto_error: Annotated[ 

49 bool, 

50 Doc( 

51 """ 

52 By default, if no HTTP Authorization header is provided, required for 

53 OpenID Connect authentication, it will automatically cancel the request 

54 and send the client an error. 

55 

56 If `auto_error` is set to `False`, when the HTTP Authorization header 

57 is not available, instead of erroring out, the dependency result will 

58 be `None`. 

59 

60 This is useful when you want to have optional authentication. 

61 

62 It is also useful when you want to have authentication that can be 

63 provided in one of multiple optional ways (for example, with OpenID 

64 Connect or in a cookie). 

65 """ 

66 ), 

67 ] = True, 

68 ): 

69 self.model = OpenIdConnectModel( 1abcdef

70 openIdConnectUrl=openIdConnectUrl, description=description 

71 ) 

72 self.scheme_name = scheme_name or self.__class__.__name__ 1abcdef

73 self.auto_error = auto_error 1abcdef

74 

75 async def __call__(self, request: Request) -> Optional[str]: 1abcdef

76 authorization = request.headers.get("Authorization") 1ygzAhBCiDEjFGkHIlJKmLMnNOoPQpRSqTUrVWsXYtZ0u12v34w56x7

77 if not authorization: 1ygzAhBCiDEjFGkHIlJKmLMnNOoPQpRSqTUrVWsXYtZ0u12v34w56x7

78 if self.auto_error: 1ghijklmnopqrstuvwx

79 raise HTTPException( 1ghjkmnpqstvw

80 status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" 

81 ) 

82 else: 

83 return None 1ilorux

84 return authorization 1yzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567