本文整理汇总了Python中rest_framework_jwt.utils.jwt_decode_handler函数的典型用法代码示例。如果您正苦于以下问题:Python jwt_decode_handler函数的具体用法?Python jwt_decode_handler怎么用?Python jwt_decode_handler使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了jwt_decode_handler函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_refresh_jwt
def test_refresh_jwt(self):
"""
Test getting a refreshed token from original token works
No date/time modifications are neccessary because it is assumed
that this operation will take less than 300 seconds.
"""
client = APIClient(enforce_csrf_checks=True)
orig_token = self.get_token()
orig_token_decoded = utils.jwt_decode_handler(orig_token)
expected_orig_iat = timegm(datetime.utcnow().utctimetuple())
# Make sure 'orig_iat' exists and is the current time (give some slack)
orig_iat = orig_token_decoded['orig_iat']
self.assertLessEqual(orig_iat - expected_orig_iat, 1)
time.sleep(1)
# Now try to get a refreshed token
response = client.post('/auth-token-refresh/', {'token': orig_token},
format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
new_token = response.data['token']
new_token_decoded = utils.jwt_decode_handler(new_token)
# Make sure 'orig_iat' on the new token is same as original
self.assertEquals(new_token_decoded['orig_iat'], orig_iat)
self.assertGreater(new_token_decoded['exp'], orig_token_decoded['exp'])
开发者ID:DjangoBD,项目名称:django-rest-framework-jwt,代码行数:30,代码来源:test_views.py
示例2: test_refresh_jwt
def test_refresh_jwt(self):
"""
Test getting a refreshed token from original token works
"""
client = APIClient(enforce_csrf_checks=True)
with freeze_time('2015-01-01 00:00:01'):
orig_token = self.get_token()
orig_token_decoded = utils.jwt_decode_handler(orig_token)
expected_orig_iat = timegm(datetime.utcnow().utctimetuple())
# Make sure 'orig_iat' exists and is the current time (give some slack)
orig_iat = orig_token_decoded['orig_iat']
self.assertLessEqual(orig_iat - expected_orig_iat, 1)
with freeze_time('2015-01-01 00:00:03'):
# Now try to get a refreshed token
response = client.post('/auth-token-refresh/', {'token': orig_token},
format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
new_token = response.data['token']
new_token_decoded = utils.jwt_decode_handler(new_token)
# Make sure 'orig_iat' on the new token is same as original
self.assertEquals(new_token_decoded['orig_iat'], orig_iat)
self.assertGreater(new_token_decoded['exp'], orig_token_decoded['exp'])
开发者ID:ArunRSclarion,项目名称:django-rest-framework-jwt,代码行数:29,代码来源:test_views.py
示例3: test_jwt_refresh
def test_jwt_refresh(self):
"""
This test verifies that an existing user can refresh their JWT token
:return:
"""
# NOTE: Only unexpired tokens can be refreshed.
login_credentials = {
'username': self.username,
'password': self.password
}
response = self.api_client.post('/auth/api-token-auth/', login_credentials, format='json')
jwt_token = response.data['token']
decoded_payload = utils.jwt_decode_handler(jwt_token)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsNotNone(jwt_token)
decoded_payload = utils.jwt_decode_handler(jwt_token)
refresh_payload = {
'token': jwt_token
}
response = self.api_client.post('/auth/api-token-refresh/', refresh_payload, format='json')
new_jwt_token = response.data['token']
new_decoded_payload = utils.jwt_decode_handler(jwt_token)
self.assertEqual(decoded_payload['orig_iat'], new_decoded_payload['orig_iat'])
self.assertEqual(decoded_payload['exp'], new_decoded_payload['exp'])
开发者ID:alexolivas,项目名称:django-rest-skeleton,代码行数:26,代码来源:tests.py
示例4: test_jwt_decode_verify_exp
def test_jwt_decode_verify_exp(self):
api_settings.JWT_VERIFY_EXPIRATION = False
payload = utils.jwt_payload_handler(self.user)
payload['exp'] = 1
token = utils.jwt_encode_handler(payload)
utils.jwt_decode_handler(token)
api_settings.JWT_VERIFY_EXPIRATION = True
开发者ID:ArunRSclarion,项目名称:django-rest-framework-jwt,代码行数:9,代码来源:test_utils.py
示例5: authenticate
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:
raise exceptions.NotAuthenticated()
try:
payload = jwt_decode_handler(jwt_value)
except jwt.ExpiredSignature: # pragma: no cover
msg = 'Signature has expired.'
raise exceptions.AuthenticationFailed(msg)
except jwt.DecodeError: # pragma: no cover
msg = 'Error decoding signature.'
raise exceptions.AuthenticationFailed(msg)
except jwt.InvalidTokenError: # pragma: no cover
raise exceptions.AuthenticationFailed()
except Exception as ex:
raise exceptions.AuthenticationFailed(ex.message)
user = User(**payload)
return user, jwt_value
开发者ID:ZeroCater,项目名称:zc_common,代码行数:25,代码来源:authentication.py
示例6: test_login
def test_login(self):
"""Test the login endpoint"""
user = get_user_model().objects.create_user(
username='testuser',
email='[email protected]',
password='password',
)
data = dict(
username=user.username,
email=user.email,
password='password',
)
response = self.client.post(
'/api/v1/auth/login',
data=data,
format='json',
)
self.assertEqual(response.status_code, status.HTTP_200_OK,
'Got error: {}'.format(response.content))
decoded_payload = utils.jwt_decode_handler(response.data['token'])
self.assertEqual(decoded_payload['username'], user.username)
self.assertEqual(decoded_payload['email'], user.email)
self.assertEqual(decoded_payload['user_id'], user.pk)
开发者ID:jtmitchell,项目名称:mymovie,代码行数:28,代码来源:test_api.py
示例7: post
def post(self, request):
'''
a known issue now...
a segment fault happens if you login and then logout and login again..
'''
serializer = testSignin.serializer_class(data=request.DATA)
if serializer.is_valid():
payload = utils.jwt_decode_handler(serializer.object['token'])
user = self.jwt.authenticate_credentials(payload)
# below is a tric for authenticate..
# due to the authentication in django -- it need username and password,
# however, decode of jwt doesn't contain password.
user.backend = 'django.contrib.auth.backends.ModelBackend'
# user = authenticate(username=user, nopass=True)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/home/')
else:
raise Exception('user not active')
else:
raise Exception('not valid user')
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
开发者ID:rolymobile,项目名称:bitcoin-zoo,代码行数:28,代码来源:views.py
示例8: token_payload
def token_payload(token, user=None, request=None):
decoded = jwt_decode_handler(token)
return {
'token': token,
'orig_iat': decoded.get('orig_iat'),
'user': ReferenceUserSerializer(user, context={'request': request}).data
}
开发者ID:eranimo,项目名称:podmon-api,代码行数:7,代码来源:auth_view.py
示例9: testuserJwtLogin
def testuserJwtLogin(self):
"""Authenticate a test user, and prepare JWT token based authentification.
POST user credentials to the JWT login url using the default
:class:`django.test.TestCase.Client` client.
Capture the JWT token from the request response,
store it in :attr:`testuserdata['jwtToken']`,
and setup the method :meth:`api_client()` of this instance
to authenticate using this JWT token.
Returns:
The HTTP status code.
"""
# https://docs.djangoproject.com/en/1.8/releases/1.8/:
# Passing a dotted path to reverse() and url
#
# Reversing URLs by Python path is an expensive operation as it
# causes the path being reversed to be imported.
# This behavior has also resulted in a security issue.
# Use named URL patterns for reversing instead.
#
# See also:
# https://docs.djangoproject.com/en/1.8/topics/auth/passwords/
# url = reverse('rest_framework_jwt.views.obtain_jwt_token')
url = reverse('jwt_token_auth')
response = self.client.post(url, self.data, format='json')
jwtToken = response.data['token']
self.testuserdata['jwtToken'] = jwtToken
self.testuserdata['decodedJwtToken'] = jwt_decode_handler(jwtToken)
authHeader = 'JWT ' + self.testuserdata['jwtToken']
self.api_client.credentials(HTTP_AUTHORIZATION=authHeader)
return response.status_code
开发者ID:peterdv,项目名称:pyreststore,代码行数:35,代码来源:baseTestCase.py
示例10: post
def post(self, request, model, app_label, object_id, field_name, score, **kwargs):
user = utils.jwt_decode_handler(request.auth)['user_id']
user = CustomUser.objects.get(id=user)
addRating = AddRatingFromModel()
return addRating(request, model, app_label, object_id, field_name, score, user)
开发者ID:keubs,项目名称:respond-react-api,代码行数:8,代码来源:api.py
示例11: grant
def grant(request):
authKey = request.data.get('authKey')
try:
jwt_decode_handler(authKey)
authenticated = True
except:
authenticated = False
channels = request.data.get('channels')
channels += [channel + '-pnpres' for channel in channels]
channels = ','.join(channels)
try:
pubnub.grant(channel=channels, auth_key=authKey, read=True, write=authenticated, ttl=604800)
return Response({'message': 'Granted!'})
except:
return Response({'message': 'Failed!'}, status=status.HTTP_401_UNAUTHORIZED)
开发者ID:genxstylez,项目名称:mooq,代码行数:17,代码来源:views.py
示例12: test_create
def test_create(self):
serializer = JSONWebTokenSerializer(data=self.data)
is_valid = serializer.is_valid()
token = serializer.object['token']
decoded_payload = utils.jwt_decode_handler(token)
self.assertTrue(is_valid)
self.assertEqual(decoded_payload['username'], self.username)
开发者ID:Mondego,项目名称:pyreco,代码行数:9,代码来源:allPythonContent.py
示例13: test_jwt_login_json
def test_jwt_login_json(self):
"""
Ensure JWT login view using JSON POST works.
"""
client = APIClient(enforce_csrf_checks=True)
response = client.post('/auth-token/', self.data, format='json')
self.assertEqual(response.status_code, status.HTTP_200_OK)
decoded_payload = utils.jwt_decode_handler(response.data['token'])
self.assertEqual(decoded_payload['user_id'], str(self.user.id))
开发者ID:DjangoBD,项目名称:django-rest-framework-jwt,代码行数:11,代码来源:test_views.py
示例14: test_jwt_login_form
def test_jwt_login_form(self):
"""
Ensure JWT login view using form POST works.
"""
client = APIClient(enforce_csrf_checks=True)
response = client.post("/auth-token/", self.data)
decoded_payload = utils.jwt_decode_handler(response.data["token"])
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(decoded_payload["username"], self.username)
开发者ID:jmacul2,项目名称:django-rest-framework-jwt,代码行数:12,代码来源:test_views.py
示例15: get
def get(self, request, format=None, pk=None):
if request.user.is_authenticated():
user_id = request.user.pk
else:
try:
token = request.META['HTTP_AUTHORIZATION'][3:]
decode = jwt_decode_handler(token)
user_id = decode['user_id']
except KeyError:
return Response({"detail": "Authorization Token not provided or user Not Authenticated"}, status=401)
playlists = PlayLists.objects.filter(user__pk=user_id)
serializer = PlaylistSerializer(playlists, many=True)
return Response(serializer.data)
开发者ID:beren5000,项目名称:musicPlayList,代码行数:13,代码来源:views.py
示例16: test_can_login_and_get_token
def test_can_login_and_get_token(self):
(http_status, response_json) = self._post(
'/api-token-auth/',
{'username': 'user_001',
'password': 'correct_password'})
assert_equal(200, http_status)
assert_in('token', response_json)
decoded_token = jwt_decode_handler(response_json['token'])
assert_equal({
'email': '',
'exp': 1420156800,
'user_id': 1,
'username': 'user_001'},
decoded_token)
开发者ID:paulfurley,项目名称:calories-project,代码行数:15,代码来源:test_login.py
示例17: test_jwt_auth
def test_jwt_auth(self):
"""
This test verifies that an existing user can get an auth token using a JSON post
:return:
"""
login_credentials = {
'username': self.username,
'password': self.password
}
response = self.api_client.post('/auth/api-token-auth/', login_credentials, format='json')
jwt_token = response.data['token']
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsNotNone(jwt_token)
decoded_payload = utils.jwt_decode_handler(jwt_token)
self.assertEqual(decoded_payload['username'], self.username)
self.assertEqual(decoded_payload['email'], self.email)
开发者ID:alexolivas,项目名称:django-rest-skeleton,代码行数:17,代码来源:tests.py
示例18: test_jwt_login_with_expired_token
def test_jwt_login_with_expired_token(self):
"""
Ensure JWT login view works even if expired token is provided
"""
payload = utils.jwt_payload_handler(self.user)
payload['exp'] = 1
token = utils.jwt_encode_handler(payload)
auth = 'JWT {0}'.format(token)
client = APIClient(enforce_csrf_checks=True)
response = client.post(
'/auth-token/', self.data,
HTTP_AUTHORIZATION=auth, format='json')
decoded_payload = utils.jwt_decode_handler(response.data['token'])
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(decoded_payload['username'], self.username)
开发者ID:DjangoBD,项目名称:django-rest-framework-jwt,代码行数:18,代码来源:test_views.py
示例19: update
def update(self, request, pk=None):
if request.auth is not None:
permission_classes = (IsAuthenticated,)
authentication_classes = (JSONWebTokenAuthentication,)
user_id = utils.jwt_decode_handler(request.auth)
user_id = user_id["user_id"]
if user_id == int(pk):
customuser = CustomUser.objects.get(pk=pk)
serializer = CustomUserSerializer(customuser, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
else:
return Response(status=status.HTTP_401_UNAUTHORIZED)
else:
return Response(status=status.HTTP_401_UNAUTHORIZED)
开发者ID:keubs,项目名称:untitled,代码行数:19,代码来源:api.py
示例20: put
def put(self, request, format=None, pk=None):
if request.user.is_authenticated():
user_id = request.user.pk
else:
try:
token = request.META['HTTP_AUTHORIZATION'][3:]
decode = jwt_decode_handler(token)
user_id = decode['user_id']
except KeyError:
return Response({"detail": "Authorization Token not provided or user Not Authenticated"}, status=401)
user = User.objects.get(pk=user_id);
name = request.POST['name']
description = request.POST['description']
songs = request.POST.getlist('songs[]')
songs = Song.objects.filter(pk__in=songs)
playlist = PlayLists(user=user, name=name, description=description)
playlist.save()
playlist.songs.add(*songs)
playlist.save()
return Response({"inserted": playlist.pk}, status=200)
开发者ID:beren5000,项目名称:musicPlayList,代码行数:20,代码来源:views.py
注:本文中的rest_framework_jwt.utils.jwt_decode_handler函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论