JWT Login Django Rest FrameworkDoes Django scale?differentiate null=True, blank=True in djangoUser Authentication in Django Rest Framework + Angular.js web appDjango-rest-framework-jwt won't return JWToken for nonstaff accounts (django admin error?)Can't create user through POST request in DjangoLogout Django Rest Framework JWTJWT Authentication with Django REST FrameworkDjango Rest Framework JWT - OperationalError: no such table: auth_userDjango Rest Framework: JWT Authorization failedDjango rest framework JWT , delete the jwt token

Does science define life as "beginning at conception"?

If you attack a Tarrasque while swallowed, what AC do you need to beat to hit it?

Gambler's Fallacy Dice

How is dynamic resistance of a diode modeled for large voltage variations?

Managing heat dissipation in a magic wand

Why is this python script running in background consuming 100 % CPU?

How can I prevent Bash expansion from passing files starting with "-" as argument?

Don't understand notation of morphisms in Monoid definition

Is there a way to generate a mapping graph like this?

US F1 Visa grace period attending a conference

How do we properly manage transitions within a descriptive section?

How to add a low pass filter to this non-inverting amplifier circuit?

What city and town structures are important in a low fantasy medieval world?

What should I wear to go and sign an employment contract?

How could Dwarves prevent sand from filling up their settlements

Bash - Execute two commands and get exit status 1 if first fails

How did Arya and the Hound get into King's Landing so easily?

Are CTRL+C and <esc> the same?

Separate the element after every 2nd ',' and push into next row in bash

400–430 degrees Celsius heated bath

What variables do I have to take into consideration when I homebrew armour?

Schwa-less Polysyllabic German Noun Stems of Germanic Origin

Connecting circles clockwise in TikZ

Story about encounter with hostile aliens



JWT Login Django Rest Framework


Does Django scale?differentiate null=True, blank=True in djangoUser Authentication in Django Rest Framework + Angular.js web appDjango-rest-framework-jwt won't return JWToken for nonstaff accounts (django admin error?)Can't create user through POST request in DjangoLogout Django Rest Framework JWTJWT Authentication with Django REST FrameworkDjango Rest Framework JWT - OperationalError: no such table: auth_userDjango Rest Framework: JWT Authorization failedDjango rest framework JWT , delete the jwt token






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I' m trying to create login view with djangorestframework-jwt.When i logged my user (url 'login/') it was fine and everything worked but and switched to another page (url 'post_list') to create a post I got an error that my user is anonymous so that is why I decided that that my user is again unauthenticated. Could you please help me to create proper JWT Login view that will allow me to create and switch between different pages without any obstacles?



My settings.py:



REST_FRAMEWORK = 

'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
],

'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],



My Serializers:



class TokenSerializer(serializers.Serializer):
username = serializers.CharField(max_length=128)
password = serializers.CharField(write_only=True,
required=True,
style=
'input_type': 'password',
'placeholder': 'password'
)


class PostSerializer(serializers.ModelSerializer):
created_by = serializers.ReadOnlyField(source='created_by.username')

class Meta:
model = Post
fields = '__all__'


My views:



class UserLogin(generics.CreateAPIView):
"""
POST login/
"""
permission_classes = (permissions.AllowAny,)
queryset = User.objects.all()
serializer_class = TokenSerializer

def post(self, request, *args, **kwargs):
username = request.data.get("username", "")
password = request.data.get("password", "")

user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
return Response(
"token": jwt_encode_handler(jwt_payload_handler(user)),
'username': username,
, status=200)
return Response(status=status.HTTP_401_UNAUTHORIZED)


class PostView(generics.ListCreateAPIView):
"""
POST, GET post_list/
"""

serializer_class = PostSerializer
queryset = Post.objects.all()

def perform_create(self, serializer):
serializer.save(created_by=self.request.user)

permission_classes = (permissions.IsAuthenticatedOrReadOnly, )


URLS:



urlpatterns = [
url(r'^register/$', UserRegistration.as_view(), name='registration'),
url(r'^login/$', UserLogin.as_view(), name='user_login'),
url(r'^post_list/$', PostView.as_view(), name='post_list'),
]









share|improve this question

















  • 1





    After loggging in, do you send your jwt token in the request authorization header while trying to create a post?

    – Ozgur Akcali
    Mar 23 at 19:50











  • What are you using as your front end framework? As the above commentator noted, you need to provide an 'Authorization' header with every request to an authenticated endpoint for your backend. The header will have the token in it you receive at login.

    – Nidal
    Mar 23 at 20:37











  • @Nida I am using djangorestframework

    – roziukp
    Mar 23 at 21:08











  • @roziukp DRF is your backend. Which language are you writing the website / client code on? Usually something like Angular, React or even pure JavaScript

    – Nidal
    Mar 23 at 21:14











  • Please, provide how do you send both requests

    – Headmaster
    Mar 25 at 8:00

















