I currently have the following:
from flask import Flask, session,request
#app.route('/venue/login', methods=['GET', 'POST'])
def venue_login():
token = generate_token()
session['venue_id'] = token
return json.dumps(...)
When I look at the response in Chrome, I can see that Set-Cookie:session=... has been set.
I have 2 questions:
1) How do I read this cookie on the `server?
I have tried:
venue_id = request.cookies.get('venue_id')
but this doesn't seem to be picking it up.
2) With my code above, all my cookies will be set with the same name. After reading the cookie value, I would like to delete the corresponding entry in session. How should I go about doing this? Also if two requests come in one after the other, will the line:
session['venue_id'] = token
override the first entry with the second? Or does every request start a new session?
I am kind of confused with how this all should work. Any help would be greatly appreciated.
Well. Cookies and sessions are a bit different.
If you want to use cookies and make venue_id = request.cookies.get('venue_id') work - You need to use set_cookie:
set_cookie('venue_id', token)
In cookies case - you can solve general problems that cookies can solve (have a long lasting cookie for example)
If you want to use session (which is intended for session uniqueness and auth) you need to just use session and put the "username" or the unique ID of the venue in your case.
Which to use - It really depends what you are trying to achieve
Have a look at:
http://flask.pocoo.org/docs/0.10/quickstart/#cookies
http://flask.pocoo.org/docs/0.10/quickstart/#sessions
Related
I am struggling to understand exactly how JWT-based authentication should be implemented in Django (I am using simplejwt). I am just a beginner, so please brace yourselves for some silly questions. The rest-framework-simplejwt documentation is very minimal and does not provide enough detail for a newbie like me.
path('token/obtain', jwt_views.TokenObtainPairView.as_view(), name='token_create'),
path('token/refresh', jwt_views.TokenRefreshView.as_view(), name='token_refresh'),
So, I've created the paths in my urls.py as suggested by the official documentation. Where do I go from here? I guess my confusion comes from the fact that I am not sure where exactly in the code I have to issue my tokens. Let's say, I am logging in the user. So, in order to obtain the token, do I have to send a request to the 'token_create' endpoint from inside my view? Or do I have to somehow indicate it in one of my serializers? What about the 'refresh_token' endpoint? Is there a specific method that I need to use?
Then, what do I do with the token once it has been issued? Clearly, I shouldn't save it in the database since it defeats the entire purpose of using JWTs in the first place. From my understanding, I should attach it to the headers so that the subsequent requests by the user contain the tokens in the headers.
The frontend will be written in ReactJS and will be on a separate server from my Django backend API, and the communication between the two will be configured through CORS.
In this case, how do I attach the token to the headers and make it so that the user's browser sends in the token with each request? Is there some sort of package that could be useful for that?
I think you just mixed everything up, I'm gonna explain everything however you may already know some stuff.
JWT simply is a way to authorize users, you usually create an endpoint to create a token for the users, this endpoint can be named login, create_token, 'generate_token', or anything! doesn't really matter!
However maybe if u use a specific library maybe it forces you to use a specific endpoint but in Flask it's really what you like.
This login (whatever you call it) endpoint will take a username and password and checks if it exists and it's correct, then generates a JWT with a library like PyJWT, You can configure the JWT to be expired in for example 20 mins or more, then you encrypt a dictionary(JSON?) which usually contains user_id which you query from the database. example of the JSON you provide to the user with:
{
"user_id": something,
"role": something,
...
}
Then it will be encrypted to a long string.
now when the user sends a request, he/she needs to have that long string as the Authorization header of the request.
In postman --> Authorizations, choose Bearer Authorization and then insert that long string.
We also give the user a refresh_token.
This is the example of the JSON you provide the user with when he/she calls the login endpoint:
{
token: some_long_string,
refresh_token: some_long_string,
}
So what is refresh Token?
it's just the token that when the main token expires instead of making the user enter username and password again, he just sends the refresh token we gave him while he called login.
One more point: This was the whole flow and logic you need to implement. Do it as you like, libraries or anything you like, doesn't really matter.
while reading about the Requests library, it occurred to me that I could try to fill a form by using it. So, since I have Django and the server, I first checked that I got the URL well and got a 200 answer code.
like this:
import requests
r = requests.get('127.0.0.1/myform')
print(r.status_code)
and yes, it was a 200
so the next step was going to be entering a value in the textfield, actually the form, for this example is just one field.
I tried this:
r = requests.post('127.0.0.1/myform', data ={'name' : 'Mexico'})
and nothing was entered. Here I have like 3 intriguing questions:
When I inspect the element, because the form was created using the ModelForm of Django, I could not actually give the field a name, (which would have been name) and 2. Django instead fills me the name with the csrf token value and 3. actually, I don't see how the requests.post presses the submit button.
What would be what is missing here in order to succeed posting the value through the form?
thank you
In Django web applications, at execution time the front end and the back end are separated and communicate over http/https requests and responses. The front end displays elements to the user, collects input, etc, but then to communicate with the back end it builds a POST request from that data and sends it when the user clicks submit. The form itself is not sent, just a collection of key value pairs corresponding to the fields of the form and the user input in each of those fields. On the back end that data is handed to the form so it can validate/save/etc.
So to answer your questions:
1) I'm not entirely sure what you are asking, but the important thing is that the post payload has a key that matches the name of the field in the corresponding Django form.
2) CSRF tokens are a security measure, and you'll have to manually account for this in your requests.post call. It may be easier to start by disabling them until you get your post working and then work on getting them working.
3) The requests.post doesn't actually press the submit button, you are just recreating the same http request that gets generated by the browser when a user presses the submit button. Does this make sense? This is a key point to understand.
Finally, in order to help you with a working solution we would need to see more. What does your form look like? What does your view look like?
I’ve seen a couple examples of this ( Storing auth tokens in a cookie )already; but I’d like to understand the reason for doing this.I think this would create more problems because you have to specifically remember to delete the cookie after you’re finished. For my specific example ; I am dealing with Instagram via the API
Thank you for any and all help
I`m not sure exactly what you're asking for. You need to know how to store the token? However, then is no need to remember to delete a cookie, just set an expiration date.
Regarding the API, you will need a valid token everytime you do a request to API, so don`t delete it, otherwise you will need to re-authenticate everytime.
Note: For Instagram Business Accounts you need to use Facebook API.
https://developers.facebook.com/docs/instagram-api/v2.10
I use Python 3 as a serverside scripting language, and I want a way to keep users logged into my site. I don't use any framework, since I prefer to hand code pages, so how do I create session variables like in PHP in Python 3?
The logic of a session is storing a unique session id inside the user cookie ( uuid package will do a perfect job for that ). And you store the sessions data inside a file, database or other semi-permanent datastore.
The idea is matching the sessionid that you receive from your user cookie, to some data stored somewhere on your server.
I assume that you know how to add the right header to set a cookie via the response header.
Otherwise there is more information here : http://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Responses
I've been searching on this but can't seem to figure out how I can delete a specific cookie using Google Apps Engine, Python version. I am setting the cookie like below and I need to update its value, I figure I may not be able to update and just need to delete and re-create but can't seem to find the way to do that, I am creating it as below:
str = 'if_loggedin_username='+ self.username
self.from_obj.response.headers.add_header(
'Set-Cookie', str)
Thanks for any advice.
There is no way for the server to delete an HTTP cookie. To update the value, just send a new cookie with the same name and it will be updated; to "delete" the cookie, set an expiration time in the past.
Just to add more, send a new cookie with same name with value None (NoneType)
self.response.headers.add_header("Set-Cookie", None)
Hope it helps