logo
Published on

Session

Authors
  • avatar
    Name
    Bowen Y
    Twitter

What is Session?

A session is a server-side storage of information that is related to a particular user or browser.

Sessions are used to persist user data across multiple HTTP requests. When a session is started, the server creates a unique identifier (session ID) which is typically passed back to the browser via a cookie.

The main security concern is session hijacking. Protecting the session ID, especially in transit (using HTTPS), is critical.

{
    "session_id": "ABCDEFG1234567",
    "user_id": 123,
    "auth": true,
    "last_accessed": "2024-01-15T12:34:56"
}
  • session_id: Unique identifier for the session.
  • user_id: Identifier for the user.
  • auth: A flag indicating whether the user is authenticated.
  • last_accessed: The last time the session was accessed.

Remember, this data is stored on the server. The client only has the session_id, typically in a cookie.

Usage Example

  • Action: The user logs in with their credentials.
  • Behind the Scenes: The server verifies the credentials and creates a session on the server side, assigning it a unique session ID, say session_id=ABCDE.
  • Cookie Integration: This session ID is sent back to the browser as a cookie.
  • Subsequent Requests: Each time the user makes a new request, the browser sends back the session ID. The server uses this ID to retrieve session data (like user authentication status, user preferences, etc.) and knows it's the same user across different requests.
  • Security: The session data itself is stored server-side, and only the session ID is exchanged with the browser, enhancing security.

Difference under the hood

  • Storage Location: On the server.
  • Data Storage: Stores user data on the server. A session ID is usually stored in a cookie on the client side to identify the session.
  • Management: Managed by the server. The session data is linked to a session ID, which the browser sends with each request.
  • Use Case: Suited for storing more sensitive or larger amounts of data that shouldn't be exposed to or managed by the client.
  • Security: More secure as the data is stored server-side. The main risk is session hijacking, which can be mitigated by secure transmission of the session ID.

Example Code

from flask import Flask, session, redirect, url_for, request

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # Set a secret key for session management

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''
        <form method="post">
            <p><input type=text name=username>
            <p><input type=submit value=Login>
        </form>
    '''

@app.route('/')
def index():
    if 'username' in session:
        return f'Logged in as {session["username"]}'
    return 'You are not logged in'

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run()

Golang

func incrHandler(c *gin.Context) {
	session := sessions.Default(c)

	var count int
	v := session.Get("count")
	if v == nil {
		count = 0
	} else {
		count = v.(int)
		count++
	}
	session.Set("count", count)
	session.Save()

	c.JSON(200, gin.H{"count": count})
}

session hijacking

Security Concern

  1. We should assume that the sessionID in the user's local computer is safe.
  2. As for the interception issue, we can ignore that due to the popularization of HTTPS.