1















I' m trying to create login view with djangorestframework-jwt.When i logged my user (url 'login/') it was fine and everything worked but and switched to another page (url 'post_list') to create a post I got an error that my user is anonymous so that is why I decided that that my user is again unauthenticated. Could you please help me to create proper JWT Login view that will allow me to create and switch between different pages without any obstacles?



My settings.py:



REST_FRAMEWORK = 

'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
],

'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],



My Serializers:



class TokenSerializer(serializers.Serializer):
username = serializers.CharField(max_length=128)
password = serializers.CharField(write_only=True,
required=True,
style=
'input_type': 'password',
'placeholder': 'password'
)


class PostSerializer(serializers.ModelSerializer):
created_by = serializers.ReadOnlyField(source='created_by.username')

class Meta:
model = Post
fields = '__all__'


My views:



class UserLogin(generics.CreateAPIView):
"""
POST login/
"""
permission_classes = (permissions.AllowAny,)
queryset = User.objects.all()
serializer_class = TokenSerializer

def post(self, request, *args, **kwargs):
username = request.data.get("username", "")
password = request.data.get("password", "")

user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
return Response(
"token": jwt_encode_handler(jwt_payload_handler(user)),
'username': username,
, status=200)
return Response(status=status.HTTP_401_UNAUTHORIZED)


class PostView(generics.ListCreateAPIView):
"""
POST, GET post_list/
"""

serializer_class = PostSerializer
queryset = Post.objects.all()

def perform_create(self, serializer):
serializer.save(created_by=self.request.user)

permission_classes = (permissions.IsAuthenticatedOrReadOnly, )


URLS:



urlpatterns = [
url(r'^register/$', UserRegistration.as_view(), name='registration'),
url(r'^login/$', UserLogin.as_view(), name='user_login'),
url(r'^post_list/$', PostView.as_view(), name='post_list'),
]









share|improve this question

















  • 1





    After loggging in, do you send your jwt token in the request authorization header while trying to create a post?

    – Ozgur Akcali
    Mar 23 at 19:50











  • What are you using as your front end framework? As the above commentator noted, you need to provide an 'Authorization' header with every request to an authenticated endpoint for your backend. The header will have the token in it you receive at login.

    – Nidal
    Mar 23 at 20:37











  • @Nida I am using djangorestframework

    – roziukp
    Mar 23 at 21:08











  • @roziukp DRF is your backend. Which language are you writing the website / client code on? Usually something like Angular, React or even pure JavaScript

    – Nidal
    Mar 23 at 21:14











  • Please, provide how do you send both requests

    – Headmaster
    Mar 25 at 8:00













1












1








1








I' m trying to create login view with djangorestframework-jwt.When i logged my user (url 'login/') it was fine and everything worked but and switched to another page (url 'post_list') to create a post I got an error that my user is anonymous so that is why I decided that that my user is again unauthenticated. Could you please help me to create proper JWT Login view that will allow me to create and switch between different pages without any obstacles?



My settings.py:



REST_FRAMEWORK = 

'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
],

'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],



My Serializers:



class TokenSerializer(serializers.Serializer):
username = serializers.CharField(max_length=128)
password = serializers.CharField(write_only=True,
required=True,
style=
'input_type': 'password',
'placeholder': 'password'
)


class PostSerializer(serializers.ModelSerializer):
created_by = serializers.ReadOnlyField(source='created_by.username')

class Meta:
model = Post
fields = '__all__'


My views:



class UserLogin(generics.CreateAPIView):
"""
POST login/
"""
permission_classes = (permissions.AllowAny,)
queryset = User.objects.all()
serializer_class = TokenSerializer

def post(self, request, *args, **kwargs):
username = request.data.get("username", "")
password = request.data.get("password", "")

user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
return Response(
"token": jwt_encode_handler(jwt_payload_handler(user)),
'username': username,
, status=200)
return Response(status=status.HTTP_401_UNAUTHORIZED)


class PostView(generics.ListCreateAPIView):
"""
POST, GET post_list/
"""

serializer_class = PostSerializer
queryset = Post.objects.all()

def perform_create(self, serializer):
serializer.save(created_by=self.request.user)

permission_classes = (permissions.IsAuthenticatedOrReadOnly, )


URLS:



urlpatterns = [
url(r'^register/$', UserRegistration.as_view(), name='registration'),
url(r'^login/$', UserLogin.as_view(), name='user_login'),
url(r'^post_list/$', PostView.as_view(), name='post_list'),
]









share|improve this question














I' m trying to create login view with djangorestframework-jwt.When i logged my user (url 'login/') it was fine and everything worked but and switched to another page (url 'post_list') to create a post I got an error that my user is anonymous so that is why I decided that that my user is again unauthenticated. Could you please help me to create proper JWT Login view that will allow me to create and switch between different pages without any obstacles?



