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.
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
I am creating a project in django for my mobile app. The django project is the API backend for the mobile App. I have created a signup for the user model using django rest framework. The signup API works fine. Now, i want to let only the request from my mobile app to be served. For this i created an oauth application Authorization grant type " client-credentials "
class UserSerializer(ModelSerializer):
email = serializers.EmailField(
required=True,
validators=[UniqueValidator(queryset=User.objects.all())]
)
username = serializers.CharField(
validators=[UniqueValidator(queryset=User.objects.all())]
)
password = serializers.CharField(min_length=8)
def create(self, validated_data):
user = User.objects.create_user(validated_data['username'], validated_data['email'],
validated_data['password'])
return user
class Meta:
model = User
fields = ('id', 'username', 'email', 'password')
read_only_fields = ('id',)
write_only_fields = ('password',)
This is the user serializer and the view is
class UserCreateAPIView(CreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (IsAuthenticatedOrCreate, TokenHasScope)
But the problem is I can make direct calls to the signup api without using the toke. How to make sure that the User Create API is called when only the token is passed or the post request to be valid when the token is passed.
You can simply create an application with grant type Client Credentials,
and set your permission class as :
permission_classes = [TokenHasReadWriteScope]
For your other APIs, which require user authentication and authorization, you can issue another client with grant type Resource Owner Password Based,
and set your permission class as :
permission_classes = [TokenHasReadWriteScope, YourCustomPermission]
Or, if you need both client credentials as well as resource owner password based (For eg, your signup api may need only client credentials but editing personal information of user may require resource owner password based grant). For this you can create custom application model and allow both for the client.
http://django-oauth-toolkit.readthedocs.io/en/latest/advanced_topics.html?highlight=extending%20
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 ?
I've been developing a mobile app to access one of my django websites. I've done the restful API using TastyPie and developed the front end using JQMobile. I've come to the part where I want to log users and have access to that logged in user.
I've done a lot of reading and searching, but I'm still really unsure what is the best approach. Ideally, I'd like to log in the user with their username and password, and then filter some of the API's returned data on this user (which I can do via the TastyPie documentation).
How have other people approached authenticating users with JQMobile and Django. I'm using PhoneGap as well so I can store returned user info from a login in the local storage if required. But I'm not quite sure how to code it all together to make request.user available on the django side when the mobile users are using the app.
So far I've come up with this from another couple of posts in the UserResource on the TastyPie side of things to sign in a user, but I'm not sure what to do once the user is signed in.
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
list_allowed_methods = ['get', 'post']
def override_urls(self):
return [
url(r"^(?P<resource_name>%s)/signin%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view('signin'), name="api_signin"),
]
def signin(self, request, **kwargs):
self.method_check(request, allowed=['post'])
# Per https://docs.djangoproject.com/en/1.3/topics/auth/#django.contrib.auth.login...
username = request.GET['username']
password = request.GET['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return self.create_response(request, {'success': True})
else:
# Return a 'disabled account' error message
return self.create_response(request, {'success': False})
else:
# Return an 'invalid login' error message.
return self.create_response(request, {'success': False})
Does anyone have any code they can share, or any pointers how to log in the users and maintain their state?
Cheers,
Ben
Phonegap is actually just a browser wrapped in some native code, which means it has the same means to persist sessions like normal web browser do - cookies!
Every ajax request being sent to the backend API can contain the sessionid cookie just like a normal GET request. The requst.user object will be available to you in your views.
You don't need to build anything special or use localstorage for that. The only thing to verify is that your domain is whitelisted so your app can access it.
I already know how to create ModelResource in tastypie. For example, I have UserResource in resources.py and User in models.py. However in views.py, I have a view called match_user where it takes the list of all user and match to request.user. It return a render_to_response html called mymatch.html. Everything works on the browser but I want to create an API for this particular match_user. How can I do that?
Thank you
I think the following answers your question:
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = "user"
authentication = SessionAuthentication()
# User is only authorized to view his own details
def apply_authorization_limits(self, request, object_list):
return object_list.filter(pk=request.user.pk)
Session authentication would work if the user has an active session and is already logged in. For more authentication options, see https://django-tastypie.readthedocs.org/en/latest/authentication_authorization.html?highlight=authentication#authentication-options