本文整理汇总了Python中starlette.status.HTTP_401_UNAUTHORIZED属性的典型用法代码示例。如果您正苦于以下问题:Python status.HTTP_401_UNAUTHORIZED属性的具体用法?Python status.HTTP_401_UNAUTHORIZED怎么用?Python status.HTTP_401_UNAUTHORIZED使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类starlette.status
的用法示例。
在下文中一共展示了status.HTTP_401_UNAUTHORIZED属性的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_user_access_token
# 需要导入模块: from starlette import status [as 别名]
# 或者: from starlette.status import HTTP_401_UNAUTHORIZED [as 别名]
def create_user_access_token(db: Session = Depends(get_db), *, user: UserLogin):
user = crud.user.authenticate(
db, username=user.username, password=user.password
)
if not user or not crud.user.is_active(user):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect user")
access_token_expires = timedelta(minutes=config.ACCESS_TOKEN_EXPIRE_MINUTES)
access_token_result = {
"access_token": create_access_token(
data={"user_id": user.id}, expires_delta=access_token_expires
),
"token_type": "bearer",
"expires_in": access_token_expires.total_seconds()
}
return dict(result=access_token_result)
示例2: __call__
# 需要导入模块: from starlette import status [as 别名]
# 或者: from starlette.status import HTTP_401_UNAUTHORIZED [as 别名]
def __call__( # type: ignore
self, request: Request
) -> Optional[HTTPBasicCredentials]:
authorization: str = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if self.realm:
unauthorized_headers = {"WWW-Authenticate": f'Basic realm="{self.realm}"'}
else:
unauthorized_headers = {"WWW-Authenticate": "Basic"}
invalid_user_credentials_exc = HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Invalid authentication credentials",
headers=unauthorized_headers,
)
if not authorization or scheme.lower() != "basic":
if self.auto_error:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers=unauthorized_headers,
)
else:
return None
try:
data = b64decode(param).decode("ascii")
except (ValueError, UnicodeDecodeError, binascii.Error):
raise invalid_user_credentials_exc
username, separator, password = data.partition(":")
if not (separator):
raise invalid_user_credentials_exc
return HTTPBasicCredentials(username=username, password=password)
示例3: __call__
# 需要导入模块: from starlette import status [as 别名]
# 或者: from starlette.status import HTTP_401_UNAUTHORIZED [as 别名]
def __call__(self, request: Request) -> Optional[str]:
authorization: str = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "bearer":
if self.auto_error:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
else:
return None
return param
示例4: test_unauthorized_exception
# 需要导入模块: from starlette import status [as 别名]
# 或者: from starlette.status import HTTP_401_UNAUTHORIZED [as 别名]
def test_unauthorized_exception():
detail = "I don't know who you are, stranger."
with pytest.raises(UnauthorizedError) as excinfo:
raise UnauthorizedError(
fields=[{"field": "because of this."}],
detail=detail
)
exc = excinfo.value
assert exc.error_code == status.HTTP_401_UNAUTHORIZED
assert exc.status_code == status.HTTP_401_UNAUTHORIZED
assert exc.detail == detail
assert exc.fields == [{"field": "because of this."}]
error_code = 444
with pytest.raises(UnauthorizedError) as excinfo:
raise UnauthorizedError(
fields=[{"field": "because of this."}],
detail=detail,
error_code=error_code
)
exc = excinfo.value
assert exc.error_code == error_code
assert exc.status_code == status.HTTP_401_UNAUTHORIZED
assert exc.detail == detail
assert exc.fields == [{"field": "because of this."}]
示例5: __call__
# 需要导入模块: from starlette import status [as 别名]
# 或者: from starlette.status import HTTP_401_UNAUTHORIZED [as 别名]
def __call__(
self, request: Request, security_scopes: SecurityScopes, return_token=False
):
if not self.enabled:
return None
if security_scopes.scopes:
authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
else:
authenticate_value = f"Bearer"
token: str = await oauth2_scheme(request) if not self.token else self.token
data = (
await models.User.join(models.Token)
.select(models.Token.id == token)
.gino.load((models.User, models.Token))
.first()
)
if data is None:
raise HTTPException(
status_code=HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": authenticate_value},
)
user, token = data # first validate data, then unpack
forbidden_exception = HTTPException(
status_code=HTTP_403_FORBIDDEN,
detail="Not enough permissions",
headers={"WWW-Authenticate": authenticate_value},
)
if "full_control" not in token.permissions:
for scope in security_scopes.scopes:
if scope not in token.permissions and not check_selective_scopes(
request, scope, token
):
raise forbidden_exception
if "server_management" in security_scopes.scopes and not user.is_superuser:
raise forbidden_exception
if return_token:
return user, token
return user