Flask - use of cookies

Flask - use of cookies

When the user accesses the server for the first time using the browser, the server generates a cookie, returns it in the response, and saves it in the user's browser

from flask import Flask,make_response
def set_cookie(name):
    response = make_response(redirect(url_for('hello')))
  response.set_cookie('name',name) # set_ The cookie view will create a set cookie field in the header of the generated response message, that is, "set Cookie: name = XXX; path = /"
  return response

The user will carry the saved cookie in the header when accessing the same server next time

from flask import Flask,request
def hello():
    name = request.args.get('name')  #If there is no name value in the query parameter, it is obtained from the cookie
  if name is None:
    name = request.cookies.get('name','Human')  #Get name value from Cookie
  return '<h1>Hello,%s</h1>' % name          

Because users can directly modify the cookie value of the browser and falsely use other people's accounts, it is not safe to use cookies directly

Flask provides a session object to encrypt and store cookie data (by default, it will store the data in a cookie named session on the browser)

app.secret_key = 'secret string' # set key

It is safer to write the key into the system environment variable (use the export or set command on the command line) or save it in env file

SECRET_KEY=secret string

Then use the getenv() method provided by the os module in the program script to obtain:

app.secret_key = os.getenv('SECRET_KEY','secret string ') # the second parameter is the default value used when the corresponding environment variable is not obtained`

#Combined use
def login():
    session['logged_in'] = True 
    #Write session Add a named logged to the session_ In, set its value to True
    #When adding a cookie with a session object, the data will be signed with the key of the program, and the encrypted data will be stored in a cookie named session The user can see the encrypted value, but cannot modify it. Once the data is modified, the value of the signature will also change. In this way, the verification will fail when reading, and the corresponding session value will become invalid
    return redirect(url_for('hello'))
def hello():
    name = request.args.get('name')
    if name is None:
        name = request.cookies.get('name','Human')
        response = '<h1>Hello, %s!</h1>' % name
    #The data in the session can be read by keys like a dictionary or by using the get() method
    if 'logged_in' in session:  #Different contents are returned according to the user authentication status
        response += '[Authenticated]'
        response += '[Not Authenticated]'
    return response

To log out of the user's account, the actual operation is to log the user's authentication on behalf of the user_ In cookie deletion is realized through the pop method of session object

from flask import session
def logout():
  if 'logged_in' in session:
  return redirect(url_for('hello'))

By default, session cookie s are deleted when the user closes the browser

By setting session Setting the persistent property to True can extend the validity of the session to flask permanent_ session_ Datetime. Corresponding to the value of the lifetime attribute Timedelta object

You can also configure the variable PERMANENT_SESSION_LIFETIME is set to 31 days by default

Although the session object will sign and encrypt the Cookie, this method can only ensure that the content of the session will not be tampered with. The encrypted data can still be easily read with the help of tools (i.e. I don't know the key), so it is absolutely impossible to store sensitive information such as user password in the session

Posted by sumitnice@rediffmail.com on Mon, 23 May 2022 20:31:40 +0300