Django Rest Framework - React - Unable to login immediately after logout - django

This is very strange. I have a react front end and a django backend with djangorestframework and django-allauth for authentication. Everything works fine from Postman. But in the browser when I successfully sign in, successfully sign out, and then try to sign in again, I get a 401 unauthorized error. The correct user credentials are sent to the server just as the first successful time, yet a 401 error. However, after I refresh the browser then I am able to sign in normally again. I use jwt for authentication and I append the token to the authorization header before sign out. I even tried clearing out the authorization header after a successful sign out but to no avail. It is the same problem with my react native front end. I don't know if this is a react or a django problem. Please does anyone have any idea what the problem might be? Thanks.

The problem solved! I appended the Token to the authorization header like so:
request.headers['Authorization'] = Token ${token}
Except when signing out, every other request did not require the authorization header to be set as above. So after sign out, the authorization header becomes:
request.headers.Authorization = Token null
That null value of the token would make every request after sign out "Unauthorized". So to solve this, I had to set the Authorization header for every request when there is token and then delete the Authorization from the header object when there is no token like so:
delete request.headers.Authorization

Related

Djoser is ignoring my Authenitcation Token

I set up djoser and DRF's TokenAuthentication. It works perfectly for registering users, and i get a valid token returned. When I try to access /users/me or /token/logout with header:
Authorization: Token {token} (and the token itself in the body for good measure) I get the response Error 403: "Authentication credentials not provided."
I've tried making the request through axios and postman.
I made other accounts and tried their keys but I get the same result.
I've looked on the djoser docs but there is no help there, nor anywhere else, because it seems no one else has this issue.
In my settings.py I had correctly figured DEFAULT_AUTHENITCATION_CLASSES and not DEFAULT_AUTHENTICATION_CLASSES. Now it works.

How does Djoser JWT login flow works

So I've been trying to use Djoser JWT and I don't know how to login in it. As far as I know you create a request with your login credentials to this url /jwt/create/ and get the access and refresh token and maybe get the user object from /users/me/. This is where I got stuck, where do I go from here?
You correctly understood the first step of the process. Basically, you can now:
Add the access token in the header of your next requests.
This will transparently authenticate the user thanks to the Simple JWT plugin and you will be able to access him with the usual request.user in the views.
Refresh the access token each time you get a 401 response.
The access token is supposed to be short-living for security concerns and a 401 response from the server indicates that the one your are using is expired. So you have to get a new one by sending the refresh token to the token/refresh/ API and, then, make your request again.
You can read this article if you need more detailed explanations about this process or JWT.

Why can't I retrieve user data from Djoser user endpoint

So I'm testing my djoser url endpoints from djoser almost every endpoints worked but I cant get the user from /users/me/, I'm using JWT and and here's my postman headers
I got the JWT from the login process but it still returns an error as displayed in the screenshot
and my server also says
Forbidden: /auth/users/me/
[04/Jul/2021 02:10:28] "GET /auth/users/me/ HTTP/1.1" 403 58
what's causing this error?
P.S tell me if you need more info
The problem is your Authorization field. You're using JWT, but acutally you should Bearer.
Change your authorization field to Bearer ACCESS_TOKEN. Naturally, change ACCESS_TOKEN for a valid access token.
Let us know if it has solved your problem.

How does Postman handle localhost OAuth 2 redirects?

When using Postman to fetch an access token via Authorization Code, one of the fields I need to enter is for the Callback URL, aka the redirect URI query param when it's making the request to the authorization endpoint. I understand this URL needs to be registered/whitelisted within the OAuth provider, but my question is how does postman actually handle/intercept that request/redirect back when it's localhost-based? For example, if I already had a local server running on http://locahost:8090, and I told postman to use http://localhost:8090 for that callback, how does Postman end up seeing that request/redirect back (to exchange the auth code for an access token) instead of my local web server handling that request?
TL;DR: Postman basically ignores the callback URL when processing the response.
The Long Story
It does need it, but only for the request. As you say, it needs to be correct - exactly matching the IdP client application config - but that's it.
Postman is just helping you acquire the token, it doesn't need to provide it to the consuming application, which is the whole point of the redirect URL - a static path known by the client app and the OAuth client application that makes sure an evil website / intermediary doesn't steal tokens by abusing the redirection flows.
Since it's not meant to work on a browser on the internet, Postman can ignore the redirect. Once the IdP responds with the token then, as far as Postman is concerned, it's good to go. It can save the token in the local token store and use it to make API requests.
Implicit Flow
This is set up to get a token from an Okta endpoint:
When I click "Request token", Postman makes a request like this:
GET https://exampleendpoint.okta.com/oauth2/default/v1/authorize?nonce=heythere&response_type=token&state=state&client_id={the_client_id}&scope=profile%20openid&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fimplicit%2Fcallback
Postman pops a browser to make this request to the /authorize endpoint, at which the IdP then either creates the token (if the browser already has a cookie), or performs various redirects to authenticate the user and then create the token.
At the end of this flow, Postman will receive the 302 from the IdP that contains the token (on the location header). The target of that redirect is the redirect URL configured in the IdP:
302
Location: http://localhost:8080/implicit/callback#access_token=eyJraWQiOiJxOGRmTGczTERCX3BEVmk4YVBrd3JBc3AtMFU1cjB6cXRUMFJveFZRUVVjIiwiYWxnIjoiUlMyNTYifQ.{the_rest_of_the_token}&token_type=Bearer&expires_in=3600&scope=profile+openid&state=state
At this point Postman grabs the token from the #access_token parameter and it's good to go.
Auth Code Flow
Auth Code flow comes in 2 flavours:
Auth Code (Classic)
Auth Code + PKCE
Auth Code flow has been seen as "better" than the implicit flow because it requires a 2nd step in the process to get an access token. You hit authorize which gives the client a code and the code is then exchanged for the tokens. This code for token gives more chances for the server side components to do more stuff - extra checks, enrich tokens and various other things.
Q: Why are there 2 Auth Code flows?
A: The problem with this was that it required a server side component, which many SPA's and/or mobile apps didn't want to host. The endpoint that receives the code and gets the token(s) had to maintain credentials - a client id and client secret - which are required by the IdP when creating the token. PKCE is an extension that removes the requirement for a trusted server. It's adds computed hash to the /authorize call, which the IdP remembers, and then on the subsequent call to /token the client provides the source value of the hash. The server does the same computation, checks it's the same as that on the original request and is then satisfied that it's not handing out tokens to a bad guy.
Auth Code with PKCE
In terms of redirects, this is exactly the same as implicit. But for requests, it needs to make the second request to exchange the code for the tokens. The main differences here are
the access token URL, which is where to send the code and get tokens in response.
the code challenge and verifier, which are PKCE requirements for generating and computing the hash
The requests are now as follows:
The GET to /authorize
GET https://exampleendpoint.okta.com/oauth2/default/v1/authorize?nonce=heythere&response_type=code&state=state&client_id={client_id}&scope=profile%20openid&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fimplicit%2Fcallback&code_challenge=E7YtiHqJRuALiNL_Oc5MAtk5cesNh_mFkyaOge86KXg&code_challenge_method=S256
Postman will pop the browser (and the IdP will redirect it through login if required)
The eventual code response is also 302, however the location header contains the code rather than tokens:
location: http://localhost:8080/implicit/callback?code=J3RlQqW122Bnnfm6W7uK&state=state
So now the client needs to call the endpoint defined in the "Access Token URL" field to get tokens:
POST https://exampleendpoint.okta.com/oauth2/default/v1/token
Body:
grant_type: "authorization_code"
code: "J3RlQqW122Bnnfm6W7uK"
redirect_uri: "http://localhost:8080/implicit/callback"
code_verifier: "Fqu4tQwH6bBh_oLKE2zr0ijArUT1pfm1YwmKpg_MYqc"
client_id: "{client_id}"
client_secret: ""
And the response is a good old 200 that doesn't redirect - the authorize call sends the client back to the final redirect landing page, and the POST is just a normal request with the tokens on the the response
{"token_type":"Bearer","expires_in":3600,"access_token":"eyJraWQiOiJxOGRmTGczTERCX3BEVmk4YVBrd3JBc3AtMFU1cjB6cXRUMFJveFZRUVVjIiwiYWxnIjoiUlMyNTYifQ.*******","scope":"profile openid","id_token":"eyJraWQiOiJxOGRmTGczTERCX3BEVmk4YVBrd3JBc3AtMFU1cjB6cXRUMFJveFZRUVVjIiwiYWxnIjoiUlMyNTYifQ.********"}

Sending CSRF Tokens via Postman

I'm trying to test my web server's login with Postman. First, I send a GET request to my login url, and I get a CSRF token as a cookie. Then, I make a POST request to that login page, with my username, password, and CSRF token.
My problem is, when I do this in Postman, I get a 403 forbidden error when I try to make that POST request to login. I'm copying the CSRF token received and putting it as one of the POST parameters, and I'm using a valid username and password. Is there anything I'm overlooking here?
You need to set it as a header in the request, not in the body. X-CSRFToken is the key and the value is CSRF token from the cookie. This will work if you are using an API framework like Tastypie or Django Rest Framework.
If you are authenticating without an API layer you would need to actually attach the cookie or create one with the CSRF token. This post explains it.
Try installing the Postman Interceptor Extension on GoogleChrome. It worked for me.
Works for me :
Set in Postman Header :
KEY : Authorization
Value : Token "Your token"