SlideShare a Scribd company logo
1 of 45
Cookies, Sessions and
User Authentication

     Thierry Sans
Today, we will



•   bake cookies

•   and use cookies to implement sessions

•   and use sessions to authenticate users

•   and define user’s permissions
Before we start
Security assumptions



Client Side                         Server Side




Web Browser            Web Server       Database
Security assumptions
                       You have absolutely no control
                       on the client


Client Side                                   Server Side




Web Browser                      Web Server       Database
Cookies
The big picture


                   key/value pairs data
Client Side                                         Server Side
                                     HTTP request

                          HTTP response
                                     HTTP request

                          HTTP response



Web Browser                                           Web Server
Cookies




•   Cookies are pieces of data sent back and forth between
    the browser and the server in HTTP request and response
Anatomy of a Cookie




•   Text data (Up to 4kb)

•   May (or may not) have an expiration date

•   Can be manipulated from the client and the server
What cookies are useful for?



•   Shopping cart

•   Browsing preferences

•   “Remember me on this computer”

•   User authentication
Manipulating cookies




•   A cookie can be modified

    •   on the server side - Django

    •   on the client side - jQuery Cookie plugin
Remember the search input (in Javascript)

                                             WebDirectory/static/js/init.js
   function search(){
       var input = $.trim($("input[name='search']").val());
       $.cookie('keywords', input);


                              storing data
                                             WebDirectory/static/js/init.js
   function init(){
     if ($.cookie("keywords")){
       $("input[name='search']").val($.cookie("keywords"));
       search();
     }
   }
                                        retrieving data
Remember the number of visits (in Django)

                                               WebDirectory/views.py
 def index(request):
   entry_list = Entry.objects.all()      retrieving data
   if 'nb_visits' in request.COOKIES:
       n = int(request.COOKIES['nb_visits']) + 1
   else:
       n = 1
   response = render_to_response('WebDirectory/index.html',
                   {'entry_list': entry_list, 'nb_visits': n})
   response.set_cookie('nb_visits', value=n,
                        max_age=None, expires=None,
                        path='/webdirectory/', domain=None,
                        secure=None, httponly=False)
   return response

                                      storing data
Firefox - debugging (and hacking) cookies
Hacking cookies




The user can create, modify, delete key/value pairs in cookies
Sessions
The big picture


                   session id
Client Side                                   Server Side
                              HTTP request

                   HTTP response
                              HTTP request

                   HTTP response



Web Browser                                     Web Server

                       key/value pairs data
The concept of session



•   There is a session id (aka token)
    between the browser and the web application

•   This session id should be unique and unforgeable
    (usually a long random number or a hash)

•   This session id is bind to key/value pairs data
Where sessions values are stored




•   Session ID is stored in a cookie

•   Session key/value pairs are stored on the server


                                       in the database
                                       with Django
Remember the number of visits using sessions


                                               WebDirectory/views.py
 def index(request):
   if 'nb_visits' in request.session:
           n = int(request.session['nb_visits']) + 1
   else:
           n = 1                           retrieving data
   request.session['nb_visits'] = n
   response = render_to_response('WebDirectory/index.html',
                   {'entry_list': entry_list, 'nb_visits': n})
   return response


             storing data
Hacking sessions




The user can create, modify, delete the session ID in the cookie

But cannot access the key/value pairs stored on the server
Clearing the session

              delete the cookie
 Dirty
              (but the session values are still on the server)


              use flush() in the view to delete the current
 Program
              session data and regenerate the session key

         django-admin.py cleanup
 Command deletes any session in the session table whose
         expire_date is in the past
User Authentication
The simple recipe for user authentication


1. Ask the user for a login and password and send it
   to the server (HTTP/POST request)

2. Verify the login/password based on information
   stored on the server (usually in the database)

3. Start a session if the login password matches i.e. once
   the user has been successfully authenticated

4. Grant access to resources according to the session
Django login/logout urls


               Django predefined login view
                                                    WebDirectory/urls.py
urlpatterns += patterns('',
    (r'^login/$',    'django.contrib.auth.views.login',
                    {'template_name': 'WebDirectory/login.html'}),
    (r'^logout/$', 'WebDirectory.views.logout_view'))


                                          User’s defined login page

     User defined logout view
Or your can manage your own login view
                                                          example
from django.contrib.auth import authenticate, login


def login_view(request):
   username = request.POST['username']
   password = request.POST['password']
   user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            # Return a 'disabled account' error message
    else:
       # Return an 'invalid login' error message.
Logout


                                                     WebDirectory/views.py
from django.contrib.auth import logout


def logout_view(request):
   logout(request)
    return HttpResponseRedirect(reverse('WebDirectory.views.index',))
Protecting resources




•   Certain views might be accessible by the authenticated users
    only
Version 1 - using the template




{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}. Thanks for logging in.</p>
{% else %}
    <p>Welcome, new user. Please log in.</p>
{% endif %}
Version 2 - using the views




def index(request):
    if request.user.is_authenticated():
       # Do something for authenticated users.
    else:
       # Do something for anonymous users.
Version 3 - using a decorator in the view




from django.contrib.auth.decorators import login_required


@login_required(login_url='/myapp/login/')
def index(request):
   # Do something for authenticated users.
WebDirectory - security policy




1. Only authenticated users can see the web gallery
WebDirectory


                                                    WebDirectory/views.py
@login_required(login_url='/webdirectory/login/')
def index(request):
  entry_list = Entry.objects.all()
  ...
WebDirectory


                                                    WebDirectory/views.py
@login_required(login_url='/webdirectory/login/')
def index(request):
  entry_list = Entry.objects.all()
  ...



               But, we must also protect all the other views:
               • getImage
               • add
               • search
Authorization
WebDirectory - security policy




1. Only authenticated users can see the web gallery

2. Only the admin user “tsans” can add a new entry
Version 0 - hide the upload button (template)

                                 WebDirectory/templates/WebDirectoryindex.html

{% if admin %}
   <a href="#" id="publisherButton"
                 onclick="showHideUploader();return false;">
   Show uploader
   </a>
   <div id="publisher">
          ...
          ...
   </div>
{% endif %}
Version 0 -hide the upload button (view)


                                                WebDirectory/views.py
@login_required(login_url='/webdirectory/login/')
def index(request):
  entry_list = Entry.objects.all()
  ...
  return render_to_response('WebDirectory/index.html',
                            {'entry_list': entry_list,
                              request.user.username=='tsans'})
Version 0 -hide the upload button (view)


                                                 WebDirectory/views.py
@login_required(login_url='/webdirectory/login/')
def index(request):
  entry_list = Entry.objects.all()
  ...
  return render_to_response('WebDirectory/index.html',
                             {'entry_list': entry_list,
                               request.user.username=='tsans'})



                      This is absolutely not secure enough !!!
Version 1 - protecting the view


                                                WebDirectory/views.py

@login_required(login_url='/webdirectory/login/')
def add(request):
 if (request.user.username == 'tsans')
        # add the entry to the database
    else:
        raise Http500
Django permissions



•   Based on the Django admin features, the model Entity
    predefines 3 permissions:

    •   Entry.add_entry

    •   Entry.change_entry

    •   Entry.delete_entry
Version 2 - using permissions in the view


                                                    WebDirectory/views.py

@login_required(login_url='/webdirectory/login/')
def add(request):
 if request.user.has_perm('Entry.add_entity'):
        # add the entry to the database
    else:
        raise Http500
Version 3 - - using a decorator in the view




                                          WebDirectory/views.py

@permission_required('Entry.add_entry')
def add(request):
  # add the entry to the database
Define custom permissions


                                                            example

class Task(models.Model):
 ...
  class Meta:
    permissions = (
        ("view_task", "Can see available tasks"),
        ("change_task_status", "Can change the status of tasks"),
        ("close_task", "Can close a task"),
    )
Summary




•   What is the difference between a cookie and a session?

•   How are users authenticated?

•   What is the difference between authentication and
    authorization?

More Related Content

What's hot

C2 Matrix A Comparison of Command and Control Frameworks
C2 Matrix A Comparison of Command and Control FrameworksC2 Matrix A Comparison of Command and Control Frameworks
C2 Matrix A Comparison of Command and Control FrameworksJorge Orchilles
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)Arjun Shanka
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?FITC
 
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web ServicesXXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web ServicesAbraham Aranguren
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional StatementsMarlon Jamera
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Expressjguerrero999
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The BasicsJeff Fox
 
ORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMMikhail Egorov
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Codemotion
 

What's hot (20)

Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
C2 Matrix A Comparison of Command and Control Frameworks
C2 Matrix A Comparison of Command and Control FrameworksC2 Matrix A Comparison of Command and Control Frameworks
C2 Matrix A Comparison of Command and Control Frameworks
 
Cookie and session
Cookie and sessionCookie and session
Cookie and session
 
Php session
Php sessionPhp session
Php session
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Why TypeScript?
Why TypeScript?Why TypeScript?
Why TypeScript?
 
Java script arrays
Java script arraysJava script arrays
Java script arrays
 
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web ServicesXXE Exposed: SQLi, XSS, XXE and XEE against Web Services
XXE Exposed: SQLi, XSS, XXE and XEE against Web Services
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional Statements
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Javascript
JavascriptJavascript
Javascript
 
Input Validation
Input ValidationInput Validation
Input Validation
 
Node Architecture and Getting Started with Express
Node Architecture and Getting Started with ExpressNode Architecture and Getting Started with Express
Node Architecture and Getting Started with Express
 
Json
JsonJson
Json
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
ORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORMORM2Pwn: Exploiting injections in Hibernate ORM
ORM2Pwn: Exploiting injections in Hibernate ORM
 
Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...Secure Coding principles by example: Build Security In from the start - Carlo...
Secure Coding principles by example: Build Security In from the start - Carlo...
 
