本文整理汇总了Python中rest_framework.exceptions.AuthenticationFailed方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.AuthenticationFailed方法的具体用法?Python exceptions.AuthenticationFailed怎么用?Python exceptions.AuthenticationFailed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.exceptions
的用法示例。
在下文中一共展示了exceptions.AuthenticationFailed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: passwd
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def passwd(self, request, **kwargs):
if not request.data.get('new_password'):
raise DeisException("new_password is a required field")
caller_obj = self.get_object()
target_obj = self.get_object()
if request.data.get('username'):
# if you "accidentally" target yourself, that should be fine
if caller_obj.username == request.data['username'] or caller_obj.is_superuser:
target_obj = get_object_or_404(User, username=request.data['username'])
else:
raise PermissionDenied()
if not caller_obj.is_superuser:
if not request.data.get('password'):
raise DeisException("password is a required field")
if not target_obj.check_password(request.data['password']):
raise AuthenticationFailed('Current password does not match')
target_obj.set_password(request.data['new_password'])
target_obj.save()
return Response({'status': 'password set'})
示例2: authenticate
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def authenticate(self, request):
"""
Returns a two-tuple of `User` and token if a valid signature has been
supplied using JWT-based authentication. Otherwise returns `None`.
"""
jwt_value = self._get_jwt_value(request)
if jwt_value is None:
return None
try:
payload = decode_jwt(jwt_value)
except jwt.ExpiredSignatureError:
msg = 'Signature has expired.'
raise exceptions.AuthenticationFailed(msg)
except jwt.DecodeError:
msg = 'Error decoding signature.'
raise exceptions.AuthenticationFailed(msg)
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed()
self._add_session_details(request, payload)
user = self.authenticate_credentials(payload)
return user, JwtToken(payload)
示例3: _get_jwt_value
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def _get_jwt_value(self, request):
auth = get_authorization_header(request).split()
auth_header_prefix = getattr(settings, 'JWT_AUTH_HEADER_PREFIX', 'JWT')
if not auth:
if getattr(settings, 'JWT_AUTH_COOKIE', None):
return request.COOKIES.get(settings.JWT_AUTH_COOKIE)
return None
if smart_str(auth[0]) != auth_header_prefix:
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)
jwt_value = auth[1]
if type(jwt_value) is bytes:
jwt_value = jwt_value.decode('utf-8')
return jwt_value
示例4: _authenticate_credentials
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def _authenticate_credentials(self, request, token):
"""
Try to authenticate the given credentials. If authentication is
successful, return the user and token. If not, throw an error.
"""
try:
payload = jwt.decode(token, settings.SECRET_KEY)
except:
msg = 'Invalid authentication. Could not decode token.'
raise exceptions.AuthenticationFailed(msg)
try:
user = User.objects.get(pk=payload['id'])
except User.DoesNotExist:
msg = 'No user matching this token was found.'
raise exceptions.AuthenticationFailed(msg)
if not user.is_active:
msg = 'This user has been deactivated.'
raise exceptions.AuthenticationFailed(msg)
return (user, token)
示例5: test_hawk_post_wrong_sig
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def test_hawk_post_wrong_sig(self):
post_data = 'one=1&two=2&three=3'
content_type = 'application/x-www-form-urlencoded'
method = 'POST'
sender = self._sender(content=post_data,
content_type=content_type,
method=method)
# This should fail the signature check.
post_data = '{0}&TAMPERED_WITH=true'.format(post_data)
req = self._request(sender,
content_type=content_type,
data=post_data,
method=method)
self.assertRaisesRegexp(AuthenticationFailed,
'^Hawk authentication failed$',
lambda: self.auth.authenticate(req))
self.assert_log_regex('warning', '^access denied: MisComputedContentHash: ')
示例6: authenticate_credentials
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def authenticate_credentials(self, key):
model = self.get_model()
try:
token = model.objects.select_related("user").get(key=key)
except model.DoesNotExist:
raise exceptions.AuthenticationFailed("Invalid token")
# Enforce the Token's expiration time
if token.is_expired:
raise exceptions.AuthenticationFailed("Token expired")
if not token.user.is_active:
raise exceptions.AuthenticationFailed("User inactive")
return token.user, token
示例7: test_authentication_new_user
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def test_authentication_new_user(
db, rf, requests_mock, settings, create_user, username, expected_count
):
settings.OIDC_CREATE_USER = create_user
user_model = get_user_model()
assert user_model.objects.filter(username=username).count() == 0
userinfo = {"preferred_username": username}
requests_mock.get(settings.OIDC_OP_USER_ENDPOINT, text=json.dumps(userinfo))
request = rf.get("/openid", HTTP_AUTHORIZATION="Bearer Token")
try:
user, _ = OIDCAuthentication().authenticate(request)
except AuthenticationFailed:
assert not create_user
else:
assert user.username == username
assert user_model.objects.count() == expected_count
示例8: get_access_token
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [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]
示例9: authenticate
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def authenticate(self, request):
"""
Returns a two-tuple of `User` and token if a valid signature has been
supplied using JWT-based authentication. Otherwise returns `None`.
"""
jwt_value = self.get_jwt_value(request)
if jwt_value is None:
return None
try:
payload = jwt_decode_handler(jwt_value)
except jwt.ExpiredSignature:
msg = 'Token过期'
raise exceptions.AuthenticationFailed({"message": msg,"errorCode":1,"data":{}})
except jwt.DecodeError:
msg = 'Token不合法'
raise exceptions.AuthenticationFailed({"message": msg,"errorCode":1,"data":{}})
except jwt.InvalidTokenError:
raise exceptions.AuthenticationFailed()
user = self.authenticate_credentials(payload)
return user, jwt_value
示例10: token
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def token(self, *arg, **kwargs):
"""
Download the token belonging to a restricted mail. This token has to be attached to
the restricted mail for authentication.
"""
instance = get_object_or_404(RestrictedMail.objects.all(), id=kwargs["pk"])
auth = self.request.GET.get("auth")
if not instance.token_verify_query_param(auth):
raise exceptions.AuthenticationFailed
if not instance.token:
raise exceptions.NotFound
file_content = f"{RESTRICTED_TOKEN_PREFIX}{instance.token}"
response = HttpResponse(file_content)
response["Content-Disposition"] = 'attachment; filename="token"'
return response
示例11: authenticate_credentials
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def authenticate_credentials(self, key):
user, token = super(TokenAuthentication, self).authenticate_credentials(key)
try:
kc_user = KeycloakModel.objects.get(user = user)
# DP ???: Should a user's roles be synced?
if self.user_exist(kc_user.UID):
return (user, token) # regular return for authenticate_credentials()
else:
# Disable the user in Django to shortcut the Keycloak lookup
user.is_active = False
user.save()
raise exceptions.AuthenticationFailed(_('User inactive or deleted.'))
except KeycloakModel.DoesNotExist:
# Regular Django user account
return (user, token)
示例12: authenticate_credentials
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def authenticate_credentials(self, payload):
"""
Returns an active user that matches the payload's user id and email.
"""
if getattr(settings, 'JWT_AUTH_DISABLED', False):
return AnonymousUser()
User = get_user_model()
username = payload.get(getattr(settings, 'JWT_ID_ATTRIBUTE'))
if not username:
msg = 'Invalid payload.'
raise exceptions.AuthenticationFailed(msg)
try:
kwargs = {
getattr(settings, 'JWT_ID_ATTRIBUTE'): username
}
user = User.objects.get(**kwargs)
except User.DoesNotExist:
msg = 'Invalid signature.'
raise exceptions.AuthenticationFailed(msg)
if not user.is_active:
msg = 'User account is disabled.'
raise exceptions.AuthenticationFailed(msg)
return user
示例13: authenticate_credentials
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def authenticate_credentials(self, access_token):
try:
user_profile = self.fetch_oidc_user_profile(access_token)
except (requests.exceptions.RequestException, OIDCEndpointRequestError):
raise exceptions.AuthenticationFailed("Unable to verify bearer token.")
email = user_profile.get("email", "").strip().lower()
if not email:
# This would happen if someone has requested an access token
# from their OIDC provider *without the 'email' scope*.
raise exceptions.AuthenticationFailed("User profile lacks 'email' scope.")
# Turn this email into a Django User instance.
user, _ = get_user_model().objects.get_or_create(
username=email[:150], defaults={"email": email}
)
# Sync user data with OIDC profile
dirty = False
family_name = user_profile.get("family_name", "").strip()
given_name = user_profile.get("given_name", "").strip()
if given_name and given_name != user.first_name:
user.first_name = given_name
dirty = True
if family_name and family_name != user.last_name:
user.last_name = family_name
dirty = True
if user.email != email:
user.email = email
dirty = True
if dirty:
user.save()
if not user.is_active:
raise exceptions.AuthenticationFailed("User inactive.")
return (user, access_token)
示例14: fetch_oidc_user_profile
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def fetch_oidc_user_profile(self, access_token):
token_hash = sha256(access_token.encode()).hexdigest()
cache_key = f"oidc-profile-{token_hash}"
cached_response = cache.get(cache_key)
if cached_response:
return cached_response
url = settings.OIDC_USER_ENDPOINT
response = requests.get(url, headers={"Authorization": f"Bearer {access_token}"})
if response.status_code == 200:
now = int(time.mktime(datetime.utcnow().timetuple()))
resets_in = int(response.headers.get("X-RateLimit-Reset", 0)) - now
cache_seconds = DEFAULT_PROFILE_CACHE_SECONDS if resets_in < 1 else resets_in
profile = response.json()
cache.set(cache_key, profile, cache_seconds)
return profile
elif response.status_code == 401:
# The OIDC provider did not like the access token.
raise exceptions.AuthenticationFailed("Unauthorized access token")
elif response.status_code >= 500:
raise requests.exceptions.RequestException(f"{response.status_code} on {url}")
# This could happen if, for some reason, we're not configured to be
# allowed to talk to the OIDC endpoint.
raise OIDCEndpointRequestError(response.status_code)
示例15: test_cannot_authenticate_a_user_if_the_auth_header_does_not_contain_the_access_token
# 需要导入模块: from rest_framework import exceptions [as 别名]
# 或者: from rest_framework.exceptions import AuthenticationFailed [as 别名]
def test_cannot_authenticate_a_user_if_the_auth_header_does_not_contain_the_access_token(self):
rf = APIRequestFactory()
request = rf.get('/', HTTP_AUTHORIZATION='Bearer')
SessionMiddleware().process_request(request)
request.session.save()
backend = BearerTokenAuthentication()
with pytest.raises(AuthenticationFailed):
backend.authenticate(request)