本文整理汇总了Python中rest_framework.authentication.get_authorization_header方法的典型用法代码示例。如果您正苦于以下问题:Python authentication.get_authorization_header方法的具体用法?Python authentication.get_authorization_header怎么用?Python authentication.get_authorization_header使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.authentication
的用法示例。
在下文中一共展示了authentication.get_authorization_header方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_access_token
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def get_access_token(self, request):
"""
Get the access token based on a request.
Returns None if no authentication details were provided. Raises
AuthenticationFailed if the token is incorrect.
"""
header = authentication.get_authorization_header(request)
if not header:
return None
header = header.decode(authentication.HTTP_HEADER_ENCODING)
auth = header.split()
if auth[0].lower() != 'bearer':
return None
if len(auth) == 1:
msg = 'Invalid "bearer" header: No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid "bearer" header: Credentials string should not contain spaces.'
raise exceptions.AuthenticationFailed(msg)
return auth[1]
示例2: authenticate
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def authenticate(self, request):
auth = authentication.get_authorization_header(request).split()
if not auth or auth[0].lower() != self.keyword.lower().encode():
return None
if len(auth) == 1:
msg = _('Invalid token header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid token header. Sign string '
'should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
try:
token = auth[1].decode()
except UnicodeError:
msg = _('Invalid token header. Sign string '
'should not contain invalid characters.')
raise exceptions.AuthenticationFailed(msg)
return self.authenticate_credentials(token)
示例3: get_access_token
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def get_access_token(request):
"""Retrieve access token from the request
The access token is searched first the request's session. If it is not
found it is then searched in the request's ``Authorization`` header.
Args:
request (Request): Django request from the user
Returns:
dict: JWT payload of the bearer token
"""
access_token = request.session.get("access_token")
if access_token is None: # Bearer token login
access_token = get_authorization_header(request).split()[1]
return JWT().unpack(access_token).payload()
示例4: get_jwt_token
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def get_jwt_token(self, request):
auth = get_authorization_header(request).split()
if not auth or smart_text(auth[0].lower()) != "bearer":
return None
if len(auth) == 1:
msg = _("Invalid Authorization header. No credentials provided.")
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _(
"Invalid Authorization header. Credentials string "
"should not contain spaces."
)
raise exceptions.AuthenticationFailed(msg)
return auth[1]
示例5: authenticate
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def authenticate(self, request):
"""
Returns two-tuple of (user, token) if authentication succeeds,
or None otherwise.
"""
auth = get_authorization_header(request).split()
if len(auth) == 1:
msg = 'Invalid bearer header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid bearer header. Token string should not contain spaces.'
raise exceptions.AuthenticationFailed(msg)
if auth and auth[0].lower() == b'bearer':
access_token = auth[1]
elif 'access_token' in request.POST:
access_token = request.POST['access_token']
elif 'access_token' in request.GET and self.allow_query_params_token:
access_token = request.GET['access_token']
else:
return None
return self.authenticate_credentials(request, access_token)
示例6: get_bearer_token
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def get_bearer_token(self, request):
auth = get_authorization_header(request).split()
header_prefix = "Bearer"
if not auth:
return None
if smart_text(auth[0].lower()) != header_prefix.lower():
raise HttpError(HttpResponseUnauthorized("No Bearer Authorization header"))
if len(auth) == 1:
msg = "Invalid Authorization header. No credentials provided"
raise HttpError(HttpResponseUnauthorized(msg))
elif len(auth) > 2:
msg = (
"Invalid Authorization header. Credentials string should "
"not contain spaces."
)
raise HttpError(HttpResponseUnauthorized(msg))
return auth[1]
示例7: authenticate
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def authenticate(self, request):
auth_header = get_authorization_header(request).decode().split()
if not auth_header or auth_header[0].lower() != self.keyword.lower():
return None
access_token = auth_header[1]
return self.authenticate_credentials(access_token)
示例8: authenticate
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def authenticate(self, request):
""" Authenticates users using a provided Bearer token. """
# First step, retrieves the Bearer token from the authorization header.
auth = get_authorization_header(request).split()
if not auth or smart_text(auth[0].lower()) != 'bearer':
return
if len(auth) == 1:
raise AuthenticationFailed('Invalid authorization header; no bearer token provided')
elif len(auth) > 2:
raise AuthenticationFailed('Invalid authorization header; many bearer tokens provided')
bearer_token = smart_text(auth[1])
# Tries to retrieve user information from the OP.
try:
userinfo_response = requests.get(
oidc_rp_settings.PROVIDER_USERINFO_ENDPOINT,
headers={'Authorization': 'Bearer {0}'.format(bearer_token)})
userinfo_response.raise_for_status()
except HTTPError:
raise AuthenticationFailed('Bearer token seems invalid or expired.')
userinfo_response_data = userinfo_response.json()
# Tries to retrieve a corresponding user in the local database and creates it if applicable.
try:
oidc_user = OIDCUser.objects.select_related('user').get(
sub=userinfo_response_data.get('sub'))
except OIDCUser.DoesNotExist:
oidc_user = create_oidc_user_from_claims(userinfo_response_data)
oidc_user_created.send(sender=self.__class__, request=request, oidc_user=oidc_user)
else:
update_oidc_user_from_claims(oidc_user, userinfo_response_data)
return oidc_user.user, bearer_token
示例9: authenticate
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def authenticate(self, request):
"""
Returns a `User` if a correct username and password have been supplied
using HTTP Basic authentication. Otherwise returns `None`.
"""
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'basic':
return None
if len(auth) == 1:
msg = 'Invalid basic header. No credentials provided.'
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = 'Invalid basic header. Credentials string should not contain spaces.'
raise exceptions.AuthenticationFailed(msg)
try:
auth_parts = base64.b64decode(auth[1]).decode(
HTTP_HEADER_ENCODING).partition(':')
except (TypeError, UnicodeDecodeError):
msg = 'Invalid basic header. Credentials not correctly base64 encoded'
raise exceptions.AuthenticationFailed(msg)
userid, password = auth_parts[0], auth_parts[2]
return self.authenticate_credentials(userid, password)
示例10: get_bearer_token
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def get_bearer_token(self, request):
auth = get_authorization_header(request).split()
auth_header_prefix = api_settings.BEARER_AUTH_HEADER_PREFIX.lower()
if not auth or smart_text(auth[0].lower()) != auth_header_prefix:
return None
if len(auth) == 1:
msg = _('Invalid Authorization header. No credentials provided')
raise AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid Authorization header. Credentials string should not contain spaces.')
raise AuthenticationFailed(msg)
return auth[1]
示例11: get_jwt_value
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def get_jwt_value(self, request):
auth = get_authorization_header(request).split()
auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower()
if not auth or smart_text(auth[0].lower()) != auth_header_prefix:
return None
if len(auth) == 1:
msg = _('Invalid Authorization header. No credentials provided')
raise AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid Authorization header. Credentials string should not contain spaces.')
raise AuthenticationFailed(msg)
return auth[1]
示例12: authenticate
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def authenticate(self, request):
auth = get_authorization_header(request).split()
authenticate_header = self.authenticate_header(request=request)
if not auth or smart_text(auth[0].lower()) != authenticate_header.lower():
return None
if len(auth) == 1:
msg = _("Invalid token header. No credentials provided.")
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _("Invalid token header. Token string should not contain spaces.")
raise exceptions.AuthenticationFailed(msg)
try:
token = auth[1].decode()
except UnicodeError:
msg = _("Invalid token header. Token string should not contain invalid characters.")
raise exceptions.AuthenticationFailed(msg)
try:
payload = decode_jwt_token(token=token)
except jwt.exceptions.ExpiredSignature:
msg = _("Signature has expired.")
raise exceptions.AuthenticationFailed(msg)
except jwt.exceptions.DecodeError:
msg = _("Error decoding signature.")
raise exceptions.AuthenticationFailed(msg)
except jwt.exceptions.InvalidKeyError:
msg = _("Unauthorized token signing key.")
raise exceptions.AuthenticationFailed(msg)
except jwt.exceptions.InvalidTokenError:
raise exceptions.AuthenticationFailed()
return self.authenticate_credentials(payload=payload, request=request)
示例13: authenticate
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def authenticate(self, request):
request.oauth2_error = getattr(request, "oauth2_error", {})
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b"bearer":
return None
if len(auth) == 1:
msg = "Invalid token header. No credentials provided."
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = "Invalid token header. " "Token string should not contain spaces."
raise exceptions.AuthenticationFailed(msg)
try:
token = auth[1].decode()
except UnicodeError:
msg = (
"Invalid token header. "
"Token string should not contain invalid characters."
)
raise exceptions.AuthenticationFailed(msg)
return self.authenticate_credentials(token)
示例14: get_auth_token
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def get_auth_token(request):
"""
Return the current request auth token.
The token is get using HTTP_AUTHORIZATION header on each request, or
using a cookie if AUTH_COOKIE_NAME setting is set.
The header is validated in order to ensure request is formatted as needed.
A valid authorization header look like(default settings):
```
Authorization: Bearer <auth0_generated_token>
```
"""
logger.debug(
"Getting auth token"
)
auth_header = get_authorization_header(request).split()
auth_token = None
if validate_authorization_header(auth_header):
logger.debug(
"Authorization header is valid"
)
auth_token = force_str(auth_header[1])
# If authorization header doesn't exists, use a cookie
elif not auth_header and auth0_api_settings.AUTH_COOKIE_NAME:
logger.warning(
"Using Cookie instead of header"
)
auth_token = request.COOKIES.get(auth0_api_settings.AUTH_COOKIE_NAME)
else:
logger.debug(
"Invalid authorization header"
)
auth_token = None # Just for maker it clear
return auth_token
示例15: delete
# 需要导入模块: from rest_framework import authentication [as 别名]
# 或者: from rest_framework.authentication import get_authorization_header [as 别名]
def delete(self, request, *args, **kwargs):
"""Delete auth token when `delete` request was issued."""
# Logic repeated from DRF because one cannot easily reuse it
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'token':
return response.Response(status=status.HTTP_400_BAD_REQUEST)
if len(auth) == 1:
msg = 'Invalid token header. No credentials provided.'
return response.Response(msg, status=status.HTTP_400_BAD_REQUEST)
elif len(auth) > 2:
msg = 'Invalid token header. Token string should not contain spaces.'
return response.Response(msg, status=status.HTTP_400_BAD_REQUEST)
try:
token = self.model.objects.get(key=auth[1])
except self.model.DoesNotExist:
pass
else:
token.delete()
signals.user_logged_out.send(
type(self),
user=token.user,
request=request,
)
return response.Response(status=status.HTTP_204_NO_CONTENT)