Css selectors
Css selectorsCss selectors
Css selectors
 
4.2 PHP Function
4.2 PHP Function4.2 PHP Function
4.2 PHP Function
 

Viewers also liked

Files
FilesFiles
Filessoon
 
Keller Williams Realty
Keller Williams RealtyKeller Williams Realty
Keller Williams RealtyRickBosl
 
Admin
AdminAdmin
Adminsoon
 
October - Corporatre Presentation
October - Corporatre PresentationOctober - Corporatre Presentation
October - Corporatre Presentationglevel
 
Google
GoogleGoogle
Googlesoon
 
Deploying
DeployingDeploying
Deployingsoon
 

Viewers also liked (8)

Files
FilesFiles
Files
 
Keller Williams Realty
Keller Williams RealtyKeller Williams Realty
Keller Williams Realty
 
Wedium coffav
Wedium coffavWedium coffav
Wedium coffav
 
Admin
AdminAdmin
Admin
 
October - Corporatre Presentation
October - Corporatre PresentationOctober - Corporatre Presentation
October - Corporatre Presentation
 
Fostering Online Networks
Fostering Online NetworksFostering Online Networks
Fostering Online Networks
 
Google
GoogleGoogle
Google
 
Deploying
DeployingDeploying
Deploying
 

Similar to Authentication

How to Build an Indivo X Personal Health App
How to Build an Indivo X Personal Health AppHow to Build an Indivo X Personal Health App
How to Build an Indivo X Personal Health AppBen Adida
 
Code your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard LearnCode your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard LearnDan Rinzel
 
ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3Neeraj Mathur
 
Introduction Yii Framework
Introduction Yii FrameworkIntroduction Yii Framework
Introduction Yii FrameworkTuan Nguyen
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfHumphreyOwuor1
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code HardeningOdoo
 
Passwords suck, but centralized proprietary services are not the answer
Passwords suck, but centralized proprietary services are not the answerPasswords suck, but centralized proprietary services are not the answer
Passwords suck, but centralized proprietary services are not the answerFrancois Marier
 
Automating Django Functional Tests Using Selenium on Cloud
Automating Django Functional Tests Using Selenium on CloudAutomating Django Functional Tests Using Selenium on Cloud
Automating Django Functional Tests Using Selenium on CloudJonghyun Park
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigWake Liu
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSmurtazahaveliwala
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5Tieturi Oy
 
Persona: in your browsers, killing your passwords
Persona: in your browsers, killing your passwordsPersona: in your browsers, killing your passwords
Persona: in your browsers, killing your passwordsFrancois Marier
 
Let's read code: the python-requests library
Let's read code: the python-requests libraryLet's read code: the python-requests library
Let's read code: the python-requests librarySusan Tan
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Luka Zakrajšek
 
How to Use Stormpath in angular js
How to Use Stormpath in angular jsHow to Use Stormpath in angular js
How to Use Stormpath in angular jsStormpath
 
Ruby on Rails Security Guide
Ruby on Rails Security GuideRuby on Rails Security Guide
Ruby on Rails Security Guideihji
 

Similar to Authentication (20)

How to Build an Indivo X Personal Health App
How to Build an Indivo X Personal Health AppHow to Build an Indivo X Personal Health App
How to Build an Indivo X Personal Health App
 
Ecom2
Ecom2Ecom2
Ecom2
 
Code your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard LearnCode your Own: Authentication Provider for Blackboard Learn
Code your Own: Authentication Provider for Blackboard Learn
 
ASP.Net Presentation Part3
ASP.Net Presentation Part3ASP.Net Presentation Part3
ASP.Net Presentation Part3
 
