10 examples of 'djangorestframework simplejwt' in Python

Every line of 'djangorestframework simplejwt' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
75def authenticate(self, request):
76 """
77 Returns a two-tuple of `User` and token if a valid signature has been
78 supplied using JWT-based authentication. Otherwise returns `None`.
79 """
80 # update request authentication info
81
82 jwt_value = self.get_jwt_value(request)
83 if jwt_value is None:
84 msg = _('未提供验证信息')
85 raise AuthenticationInfoHasExpiredError(msg)
86 # if have SSO login modules
87 if settings.MODULES.get('SSO_LOGIN', None):
88 sso_user_id = request.COOKIES.get('uid')
89 sso_user_token = jwt_value
90
91 if not sso_user_id or not sso_user_token:
92 msg = _("Cookie信息里面应该包含Token和用户uid")
93 raise AuthenticationInfoHasExpiredError(msg)
94
95 if sso_user_id == 'null' or sso_user_token == 'null':
96 msg = _("Cookie信息里面应该包含Token和用户uid")
97 raise AuthenticationInfoHasExpiredError(msg)
98 try:
99 user = Users.objects.get(sso_user_id=sso_user_id)
100 return user, None
101 except Users.DoesNotExist:
102 msg = _('认证信息错误')
103 raise AuthenticationInfoHasExpiredError(msg)
104 else:
105 try:
106 payload = jwt_decode_handler(jwt_value)
107 except jwt.ExpiredSignature:
108 # msg = _('Signature has expired.')
109 msg = _('认证信息已过期')
110 raise AuthenticationInfoHasExpiredError(msg)
111 except jwt.DecodeError:
112 # msg = _('Error decoding signature.')
113 msg = _('认证信息错误')
114 # raise exceptions.AuthenticationFailed(msg)
115 raise AuthenticationInfoHasExpiredError(msg)
116 except jwt.InvalidTokenError:
117 msg = _('认证信息错误,请求Token不合法')
118 # raise exceptions.AuthenticationFailed(msg)
119 raise AuthenticationInfoHasExpiredError(msg)
120
121 user = self.authenticate_credentials(payload)
122 return user, jwt_value
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

87def authenticate(self, request): # pylint: disable=no-self-use
88 """Method required."""
89 token = get_token_from_request(request)
90 payload = get_payload_from_token(token)
91 user_id = get_user_id_from_payload(payload)
92 return get_user(user_id), token
121def _get_jwt_value(self, request):
122 auth = get_authorization_header(request).split()
123 auth_header_prefix = getattr(settings, 'JWT_AUTH_HEADER_PREFIX', 'JWT')
124
125 if not auth:
126 if getattr(settings, 'JWT_AUTH_COOKIE', None):
127 return request.COOKIES.get(settings.JWT_AUTH_COOKIE)
128 return None
129
130 if smart_str(auth[0]) != auth_header_prefix:
131 return None
132
133 if len(auth) == 1:
134 msg = 'Invalid Authorization header. No credentials provided.'
135 raise exceptions.AuthenticationFailed(msg)
136 elif len(auth) > 2:
137 msg = ('Invalid Authorization header. Credentials string '
138 'should not contain spaces.')
139 raise exceptions.AuthenticationFailed(msg)
140
141 jwt_value = auth[1]
142 if type(jwt_value) is bytes:
143 jwt_value = jwt_value.decode('utf-8')
144 return jwt_value
232def get_jwt_value(self, request):
233 """
234 Get the JWT token from the authorization header.
235
236 Copied from upstream's implementation but uses a hardcoded 'JWT'
237 prefix in order to be isolated from JWT_AUTH_HEADER_PREFIX setting
238 which is used for the non-api key auth above.
239 """
240 auth = get_authorization_header(request).split()
241 auth_header_prefix = 'jwt' # JWT_AUTH_HEADER_PREFIX.lower()
242
243 if not auth or smart_text(auth[0].lower()) != auth_header_prefix:
244 return None
245
246 if len(auth) == 1:
247 msg = ugettext('Invalid Authorization header. '
248 'No credentials provided.')
249 raise exceptions.AuthenticationFailed(msg)
250 elif len(auth) > 2:
251 msg = ugettext('Invalid Authorization header. Credentials string '
252 'should not contain spaces.')
253 raise exceptions.AuthenticationFailed(msg)
254
255 return auth[1]
9def handle_user_login(self, request, serializer, *args, **kwargs):
10 token = RefreshToken.for_user(serializer.user)
11 return Response(
12 {
13 'refresh': str(token),
14 'access': str(token.access_token)
15 }
16 )
21def post(self, request, *args, **kwargs):
22 serializer = self.get_serializer(data=request.data)
23
24 if serializer.is_valid():
25 user = serializer.object.get('user') or request.user
26 token = serializer.object.get('token')
27 response_data = jwt_response_payload_handler(token, user, request)
28 response_data['is_student'] = will_it_raise_exception(lambda: user.student)
29 response_data['is_organization'] = will_it_raise_exception(lambda: user.organization)
30 response = Response(response_data)
31 if api_settings.JWT_AUTH_COOKIE:
32 expiration = (datetime.utcnow() +
33 api_settings.JWT_EXPIRATION_DELTA)
34 response.set_cookie(api_settings.JWT_AUTH_COOKIE,
35 token,
36 expires=expiration,
37 httponly=True)
38 return response
39
40 return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
41@cached_property
42def pk(self):
43 return self.id
21def get_serializer_context(self):
22 """
23 Extra context provided to the serializer class.
24 """
25 return {
26 'request': self.request,
27 'view': self,
28 }
91def test_login_returns_serialized_token_and_username_field(self):
92
93 with override_settings(REST_KNOX=user_serializer_knox):
94 reload_module(views)
95 self.assertEqual(AuthToken.objects.count(), 0)
96 url = reverse('knox_login')
97 self.client.credentials(
98 HTTP_AUTHORIZATION=get_basic_auth_header(self.username, self.password)
99 )
100 response = self.client.post(url, {}, format='json')
101 self.assertEqual(user_serializer_knox["USER_SERIALIZER"], UserSerializer)
102 reload_module(views)
103 self.assertEqual(response.status_code, 200)
104 self.assertIn('token', response.data)
105 username_field = self.user.USERNAME_FIELD
106 self.assertIn('user', response.data)
107 self.assertIn(username_field, response.data['user'])
18def decode(self, token):
19 """
20 Performs a validation of the given token and returns its payload
21 dictionary.
22
23 Raises a `TokenBackendError` if the token is malformed, if its
24 signature check fails, or if its 'exp' claim indicates it has expired.
25 """
26 try:
27 return jwt.decode(
28 token, self.secret_key, algorithms=[self.algorithm], verify=True
29 )
30 except jwt.InvalidTokenError:
31 raise TokenError("Token is invalid or expired")

Related snippets