My settings.py:



REST_FRAMEWORK = 

'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
],

'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],



My Serializers:



class TokenSerializer(serializers.Serializer):
username = serializers.CharField(max_length=128)
password = serializers.CharField(write_only=True,
required=True,
style=
'input_type': 'password',
'placeholder': 'password'
)


class PostSerializer(serializers.ModelSerializer):
created_by = serializers.ReadOnlyField(source='created_by.username')

class Meta:
model = Post
fields = '__all__'


My views:



class UserLogin(generics.CreateAPIView):
"""
POST login/
"""
permission_classes = (permissions.AllowAny,)
queryset = User.objects.all()
serializer_class = TokenSerializer

def post(self, request, *args, **kwargs):
username = request.data.get("username", "")
password = request.data.get("password", "")

user = auth.authenticate(request, username=username, password=password)
if user is not None:
auth.login(request, user)
return Response(
"token": jwt_encode_handler(jwt_payload_handler(user)),
'username': username,
, status=200)
return Response(status=status.HTTP_401_UNAUTHORIZED)


class PostView(generics.ListCreateAPIView):
"""
POST, GET post_list/
"""

serializer_class = PostSerializer
queryset = Post.objects.all()

def perform_create(self, serializer):
serializer.save(created_by=self.request.user)

permission_classes = (permissions.IsAuthenticatedOrReadOnly, )


URLS:



urlpatterns = [
url(r'^register/$', UserRegistration.as_view(), name='registration'),
url(r'^login/$', UserLogin.as_view(), name='user_login'),
url(r'^post_list/$', PostView.as_view(), name='post_list'),
]






python django django-rest-framework jwt django-rest-framework-jwt






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 19:34









roziukproziukp

275




275







  • 1





    After loggging in, do you send your jwt token in the request authorization header while trying to create a post?

    – Ozgur Akcali
    Mar 23 at 19:50











  • What are you using as your front end framework? As the above commentator noted, you need to provide an 'Authorization' header with every request to an authenticated endpoint for your backend. The header will have the token in it you receive at login.

    – Nidal
    Mar 23 at 20:37











  • @Nida I am using djangorestframework

    – roziukp
    Mar 23 at 21:08











  • @roziukp DRF is your backend. Which language are you writing the website / client code on? Usually something like Angular, React or even pure JavaScript

    – Nidal
    Mar 23 at 21:14











  • Please, provide how do you send both requests

    – Headmaster
    Mar 25 at 8:00












  • 1





    After loggging in, do you send your jwt token in the request authorization header while trying to create a post?

    – Ozgur Akcali
    Mar 23 at 19:50











  • What are you using as your front end framework? As the above commentator noted, you need to provide an 'Authorization' header with every request to an authenticated endpoint for your backend. The header will have the token in it you receive at login.

    – Nidal
    Mar 23 at 20:37











  • @Nida I am using djangorestframework

    – roziukp
    Mar 23 at 21:08











  • @roziukp DRF is your backend. Which language are you writing the website / client code on? Usually something like Angular, React or even pure JavaScript

    – Nidal
    Mar 23 at 21:14











  • Please, provide how do you send both requests

    – Headmaster
    Mar 25 at 8:00







1




1





After loggging in, do you send your jwt token in the request authorization header while trying to create a post?

– Ozgur Akcali
Mar 23 at 19:50





After loggging in, do you send your jwt token in the request authorization header while trying to create a post?

– Ozgur Akcali
Mar 23 at 19:50













What are you using as your front end framework? As the above commentator noted, you need to provide an 'Authorization' header with every request to an authenticated endpoint for your backend. The header will have the token in it you receive at login.

– Nidal
Mar 23 at 20:37





What are you using as your front end framework? As the above commentator noted, you need to provide an 'Authorization' header with every request to an authenticated endpoint for your backend. The header will have the token in it you receive at login.

– Nidal
Mar 23 at 20:37













@Nida I am using djangorestframework

– roziukp
Mar 23 at 21:08





@Nida I am using djangorestframework

– roziukp
Mar 23 at 21:08













@roziukp DRF is your backend. Which language are you writing the website / client code on? Usually something like Angular, React or even pure JavaScript

– Nidal
Mar 23 at 21:14





@roziukp DRF is your backend. Which language are you writing the website / client code on? Usually something like Angular, React or even pure JavaScript

– Nidal
Mar 23 at 21:14













Please, provide how do you send both requests

– Headmaster
Mar 25 at 8:00





Please, provide how do you send both requests

– Headmaster
Mar 25 at 8:00












0






active

oldest

votes












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317598%2fjwt-login-django-rest-framework%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55317598%2fjwt-login-django-rest-framework%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript