slide1 l.
Skip this Video
Loading SlideShow in 5 Seconds..
Django Authentication PowerPoint Presentation
Download Presentation
Django Authentication

Loading in 2 Seconds...

play fullscreen
1 / 38

Django Authentication - PowerPoint PPT Presentation

  • Uploaded on

Cookies, Sessions, Users, and Registration CMPT 170 Spring 2009, SFU Surrey (based on Chapter 14 of The Django Book) ‏ Django Authentication The Problem with HTTP HTTP is a stateless protocol From the server's point of view, no connection whatsoever between different HTTP requests

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

Django Authentication

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Cookies, Sessions, Users, and RegistrationCMPT 170 Spring 2009, SFU Surrey(based on Chapter 14 of The Django Book)‏Django Authentication
the problem with http
The Problem with HTTP
  • HTTP is a stateless protocol
    • From the server's point of view, no connection whatsoever between different HTTP requests
  • This is a big problem when it comes handling user accounts
  • We want a user to be able to login to a website and do things to their account that only they can do
the solution cookies

HTTP/1.1 200 OK

Content-Type: text/html

Set-Cookie: PREF=ID=5b14f22bdaf1e81c:TM=1167000671:LM=1167000671;

expires=Sun, 17-Jan-2038 19:14:07 GMT;


Server: GWS/2.1


The Solution: Cookies


GET / HTTP/1.1



  • Websites often send your browsers unique cookies
  • A cookie is just a small amount of data, usually a string
  • Cookies can be used to identify who you are to the server in later requests

GET / HTTP/1.1


Cookie: PREF=ID=5b14f22bdaf1e81c:TM=1167000671:LM=1167000671


getting and setting cookies
Getting and Setting Cookies
  • Django makes it easy to get/set cookies directly
  • However, dealing directly with cookies is very low-level
  • It's usually preferable to instead use high-level applications that set cookies behind the scenes
    • This is what we will be doing with authentication
getting cookies in django
Getting Cookies in Django

def show_color(request):

if "favorite_color" in request.COOKIES:

return HttpResponse("Your favorite color is %s" % \



return HttpResponse("No favorite color.")‏

A view's request object stores cookies in a dictionary called COOKIES.

setting cookies in django
Setting Cookies in Django

def set_color(request):

if "favorite_color" in request.GET:

response = HttpResponse("favorite color = %s" % \




return response


return HttpResponse("No color given!")‏

a few cookie options
A Few Cookie Options
  • max_age: Age (in seconds) that the cookie should last. If this parameter is None, the cookie will last only until the browser is closed.
  • expires: The actual date/time when the cookie should expire. If given, this parameter overrides the max_age parameter.
  • secure: If set to True, this parameter instructs the browser to only return this cookie to pages accessed over HTTPS.
pros and cons of cookies
Pros and Cons of Cookies
  • They work! Everyone uses them!
  • They are not programs; they store data only
  • However
    • Cookies are not secure unless sent via HTTPS
    • Browsers let users manage cookies, so there is no guarantee a browser will accept your site's cookies
    • Browsers/user could modify cookies in any way they want at any time --- so don't store important information in them!
      • Cookie poisoning
some cookie limit
Some Cookie Limit
  • Browsers limit how many cookies from any one domain they will store
    • Firefox 2/IE 6/IE 7: 50 cookies per domain
    • Opera 9: 30 cookies per domain
  • Cookies must be less than 4KB each
    • IE limits the sum of the sizes of all cookies from a single domain to be 4KB
third party cookies
Third-party Cookies
  • Web advertisers often set cookies (via image downloadss) that can track you across multiple websites
  • Thus they can build a profile of your browsing habits to send you targetted ads
  • These raise serious privacy issues
  • Many web browsers let you deny 3rd party cookies --- often with no ill-effects
    • Of course, advertisers and tracking companies might not be happy about this!
alternatives to cookies
Alternatives to Cookies
  • IP addresses
    • Not so good
    • Different users/computers may share same IP address
    • IP address may change during a session (e.g. in dial-up access)‏
  • URL query strings can contain information
    • Server appends state info to URL links
    • Similar to cookies, but with more consistency/security issues
    • PHP and Java Servlets can use this approach
alternatives to cookies13
Alternatives to Cookies
  • Hidden fields in forms
    • ASP.NET can track users by storing information in hidden form fields
    • 2-32MB of data can be stored in a page's attribute
    • Each page/tab has its own
  • Flash plug-in locally stored objects
    • Similar to cookies
    • Only works if you have Flash installed
    • Different set of privacy/security controls
django s session framework
Django's Session Framework
  • A high-level way to handle store and retrieve user-specific data
  • Uses cookies, but you don't usually need to worry about them
  • Implements many best practices, so the default are generally efficient and safe
  • Sessions are installed by default in new Django projects
    • Search for 'session' to see where
using sessions
Using Sessions

# Set a session value:

request.session["fav_color"] = "blue"

# Get a session value -- this could be called in a

# different view, or many requests later (or both):

fav_color = request.session["fav_color"]

# Clear an item from the session:

del request.session["fav_color"]

# Check if the session has a given key:

if "fav_color" in request.session:


using sessions16
Using Sessions
  • Use sessions instead of cookies!
  • Use strings as the keys
    • But don't use strings like '_color' that start with an underscore: the underscore indicates a special variable
  • Don't replace request.session, i.e. this is bad:request.session = s2 # bad!!
sample usage
Sample Usage

def post_comment(request, new_comment):

if request.method != 'POST':

raise Http404('Only POSTs are allowed')‏

if request.session.get('has_commented', False):

return HttpResponse("You've already commented.")‏

c = comments.Comment(comment=new_comment)‏‏

request.session['has_commented'] = True

return HttpResponse('Thanks for your comment!')‏

simple login
Simple Login

This is not a very good way to login to a Django site. It's a simple example of how to use a session. Later we will see a better way of logging in using the authentication application.

def login(request):

if request.method != 'POST':

raise Http404('Only POSTs are allowed')‏


m = Member.objects.get(username=request.POST['username'])‏

if m.password == request.POST['password']:

request.session['member_id'] =

return HttpResponseRedirect('/you-are-logged-in/')‏

except Member.DoesNotExist:

return HttpResponse("Username/password didn't match.")‏

simple logout
Simple Logout

Again, later we will see a better way of logging out using the authentication application.

def logout(request):


del request.session['member_id']

except KeyError:


return HttpResponse("You're logged out.")‏

some session details
Some Session Details
  • Sessions are based entirely on cookies
  • They have various options you can set, such as when they expire
  • Session information is stored in the database table django_session
  • Session data is only fetched on demand: so if you don't use it, it won't access the database for it
users and authentication
Users and Authentication
  • Sessions let us store data
  • Django's user and authentication application is built on top of sessions
  • Django's authentication system handles
    • user accounts
    • groups
    • permissions
    • cookie-based user sessions
  • Authentication has two main tasks
    • Verifying that a user is who they say they are
      • e.g. by comparing a username and password to ones stored in the database
    • Verifying that a user is allowed to perform some action
      • By checking against a (database) table of permissions
basic components
Basic Components
  • Users: people registered with your site
  • Permissions: yes/no flags indication what actions a user may perform
  • Groups: a way to give multiple user the same permissions/labels
  • Messages: a way to send system messages to users
enabling authentication
Enabling Authentication
  • Django's authentication app is enabled by default
  • Search for 'auth' to see how
  • Also requires the sessions app to be installed
    • Also enabled by default
authenticated users
Authenticated Users
  • The request.user object lets us test if a user is authenticated

if request.user.is_authenticated():

# Do something for authenticated users.


# Do something for anonymous users.

some user object fields
Some User Object Fields
  • user objects have many pre-defined fields and methods, e.g.
    • username: required; 30 or fewer alphanumeric characters
    • first_name, last_name: optional
    • password: required; hash of user's password
    • is_staff: True iff user can use admin site
    • is_active: False means user can't use account (set this instead of deleting an account)‏
    • is_superuser: True iff user has all permissions
    • last_login, date_joined
some user object methods
Some User Object Methods
  • is_authenticated(): True iff user is authenticated
  • is_anonymous(): True iff user is not authenticated
  • set_password(passwd): change the user's password
  • check_password(passwd): compare to user's password
  • get_all_permissions(): return a list of all user's permission strings
loggin in and out
Loggin in and out
  • Logging in and logging out is so common that Django provide's pre-written views for both
  • However, it is first useful to see how to do logging in/out manually ...
manual login
Manual Login

from django.contrib import auth

def login_view(request):

uname = request.POST.get('username', '')‏

passwd = request.POST.get('password', '')‏

user = auth.authenticate(username=uname, password=passwd)‏

if user is not None and user.is_active:

# Correct password, and the user is marked "active"

auth.login(request, user)‏

# Redirect to a success page.

return HttpResponseRedirect("/account/loggedin/")‏

else: # Show an error page

return HttpResponseRedirect("/account/invalid/")‏

manual logout
Manual Logout

from django.contrib import auth

def logout_view(request):


# Redirect to a success page.

return HttpResponseRedirect("/account/loggedout/")‏

generic login
Generic Login
  • Most Django sites use the generic login/logout views


from django.contrib.auth.views import login, logout

urlpatterns = patterns('',

# ...

(r'^accounts/login/$', login),

(r'^accounts/logout/$', logout),


login and logout templates
Login and Logout Templates
  • The default login expects a login template at registration/login.html
  • The default login expects a login template at registration/logged_out.html
  • See chapter 14 of the Django book for more information on these methods (‏
  • Here's a sample of what the login template might look like ...
sample login template
Sample Login Template

{% if form.errors %}

<p class="error">Invalid username or password</p>

{% endif %}

<form action='.' method='post'>

<label for="username">User name:</label>

<input type="text" name="username" value="" id="username">

<label for="password">Password:</label>

<input type="password" name="password" value="" id="password">

<input type="submit" value="login" />

<input type="hidden" name="next" value="{{ next|escape }}" />

<form action='.' method='post'>

limiting access
Limiting Access
  • We have two main ways to limit access of anonymous (non-authenticated users)‏
  • One way is to check with an if-statement:

from django.http import HttpResponseRedirect

def my_view(request):

if not request.user.is_authenticated():

return HttpResponseRedirect('/login/?next=%s' % request.path)‏

# ...

limiting access35
Limiting Access
  • The other way is to use a decorator:

from django.contrib.auth.decorators import login_required


def my_view(request):

# ...

If the user is not logged in, this re-directs to /accounts/login

creating users
Creating Users
  • Can create users via the admin interface
  • Or programmatically:

>>> from django.contrib.auth.models import User

>>> user = User.objects.create_user(username='john',email='', password='glass onion')‏

changing passwords
Changing Passwords

>>> user = User.objects.get(username='john')‏

>>> user.set_password('goo goo goo joob')‏


Passwords are stored as salted hashes, so you shouldn't set them directly unless you understand what this means in detail!

  • You will almost always want to use the standard Django ways of handling users
  • Security is harder than you might think, and so you not do it yourself unless you know what you are doing
  • For more details, see chapter 14 of the Django book: