当前位置: 首页>>代码示例>>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;未经允许,请勿转载。