Python rest_framework.exceptions.AuthenticationFailed() Examples
The following are 30
code examples of rest_framework.exceptions.AuthenticationFailed().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
rest_framework.exceptions
, or try the search function
.
Example #1
Source File: authentication.py From boss with Apache License 2.0 | 6 votes |
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)
Example #2
Source File: authentication.py From django-oauth-toolkit-jwt with MIT License | 6 votes |
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
Example #3
Source File: views.py From controller with MIT License | 6 votes |
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'})
Example #4
Source File: authentication.py From django-oauth-toolkit-jwt with MIT License | 6 votes |
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)
Example #5
Source File: backends.py From aws-workshop with MIT License | 6 votes |
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)
Example #6
Source File: test_authentication.py From hawkrest with BSD 3-Clause "New" or "Revised" License | 6 votes |
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: ')
Example #7
Source File: api.py From peering-manager with Apache License 2.0 | 6 votes |
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
Example #8
Source File: test_authentication.py From timed-backend with GNU Affero General Public License v3.0 | 6 votes |
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
Example #9
Source File: drf.py From mozilla-django-oidc with Mozilla Public License 2.0 | 6 votes |
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]
Example #10
Source File: jwtAuth.py From django-RESTfulAPI with MIT License | 6 votes |
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
Example #11
Source File: views.py From lego with MIT License | 6 votes |
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
Example #12
Source File: views.py From controller with MIT License | 6 votes |
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'})
Example #13
Source File: hook.py From permabots with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_recipient(self, id, hook, user): try: obj = self.model.objects.get(id=id, hook=hook) if self._user(obj) != user: raise exceptions.AuthenticationFailed() return obj except self.model.DoesNotExist: raise Http404
Example #14
Source File: handler.py From permabots with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_object(self, id, handler, user): try: obj = self.model.objects.get(id=id, bot=handler.bot) if self._user(handler) != user: raise exceptions.AuthenticationFailed() return obj except self.model.DoesNotExist: raise Http404
Example #15
Source File: test_serializers.py From django-rest-framework-simplejwt with MIT License | 5 votes |
def test_it_should_not_validate_if_user_not_found(self): s = TokenObtainSerializer(context=MagicMock(), data={ TokenObtainSerializer.username_field: 'missing', 'password': 'pass', }) with self.assertRaises(drf_exceptions.AuthenticationFailed): s.is_valid()
Example #16
Source File: serializers.py From django-rest-framework-simplejwt with MIT License | 5 votes |
def validate(self, attrs): authenticate_kwargs = { self.username_field: attrs[self.username_field], 'password': attrs['password'], } try: authenticate_kwargs['request'] = self.context['request'] except KeyError: pass self.user = authenticate(**authenticate_kwargs) # Prior to Django 1.10, inactive users could be authenticated with the # default `ModelBackend`. As of Django 1.10, the `ModelBackend` # prevents inactive users from authenticating. App designers can still # allow inactive users to authenticate by opting for the new # `AllowAllUsersModelBackend`. However, we explicitly prevent inactive # users from authenticating to enforce a reasonable policy and provide # sensible backwards compatibility with older Django versions. if self.user is None or not self.user.is_active: raise exceptions.AuthenticationFailed( self.error_messages['no_active_account'], 'no_active_account', ) return {}
Example #17
Source File: hook.py From permabots with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_hook(self, id, bot, user): try: hook = Hook.objects.get(id=id, bot=bot) if hook.bot.owner != user: raise exceptions.AuthenticationFailed() return hook except Hook.DoesNotExist: raise Http404
Example #18
Source File: user.py From rssant with BSD 3-Clause "New" or "Revised" License | 5 votes |
def user_login( request, account: T.str.optional, password: T.str.optional, ) -> UserSchema: if not (account or password): if request.user.is_authenticated: if not request.user.is_active: return Response(status=403) return serialize_user(request.user) return Response(status=401) error_message = {'message': '用户名或密码错误'} if '@' in account: tmp_user = User.objects.filter(email=account).first() if tmp_user: username = tmp_user.username else: return Response(error_message, status=401) else: username = account try: user = django_auth.authenticate(username=username, password=password) except AuthenticationFailed: return Response(error_message, status=401) if not user or not user.is_authenticated: return Response(status=401) if not user.is_active: return Response(status=403) django_auth.login(request, user=user) return serialize_user(request.user)
Example #19
Source File: authentication.py From django-oauth-toolkit-jwt with MIT License | 5 votes |
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
Example #20
Source File: test_authentication.py From tfrs with Apache License 2.0 | 5 votes |
def test_jwt_no_token(self): """Test no token""" request = self.factory.get('/') with self.assertRaises(exceptions.AuthenticationFailed): _user, _auth = self.userauth.authenticate(request)
Example #21
Source File: test_authentication.py From tfrs with Apache License 2.0 | 5 votes |
def test_jwt_invalid_token(self): """Test invalid token""" request = self.factory.get('/') request.META = { 'HTTP_AUTHORIZATION': 'garbage' } with self.assertRaises(exceptions.AuthenticationFailed): _user, _auth = self.userauth.authenticate(request)
Example #22
Source File: views.py From django-freeradius with GNU General Public License v3.0 | 5 votes |
def authenticate(self, request): if request.META.get('HTTP_AUTHORIZATION', False): headers = request.META.get('HTTP_AUTHORIZATION').split(',') for header in headers: try: token = header.split(' ')[1] except IndexError: raise ParseError('Invalid token') if token == app_settings.API_TOKEN: return (AnonymousUser(), None) if request.GET.get('token') == app_settings.API_TOKEN: return (AnonymousUser(), None) raise AuthenticationFailed('Token authentication failed')
Example #23
Source File: auth.py From lego with MIT License | 5 votes |
def get_jwt_value(self, scope): if scope.get("type") != "websocket": raise exceptions.AuthenticationFailed("Websocket connection i required") query_string = (scope.get("query_string", b"")).decode() qs = parse_qs(query_string) jwt_param = qs.get("jwt", []) if len(jwt_param) != 1: raise exceptions.AuthenticationFailed("Invalid JWT query param") return jwt_param[0]
Example #24
Source File: authentication.py From lego with MIT License | 5 votes |
def authenticate_credentials(self, key): try: survey = Survey.objects.get(token=key) except Survey.DoesNotExist: raise exceptions.AuthenticationFailed("Invalid token") return None, survey
Example #25
Source File: jwtAuth.py From django-RESTfulAPI with MIT License | 5 votes |
def get_jwt_value(self, request): auth = request.META.get('HTTP_AUTHORIZATION', '').split() auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower() if not auth or auth[0].lower() != auth_header_prefix: return None if len(auth) == 1: msg = 'Invalid Authorization header. No credentials provided.' raise exceptions.AuthenticationFailed({"message": "消息头不合法","errorCode":1,"data":{}}) elif len(auth) > 2: msg = 'Invalid Authorization header. Credentials string should not contain spaces.' raise exceptions.AuthenticationFailed({"message": "消息头不合法","errorCode":1,"data":{}}) return auth[1]
Example #26
Source File: jwtAuth.py From django-RESTfulAPI with MIT License | 5 votes |
def authenticate_credentials(self, payload): id = jwt_get_user_id_from_payload_handler(payload) if not id: raise exceptions.AuthenticationFailed({"message": "没有该用户","errorCode":1,"data":{}}) try: user = User.objects.filter(id=id).first() except User.DoesNotExist: raise exceptions.AuthenticationFailed({"message": "没有该用户","errorCode":1,"data":{}}) return user
Example #27
Source File: authentication.py From normandy with Mozilla Public License 2.0 | 5 votes |
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)
Example #28
Source File: test_authentication.py From django-rest-framework-expiring-tokens with BSD 2-Clause "Simplified" License | 5 votes |
def test_expired_token(self): """Check that an expired token cannot authenticate.""" # Crude, but necessary as auto_now_add field can't be changed. with self.settings(EXPIRING_TOKEN_LIFESPAN=timedelta(milliseconds=1)): sleep(0.001) try: self.test_instance.authenticate_credentials(self.key) except AuthenticationFailed as e: self.assertEqual(e.__str__(), 'Token has expired') else: self.fail("AuthenticationFailed not raised.")
Example #29
Source File: authentication.py From django-oidc-rp with MIT License | 5 votes |
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
Example #30
Source File: test_serializers.py From django-rest-framework-simplejwt with MIT License | 5 votes |
def test_it_should_raise_if_user_not_active(self): self.user.is_active = False self.user.save() s = TokenObtainSerializer(context=MagicMock(), data={ TokenObtainSerializer.username_field: self.username, 'password': self.password, }) with self.assertRaises(drf_exceptions.AuthenticationFailed): s.is_valid()