當前位置: 首頁>>代碼示例>>Python>>正文


Python status.HTTP_401_UNAUTHORIZED屬性代碼示例

本文整理匯總了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) 
開發者ID:QAX-A-Team,項目名稱:LuWu,代碼行數:19,代碼來源:login.py

示例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) 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:33,代碼來源:http.py

示例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 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:15,代碼來源:oauth2.py

示例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."}] 
開發者ID:identixone,項目名稱:fastapi_contrib,代碼行數:29,代碼來源:test_exceptions.py

示例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 
開發者ID:MrNaif2018,項目名稱:bitcart,代碼行數:41,代碼來源:utils.py


注:本文中的starlette.status.HTTP_401_UNAUTHORIZED屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。