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

19 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from typing import Optional 1abcde

2 

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

4from fastapi.security.base import SecurityBase 1abcde

5from starlette.exceptions import HTTPException 1abcde

6from starlette.requests import Request 1abcde

7from starlette.status import HTTP_403_FORBIDDEN 1abcde

8from typing_extensions import Annotated, Doc 1abcde

9 

10 

11class OpenIdConnect(SecurityBase): 1abcde

12 """ 

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

14 dependency. 

15 """ 

16 

17 def __init__( 1abcde

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( 1abcde

70 openIdConnectUrl=openIdConnectUrl, description=description 

71 ) 

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

73 self.auto_error = auto_error 1abcde

74 

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

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

77 if not authorization: 1abcde

78 if self.auto_error: 1abcde

79 raise HTTPException( 1abcde

80 status_code=HTTP_403_FORBIDDEN, detail="Not authenticated" 

81 ) 

82 else: 

83 return None 1abcde

84 return authorization 1abcde