Ali Khiti
Ali Khiti

Reputation: 275

How can I use JWT tokens in Django Rest Framework?

I'm new to django and DRF, I'm trying to build an authentification system using JWT, I want to login the user directly after registering, I read the documentation and I managed to create a token manually and return it in my serializer, but my questions are this:

1) How can I use this token to see if the user is logged in or not?

2) Can I use the {% if user.is_authenticated %} in my templates? if so how?

3) How can I get the user logged in informations in another view?

4) Is there a more efficient way of dealing with authentifications with DRF?

Upvotes: 1

Views: 979

Answers (2)

Carter
Carter

Reputation: 342

DRF Auth and Permissions has a lot of useful information on working with auth and permissions in DRF, check it out.

Adding on to what @Reza-Torkaman-Ahmadi said:

In your views you can use permissions to make sure a user is authenticated:

permission_classes = (permissions.IsAuthenticatedOrReadOnly,) 

Upvotes: 0

Reza Torkaman Ahmadi
Reza Torkaman Ahmadi

Reputation: 3038

1- Basically when you are using DRF and jwt token, Means you are using token-based authentication, So all your requests should contains a http header for Authorization: basic <token value>. So django drf authentication backend, will recognize this token and if valid, user will be authenticated.

2- I don't think you can use that templatetag anymore. Because that's for session based authentications.

3- if you provide the authentication backed for that token and send the token in header, every view should has user info in request.user

4- One of the best solutions in my opinion is token-based with jwt tokens.

Upvotes: 2

Related Questions