Introduction Yii Framework
Introduction Yii FrameworkIntroduction Yii Framework
Introduction Yii Framework
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
 
Rails Security
Rails SecurityRails Security
Rails Security
 
Security: Odoo Code Hardening
Security: Odoo Code HardeningSecurity: Odoo Code Hardening
Security: Odoo Code Hardening
 
Passwords suck, but centralized proprietary services are not the answer
Passwords suck, but centralized proprietary services are not the answerPasswords suck, but centralized proprietary services are not the answer
Passwords suck, but centralized proprietary services are not the answer
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
 
Automating Django Functional Tests Using Selenium on Cloud
Automating Django Functional Tests Using Selenium on CloudAutomating Django Functional Tests Using Selenium on Cloud
Automating Django Functional Tests Using Selenium on Cloud
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # Twig
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
 
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5TechDays 2013 Jari Kallonen: What's New WebForms 4.5
TechDays 2013 Jari Kallonen: What's New WebForms 4.5
 
Persona: in your browsers, killing your passwords
Persona: in your browsers, killing your passwordsPersona: in your browsers, killing your passwords
Persona: in your browsers, killing your passwords
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Let's read code: the python-requests library
Let's read code: the python-requests libraryLet's read code: the python-requests library
Let's read code: the python-requests library
 
Django Class-based views (Slovenian)
Django Class-based views (Slovenian)Django Class-based views (Slovenian)
Django Class-based views (Slovenian)
 
How to Use Stormpath in angular js
How to Use Stormpath in angular jsHow to Use Stormpath in angular js
How to Use Stormpath in angular js
 
Ruby on Rails Security Guide
Ruby on Rails Security GuideRuby on Rails Security Guide
Ruby on Rails Security Guide
 

Recently uploaded

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Recently uploaded (20)

What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

