Why i'm unable to autherize in my django app? - django

i'm testing my api. if the user is authenticated then he can able to see the projects otherwise return not authorizated response. I'm passing my jwt token in header but still unable to autherize...?
class ListProjectAPIView(generics.ListAPIView):
"""This endpoint list all of the available Projects from the database"""
permission_classes = [IsAuthenticated,]
queryset = Project.objects.get_all()
serializer_class = serializers.ProjectSerializer

Related

DRF django-rest-framework-simplejwt JWTAuthentication not working

Ideally using django-rest-framework-simplejwt and the authentication class JWTAuthentication, the API should give 403 when I pass the token incorrectly.
Instead, when I am making my API request it is executing successfully even without the Authentication token.
This is a dummy API, my concern is the Authentication should work.
My code looks like this:
class ViewSet(viewsets.ModelViewSet):
queryset = get_user_model().objects.all()
serializer_class = SomeSerializer
http_method_names = ("post", "patch")
authentication_classes = (JWTAuthentication,)
When I debug I see that it is executing JWTAuthentication, which in turn returns None.
Which is expected since I am not passing the Token in the header.
def authenticate(self, request):
header = self.get_header(request)
if header is None:
return None
Now I think the View should give Permission Denied, which is not happening.
Not able to understand what is missing here.
If you pass incorrect token, it'll return 401 status response.
But if you don't put authorization header on your request, django will not return 401 response and behave with request as AnonymousUser request.
If you want only authenticated users have access to your ViewSet, you should put permission_classes = [IsAuthenticated,] in your ViewSet.
IsAuthenticated permission class can be imported from rest_framework.permissions

Django restful API - get user id with token

How to obtain User ID from Django API having authentication token?
Basically, I want to send authentication token and get back User id.
I have tried this solution: How can I return user ID with token in Django?
but it is returning token with provided username and password, which is not what I want.
#myapp/views.py
class UserIdViewSet(viewsets.ModelViewSet):
serializer_class = UserSerializer
def get_queryset(self):
return User.objects.filter(id=self.request.user.id)
#myapp/urls.py
router.register(r'api/user-id', userviews.UserIdViewSet, base_name="UserId")
sort out the problem. Basically created View set and sort this out against current user.
What type of authentication you use ?
If for example, you use TokenAuthentication from rest_framework, you can have a look how this class implements request authentication.
You can find there methods authenticate and authenticate_credentials and I believe that there - you will find your answer how to get the user.
In the perform_create method you can assign the user to your model
class EmailViewSet(viewsets.ModelViewSet):
authentication_classes = (TokenAuthentication)
permission_classes = (IsAuthenticated,)
queryset = Email.objects.all()
serializer_class = EmailSerializer
def perform_create(self, serializer):
serializer.save(user=self.request.user)

Detect first time user has authenticated using Django Rest Framework

I'm using DRF to allow users of my mobile app to authenticate to my web application.
I want to create a model instance associated with this user the first time a user "logs in" using the client.
I'm using token-based authentication in DRF, and for my /api/authenticate/ endpoint I'm pointing at url(r'^authenticate/', restviews.obtain_auth_token),
It seems like the best way to handle this is to override ObtainAuthToken(APIView), by adding this class to my api/views.py. This class looks like this:
class ObtainAuthTokenCustomized(APIView):
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
obtain_auth_token = ObtainAuthTokenCustomized.as_view()
It looks like I would want to insert a test prior to get_or_create for whether a token has been created previously for this user. And if so, perform the model instance creation I have planned.
Is this there a better way to handle this?
From what I can tell this is the best place to handle this.
The reason is that DRF does not currently have a token expiration capability. So once a token is created with the above class it does not go away.
This means created will return True if it is the user's first time logging in:
token, created = Token.objects.get_or_create(user=user)
Thus you'd simply test created on the following line and perform the model creation or other actions necessary.
Additional logic may be necessary to handle a situation if tokens were removed. For example, if you used created an API logout method like the one given in this answer.

Django Rest Framework API How to extract access_token from request?

My API is currently protected by the OAuth2TokenAuthentication from django-oauth-toolkit, so that it can validate API requests that contains access token in following ways:
as query param?access_token=xxxx
in header Authorization: Bearer xxxx
while I can hardcode in my API view to try to get the access token from those 2 places, is there a canonical way to obtain the token?
I dug through the code inside OAuth2TokenAuthentication, and borrowed it into my API View:
class IntrospectView(APIView):
"""
An API view that introspect a given token
"""
serializer_class = TokenIntrospectSerializer
authentication_classes = []
permission_classes = []
def get(self, request, *args, **kwargs):
oauthlib_core = get_oauthlib_core()
valid, r = oauthlib_core.verify_request(request, scopes=[])
if not valid:
raise APIException('Invalid token')
return Response(TokenIntrospectSerializer(r.access_token).data)

Django - how to use HttpBasicAuth

In my Django code I am writing a connection.py, which will connect to another server using the following http_auth = http_auth.HTTPBasicAuth(user password). So when I am connecting to that server one of the parameter I pass is http_auth = http_auth.HTTPBasicAuth(user password) against the server. I searched the web a lot and Django docs but nothing exactly tells me how to do this? Can anyone please help
Here is an example of how you might use Django's Basic Authentication when presenting Users as RESTful resources:
# REST endpoint for authenticating user accounts
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'auth/user'
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
def apply_authorization_limits(self, request, object_list):
return object_list.filter(username=request.user)
Authentication can be as simple as the one line:
authentication = BasicAuthentication()
depending on how you implement it.