Hi I am building a web service using HttpBasicAuth for authentication on top of Django authentication. Using tastypie this works flawlessly with minimal configuration. However I'm trying to figure out the best way to simply check the credentials with the service before making any actual calls to my resources for data. Is there some best practice way of doing this ?
This is how I eventually solved it.
class LoginResource(ModelResource):
class Meta:
allowed_methods = ['get']
resource_name = 'login'
include_resource_uri = False
object_class = User
authentication = BasicAuthentication()
authorization = DjangoAuthorization()
def obj_get_list(self, bundle, **kwargs):
return [bundle.request.user]
Still interested in hearing what others have to say on this, maybe there is still a better way ?
Related
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
In my Django project I have a public API endpoint built with Django Rest Framework's APIView. It does not need to know anything about the user. Still, Django automatically fetches the session and the user from the database. Is there a way to not do this since it causes two unnecessary DB hits?
Here is the code:
class TermListView(APIView):
permission_classes = ()
def get(self, request, format=None):
qs = Term.objects.all().only('original_word')
return Response([term.original_word for term in qs])
You need to add authentication_classes = () to the View class. This tells Django not to worry about the user. Or you can also configure this option globally for all your endpoints.
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.
We are using Django Rest Framework in our web projects, and it's great. We also use headers based authentication with token etc.. That creates a situation where our developers can't easily browse the browesable api without getting a token, pasting it, etc.
Is there a way around this? disable token security for the browersable api and allow some kind of basic http user/password auth? maybe IP protection? Any other Ideas how to solve this problem? I'll love to hear feedback from other DRF users.
I haven't tested this with TokenAuthentication but it should be the right way to go (of course you need to make it a mixin and reuse it):
class MyAwesomeView(APIView):
authentication_classes = (SessionAuthentication, BasicAuthentication)
permission_classes = (IsAuthenticated,)
# some more attributes
def initial(self, request, *args, **kwargs):
if self.get_format_suffix(**kwargs) == 'api':
self.authentication_classes = (BasicAuthentication,)
super(MyAwesomeView, self).initial(request, *args, **kwargs)
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.