Authentication

  • 1. Cookies, Sessions and User Authentication Thierry Sans
  • 2. Today, we will • bake cookies • and use cookies to implement sessions • and use sessions to authenticate users • and define user’s permissions
  • 4. Security assumptions Client Side Server Side Web Browser Web Server Database
  • 5. Security assumptions You have absolutely no control on the client Client Side Server Side Web Browser Web Server Database
  • 7. The big picture key/value pairs data Client Side Server Side HTTP request HTTP response HTTP request HTTP response Web Browser Web Server
  • 8. Cookies • Cookies are pieces of data sent back and forth between the browser and the server in HTTP request and response
  • 9. Anatomy of a Cookie • Text data (Up to 4kb) • May (or may not) have an expiration date • Can be manipulated from the client and the server
  • 10. What cookies are useful for? • Shopping cart • Browsing preferences • “Remember me on this computer” • User authentication
  • 11. Manipulating cookies • A cookie can be modified • on the server side - Django • on the client side - jQuery Cookie plugin
  • 12. Remember the search input (in Javascript) WebDirectory/static/js/init.js function search(){ var input = $.trim($("input[name='search']").val()); $.cookie('keywords', input); storing data WebDirectory/static/js/init.js function init(){ if ($.cookie("keywords")){ $("input[name='search']").val($.cookie("keywords")); search(); } } retrieving data
  • 13. Remember the number of visits (in Django) WebDirectory/views.py def index(request): entry_list = Entry.objects.all() retrieving data if 'nb_visits' in request.COOKIES: n = int(request.COOKIES['nb_visits']) + 1 else: n = 1 response = render_to_response('WebDirectory/index.html', {'entry_list': entry_list, 'nb_visits': n}) response.set_cookie('nb_visits', value=n, max_age=None, expires=None, path='/webdirectory/', domain=None, secure=None, httponly=False) return response storing data
  • 14. Firefox - debugging (and hacking) cookies
  • 15. Hacking cookies The user can create, modify, delete key/value pairs in cookies
  • 17. The big picture session id Client Side Server Side HTTP request HTTP response HTTP request HTTP response Web Browser Web Server key/value pairs data
  • 18. The concept of session • There is a session id (aka token) between the browser and the web application • This session id should be unique and unforgeable (usually a long random number or a hash) • This session id is bind to key/value pairs data
  • 19. Where sessions values are stored • Session ID is stored in a cookie • Session key/value pairs are stored on the server in the database with Django
  • 20. Remember the number of visits using sessions WebDirectory/views.py def index(request): if 'nb_visits' in request.session: n = int(request.session['nb_visits']) + 1 else: n = 1 retrieving data request.session['nb_visits'] = n response = render_to_response('WebDirectory/index.html', {'entry_list': entry_list, 'nb_visits': n}) return response storing data
  • 21. Hacking sessions The user can create, modify, delete the session ID in the cookie But cannot access the key/value pairs stored on the server
  • 22. Clearing the session delete the cookie Dirty (but the session values are still on the server) use flush() in the view to delete the current Program session data and regenerate the session key django-admin.py cleanup Command deletes any session in the session table whose expire_date is in the past
  • 24. The simple recipe for user authentication 1. Ask the user for a login and password and send it to the server (HTTP/POST request) 2. Verify the login/password based on information stored on the server (usually in the database) 3. Start a session if the login password matches i.e. once the user has been successfully authenticated 4. Grant access to resources according to the session
  • 25. Django login/logout urls Django predefined login view WebDirectory/urls.py urlpatterns += patterns('', (r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'WebDirectory/login.html'}), (r'^logout/$', 'WebDirectory.views.logout_view')) User’s defined login page User defined logout view
  • 26. Or your can manage your own login view example from django.contrib.auth import authenticate, login def login_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) # Redirect to a success page. else: # Return a 'disabled account' error message else: # Return an 'invalid login' error message.
  • 27. Logout WebDirectory/views.py from django.contrib.auth import logout def logout_view(request): logout(request) return HttpResponseRedirect(reverse('WebDirectory.views.index',))
  • 28. Protecting resources • Certain views might be accessible by the authenticated users only
  • 29. Version 1 - using the template {% if user.is_authenticated %} <p>Welcome, {{ user.username }}. Thanks for logging in.</p> {% else %} <p>Welcome, new user. Please log in.</p> {% endif %}
  • 30. Version 2 - using the views def index(request): if request.user.is_authenticated(): # Do something for authenticated users. else: # Do something for anonymous users.
  • 31. Version 3 - using a decorator in the view from django.contrib.auth.decorators import login_required @login_required(login_url='/myapp/login/') def index(request): # Do something for authenticated users.
  • 32. WebDirectory - security policy 1. Only authenticated users can see the web gallery
  • 33. WebDirectory WebDirectory/views.py @login_required(login_url='/webdirectory/login/') def index(request): entry_list = Entry.objects.all() ...
  • 34. WebDirectory WebDirectory/views.py @login_required(login_url='/webdirectory/login/') def index(request): entry_list = Entry.objects.all() ... But, we must also protect all the other views: • getImage • add • search
  • 36. WebDirectory - security policy 1. Only authenticated users can see the web gallery 2. Only the admin user “tsans” can add a new entry
  • 37. Version 0 - hide the upload button (template) WebDirectory/templates/WebDirectoryindex.html {% if admin %} <a href="#" id="publisherButton" onclick="showHideUploader();return false;"> Show uploader </a> <div id="publisher"> ... ... </div> {% endif %}
  • 38. Version 0 -hide the upload button (view) WebDirectory/views.py @login_required(login_url='/webdirectory/login/') def index(request): entry_list = Entry.objects.all() ... return render_to_response('WebDirectory/index.html', {'entry_list': entry_list, request.user.username=='tsans'})
  • 39. Version 0 -hide the upload button (view) WebDirectory/views.py @login_required(login_url='/webdirectory/login/') def index(request): entry_list = Entry.objects.all() ... return render_to_response('WebDirectory/index.html', {'entry_list': entry_list, request.user.username=='tsans'}) This is absolutely not secure enough !!!
  • 40. Version 1 - protecting the view WebDirectory/views.py @login_required(login_url='/webdirectory/login/') def add(request): if (request.user.username == 'tsans') # add the entry to the database else: raise Http500
  • 41. Django permissions • Based on the Django admin features, the model Entity predefines 3 permissions: • Entry.add_entry • Entry.change_entry • Entry.delete_entry
  • 42. Version 2 - using permissions in the view WebDirectory/views.py @login_required(login_url='/webdirectory/login/') def add(request): if request.user.has_perm('Entry.add_entity'): # add the entry to the database else: raise Http500
  • 43. Version 3 - - using a decorator in the view WebDirectory/views.py @permission_required('Entry.add_entry') def add(request): # add the entry to the database
  • 44. Define custom permissions example class Task(models.Model): ... class Meta: permissions = ( ("view_task", "Can see available tasks"), ("change_task_status", "Can change the status of tasks"), ("close_task", "Can close a task"), )
  • 45. Summary • What is the difference between a cookie and a session? • How are users authenticated? • What is the difference between authentication and authorization?

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n