The Flask Mega-Tutorial Part V: User Logins

This is the fifth installment of the Flask Mega-Tutorial series, in which I'm going to tell you how to create a user login subsystem.

For your reference, below is a list of the articles in this series.

Note 1: If you are looking for the legacy version of this tutorial, it's here.

Note 2: If you would like to support my work on this blog, or just don't have patience to wait for weekly articles, I am offering the complete version of this tutorial packaged as an ebook or a set of videos. For more information, visit courses.miguelgrinberg.com.

In Chapter 3 you learned how to create the user login form, and in Chapter 4 you learned how to work with a database. This chapter will teach you how to combine the topics from those two chapters to create a simple user login system.

The GitHub links for this chapter are: Browse, Zip, Diff.

Password Hashing

In Chapter 4 the user model was given a password_hash field, that so far is unused. The purpose of this field is to hold a hash of the user password, which will be used to verify the password entered by the user during the log in process. Password hashing is a complicated topic that should be left to security experts, but there are several easy to use libraries that implement all that logic in a way that is simple to be invoked from an application.

One of the packages that implement password hashing is Werkzeug, which you may have seen referenced in the output of pip when you install Flask, since it is one of its core dependencies. Since it is a dependency, Werkzeug is already installed in your virtual environment. The following Python shell session demonstrates how to hash a password:

>>> from werkzeug.security import generate_password_hash
>>> hash = generate_password_hash('foobar')
>>> hash

In this example, the password foobar is transformed into a long encoded string through a series of cryptographic operations that have no known reverse operation, which means that a person that obtains the hashed password will be unable to use it to obtain the original password. As an additional measure, if you hash the same password multiple times, you will get different results, so this makes it impossible to identify if two users have the same password by looking at their hashes.

The verification process is done with a second function from Werkzeug, as follows:

>>> from werkzeug.security import check_password_hash
>>> check_password_hash(hash, 'foobar')
>>> check_password_hash(hash, 'barfoo')

The verification function takes a password hash that was previously generated, and a password entered by the user at the time of log in. The function returns True if the password provided by the user matches the hash, or False otherwise.

The whole password hashing logic can be implemented as two new methods in the user model:

app/models.py: Password hashing and verification

from werkzeug.security import generate_password_hash, check_password_hash

# ...

class User(db.Model):
    # ...

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

With these two methods in place, a user object is now able to do secure password verification, without the need to ever store original passwords. Here is an example usage of these new methods:

>>> u = User(username='susan', email='susan@example.com')
>>> u.set_password('mypassword')
>>> u.check_password('anotherpassword')
>>> u.check_password('mypassword')

Introduction to Flask-Login

In this chapter I'm going to introduce you to a very popular Flask extension called Flask-Login. This extension manages the user logged-in state, so that for example users can log in to the application and then navigate to different pages while the application "remembers" that the user is logged in. It also provides the "remember me" functionality that allows users to remain logged in even after closing the browser window. To be ready for this chapter, you can start by installing Flask-Login in your virtual environment:

(venv) $ pip install flask-login

As with other extensions, Flask-Login needs to be created and initialized right after the application instance in app/__init__.py. This is how this extension is initialized:

app/__init__.py: Flask-Login initialization

# ...
from flask_login import LoginManager

app = Flask(__name__)
# ...
login = LoginManager(app)

# ...

Preparing The User Model for Flask-Login

The Flask-Login extension works with the application's user model, and expects certain properties and methods to be implemented in it. This approach is nice, because as long as these required items are added to the model, Flask-Login does not have any other requirements, so for example, it can work with user models that are based on any database system.

The four required items are listed below:

  • is_authenticated: a property that is True if the user has valid credentials or False otherwise.
  • is_active: a property that is True if the user's account is active or False otherwise.
  • is_anonymous: a property that is False for regular users, and True for a special, anonymous user.
  • get_id(): a method that returns a unique identifier for the user as a string (unicode, if using Python 2).

I can implement these four easily, but since the implementations are fairly generic, Flask-Login provides a mixin class called UserMixin that includes generic implementations that are appropriate for most user model classes. Here is how the mixin class is added to the model:

app/models.py: Flask-Login user mixin class

# ...
from flask_login import UserMixin

class User(UserMixin, db.Model):
    # ...

User Loader Function

Flask-Login keeps track of the logged in user by storing its unique identifier in Flask's user session, a storage space assigned to each user who connects to the application. Each time the logged-in user navigates to a new page, Flask-Login retrieves the ID of the user from the session, and then loads that user into memory.

Because Flask-Login knows nothing about databases, it needs the application's help in loading a user. For that reason, the extension expects that the application will configure a user loader function, that can be called to load a user given the ID. This function can be added in the app/models.py module:

app/models.py: Flask-Login user loader function

from app import login
# ...

def load_user(id):
    return User.query.get(int(id))

The user loader is registered with Flask-Login with the @login.user_loader decorator. The id that Flask-Login passes to the function as an argument is going to be a string, so databases that use numeric IDs need to convert the string to integer as you see above.

Logging Users In

Let's revisit the login view function, which as you recall, implemented a fake login that just issued a flash() message. Now that the application has access to a user database and knows how to generate and verify password hashes, this view function can be completed.

app/routes.py: Login view function logic

# ...
from flask_login import current_user, login_user
from app.models import User

# ...

@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=form)

The top two lines in the login() function deal with a weird situation. Imagine you have a user that is logged in, and the user navigates to the /login URL of your application. Clearly that is a mistake, so I want to not allow that. The current_user variable comes from Flask-Login and can be used at any time during the handling to obtain the user object that represents the client of the request. The value of this variable can be a user object from the database (which Flask-Login reads through the user loader callback I provided above), or a special anonymous user object if the user did not log in yet. Remember those properties that Flask-Login required in the user object? One of those was is_authenticated, which comes in handy to check if the user is logged in or not. When the user is already logged in, I just redirect to the index page.

In place of the flash() call that I used earlier, now I can log the user in for real. The first step is to load the user from the database. The username came with the form submission, so I can query the database with that to find the user. For this purpose I'm using the filter_by() method of the SQLAlchemy query object. The result of filter_by() is a query that only includes the objects that have a matching username. Since I know there is only going to be one or zero results, I complete the query by calling first(), which will return the user object if it exists, or None if it does not. In Chapter 4 you have seen that when you call the all() method in a query, the query executes and you get a list of all the results that match that query. The first() method is another commonly used way to execute a query, when you only need to have one result.

If I got a match for the username that was provided, I can next check if the password that also came with the form is valid. This is done by invoking the check_password() method I defined above. This will take the password hash stored with the user and determine if the password entered in the form matches the hash or not. So now I have two possible error conditions: the username can be invalid, or the password can be incorrect for the user. In either of those cases, I flash a message, and redirect back to the login prompt so that the user can try again.

If the username and password are both correct, then I call the login_user() function, which comes from Flask-Login. This function will register the user as logged in, so that means that any future pages the user navigates to will have the current_user variable set to that user.

To complete the login process, I just redirect the newly logged-in user to the index page.

Logging Users Out

I know I will also need to offer users the option to log out of the application. This can be done with Flask-Login's logout_user() function. Here is the logout view function:

app/routes.py: Logout view function

# ...
from flask_login import logout_user

# ...

def logout():
    return redirect(url_for('index'))

To expose this link to users, I can make the Login link in the navigation bar automatically switch to a Logout link after the user logs in. This can be done with a conditional in the base.html template:

app/templates/base.html: Conditional login and logout links

        <a href="{{ url_for('index') }}">Home</a>
        {% if current_user.is_anonymous %}
        <a href="{{ url_for('login') }}">Login</a>
        {% else %}
        <a href="{{ url_for('logout') }}">Logout</a>
        {% endif %}

The is_anonymous property is one of the attributes that Flask-Login adds to user objects through the UserMixin class. The current_user.is_anonymous expression is going to be True only when the user is not logged in.

Requiring Users To Login

Flask-Login provides a very useful feature that forces users to log in before they can view certain pages of the application. If a user who is not logged in tries to view a protected page, Flask-Login will automatically redirect the user to the login form, and only redirect back to the page the user wanted to view after the login process is complete.

For this feature to be implemented, Flask-Login needs to know what is the view function that handles logins. This can be added in app/__init__.py:

# ...
login = LoginManager(app)
login.login_view = 'login'

The 'login' value above is the function (or endpoint) name for the login view. In other words, the name you would use in a url_for() call to get the URL.

The way Flask-Login protects a view function against anonymous users is with a decorator called @login_required. When you add this decorator to a view function below the @app.route decorators from Flask, the function becomes protected and will not allow access to users that are not authenticated. Here is how the decorator can be applied to the index view function of the application:

app/routes.py: @login\_required decorator

from flask_login import login_required

def index():
    # ...

What remains is to implement the redirect back from the successful login to the page the user wanted to access. When a user that is not logged in accesses a view function protected with the @login_required decorator, the decorator is going to redirect to the login page, but it is going to include some extra information in this redirect so that the application can then return to the first page. If the user navigates to /index, for example, the @login_required decorator will intercept the request and respond with a redirect to /login, but it will add a query string argument to this URL, making the complete redirect URL /login?next=/index. The next query string argument is set to the original URL, so the application can use that to redirect back after login.

Here is a snippet of code that shows how to read and process the next query string argument:

app/routes.py: Redirect to "next" page

from flask import request
from werkzeug.urls import url_parse

@app.route('/login', methods=['GET', 'POST'])
def login():
    # ...
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('Invalid username or password')
            return redirect(url_for('login'))
        login_user(user, remember=form.remember_me.data)
        next_page = request.args.get('next')
        if not next_page or url_parse(next_page).netloc != '':
            next_page = url_for('index')
        return redirect(next_page)
    # ...

Right after the user is logged in by calling Flask-Login's login_user() function, the value of the next query string argument is obtained. Flask provides a request variable that contains all the information that the client sent with the request. In particular, the request.args attribute exposes the contents of the query string in a friendly dictionary format. There are actually three possible cases that need to be considered to determine where to redirect after a successful login:

  • If the login URL does not have a next argument, then the user is redirected to the index page.
  • If the login URL includes a next argument that is set to a relative path (or in other words, a URL without the domain portion), then the user is redirected to that URL.
  • If the login URL includes a next argument that is set to a full URL that includes a domain name, then the user is redirected to the index page.

The first and second cases are self-explanatory. The third case is in place to make the application more secure. An attacker could insert a URL to a malicious site in the next argument, so the application only redirects when the URL is relative, which ensures that the redirect stays within the same site as the application. To determine if the URL is relative or absolute, I parse it with Werkzeug's url_parse() function and then check if the netloc component is set or not.

Showing The Logged In User in Templates

Do you recall that way back in Chapter 2 I created a fake user to help me design the home page of the application before the user subsystem was in place? Well, the application has real users now, so I can now remove the fake user and start working with real users. Instead of the fake user I can use Flask-Login's current_user in the template:

app/templates/index.html: Pass current user to template

{% extends "base.html" %}

{% block content %}
    <h1>Hi, {{ current_user.username }}!</h1>
    {% for post in posts %}
    <div><p>{{ post.author.username }} says: <b>{{ post.body }}</b></p></div>
    {% endfor %}
{% endblock %}

And I can remove the user template argument in the view function:

app/routes.py: Do not pass user to template anymore

def index():
    # ...
    return render_template("index.html", title='Home Page', posts=posts)

This is a good time to test how the login and logout functionality works. Since there is still no user registration, the only way to add a user to the database is to do it via the Python shell, so run flask shell and enter the following commands to register a user:

>>> u = User(username='susan', email='susan@example.com')
>>> u.set_password('cat')
>>> db.session.add(u)
>>> db.session.commit()

If you start the application and try to access http://localhost:5000/ or http://localhost:5000/index, you will be immediately redirected to the login page, and after you log in using the credentials of the user that you added to your database, you will be returned to the original page, in which you will see a personalized greeting.

User Registration

The last piece of functionality that I'm going to build in this chapter is a registration form, so that users can register themselves through a web form. Let's begin by creating the web form class in app/forms.py:

app/forms.py: User registration form

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo
from app.models import User

# ...

class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired()])
    email = StringField('Email', validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    password2 = PasswordField(
        'Repeat Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Register')

    def validate_username(self, username):
        user = User.query.filter_by(username=username.data).first()
        if user is not None:
            raise ValidationError('Please use a different username.')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is not None:
            raise ValidationError('Please use a different email address.')

There are a couple of interesting things in this new form related to validation. First, for the email field I've added a second validator after DataRequired, called Email. This is another stock validator that comes with WTForms that will ensure that what the user types in this field matches the structure of an email address.

The Email() validator from WTForms requires an external dependency to be installed.

(venv) $ pip install email-validator

Since this is a registration form, it is customary to ask the user to type the password two times to reduce the risk of a typo. For that reason I have password and password2 fields. The second password field uses yet another stock validator called EqualTo, which will make sure that its value is identical to the one for the first password field.

I have also added two methods to this class called validate_username() and validate_email(). When you add any methods that match the pattern validate_<field_name>, WTForms takes those as custom validators and invokes them in addition to the stock validators. In this case I want to make sure that the username and email address entered by the user are not already in the database, so these two methods issue database queries expecting there will be no results. In the event a result exists, a validation error is triggered by raising ValidationError. The message included as the argument in the exception will be the message that will be displayed next to the field for the user to see.

To display this form on a web page, I need to have an HTML template, which I'm going to store in file app/templates/register.html. This template is constructed similarly to the one for the login form:

app/templates/register.html: Registration template

{% extends "base.html" %}

{% block content %}
    <form action="" method="post">
        {{ form.hidden_tag() }}
            {{ form.username.label }}<br>
            {{ form.username(size=32) }}<br>
            {% for error in form.username.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            {{ form.email.label }}<br>
            {{ form.email(size=64) }}<br>
            {% for error in form.email.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            {{ form.password.label }}<br>
            {{ form.password(size=32) }}<br>
            {% for error in form.password.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
            {{ form.password2.label }}<br>
            {{ form.password2(size=32) }}<br>
            {% for error in form.password2.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        <p>{{ form.submit() }}</p>
{% endblock %}

The login form template needs a link that sends new users to the registration form, right below the form:

app/templates/login.html: Link to registration page

    <p>New User? <a href="{{ url_for('register') }}">Click to Register!</a></p>

And finally, I need to write the view function that is going to handle user registrations in app/routes.py:

app/routes.py: User registration view function

from app import db
from app.forms import RegistrationForm

# ...

@app.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(username=form.username.data, email=form.email.data)
        flash('Congratulations, you are now a registered user!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)

And this view function should also be mostly self-explanatory. I first make sure the user that invokes this route is not logged in. The form is handled in the same way as the one for logging in. The logic that is done inside the if validate_on_submit() conditional creates a new user with the username, email and password provided, writes it to the database, and then redirects to the login prompt so that the user can log in.

Registration Form

With these changes, users should be able to create accounts on this application, and log in and out. Make sure you try all the validation features I've added in the registration form to better understand how they work. I am going to revisit the user authentication subsystem in a future chapter to add additional functionality such as to allow the user to reset the password if forgotten. But for now, this is enough to continue building other areas of the application.


  • #101 Steve said 2018-05-29T20:53:37Z

    Basic Python question: In RegistrationForm could code be simply, if user: Rather than if user is not None: i.e., if db query returns user=None, won't Python evaluate if user as False?


  • #102 Miguel Grinberg said 2018-05-30T01:15:26Z

    @Steve: Yes, the two conditions are not exactly the same, but to test if you have a valid user they both work as well.

  • #103 Flaviu said 2018-06-05T15:46:08Z

    Hi Miguel,

    I have a problem, I need two user models in my app, let's say a client and a provider of services, they both have their own table in the database, since there are just a lot of different fields, only the email and password would be the same fields.

    Could I use Flask login for such a use case?

    Many thanks! Flaviu

  • #104 Miguel Grinberg said 2018-06-05T19:26:28Z

    @Flaviu: yes, that should be fine, as long as you don't have duplicate ids between clients and providers. If the ids are not unique it can still be done, but you need to figure out a way to make the ids unique for Flask-Login.

  • #105 Akib Jabed said 2018-06-08T18:17:52Z

    I have added two methods in RegistrationForm class called validate_username() and validate_email() and they should be taken by WTForms as custom validators. But it shows error in those two methods name.

    from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError from flaskblog.models import User

    class RegistrationForm(FlaskForm): username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)]) email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')]) submit = SubmitField('Sign Up')

    def validate_username(self, username): user = User.query.filter_by(username=username.data).first() if user: raise ValidationError('That username is taken. Please choose a different one.') def validate_email(self, email): user = User.query.filter_by(email=email.data).first() if user: raise ValidationError('That email is taken. Please choose a different one.')

    class LoginForm(FlaskForm): email = StringField('Email', validators=[DataRequired(), Email()]) password = PasswordField('Password', validators=[DataRequired()]) remember = BooleanField('Remember Me') submit = SubmitField('Login')

  • #106 Miguel Grinberg said 2018-06-08T19:10:25Z

    @Akib: what's the error?

  • #107 Gawayne said 2018-06-10T05:21:52Z

    Hello Miguel

    Great tutorial. I have been following along and will continue to do so.

    Just a small point, in the register.html file i noticed that you do not have the novalidate attribute in order to fully leave the validation task to Flask as you previously did with the login form. Maybe you did this intentionally as it did allow me to see the effect of not including it. So as i said just a minor point.

  • #108 Miguel Grinberg said 2018-06-10T18:11:20Z

    @Gawayne: Yes, I wanted you to see both options, so that you can decide which one you prefer.

  • #109 senel said 2018-06-11T14:54:58Z

    Hi Miguel,

    Everytime I try to login i need to enter quotation marks ('') around the actual password in the password field of the login form to pass the hash check. Any idea why? I tried verifying through the console and it works just fine, it's just that with the password field that I have the issue. For example: pass is '1234', I need to actually put '1234' in the password field to be able to login.


  • #110 Miguel Grinberg said 2018-06-11T15:49:51Z

    @senel: maybe when you created this password you used those quotes? Try setting a new password on the account.

  • #111 pcx said 2018-06-14T17:31:52Z

    Hello Miguel, I am trying to get the username / email for loggin in as you suggested in comments, but i have problems with the validation. I mean it doesnt work at all so, the only loggin in validation I have is the one from the models.py

    Can you please give me a tip how to make the validation on submitting the form?

    Here's the code: https://pastebin.com/TbhrNSZC

  • #112 Miguel Grinberg said 2018-06-14T19:01:25Z

    @pcx: your validate_submit() method is going to take a single argument, which is the field being validated (the submit button). Use self.username or self.email to access the other fields.

  • #113 Ashwani Duggal said 2018-06-17T09:27:06Z

    Thanks for a very useful and well written tutorial. In Chapter 5 - I am getting the following error once I type in correct username and password ('susan', 'cat'). jinja2.exceptions.UndefinedError: 'user' is undefined

    Login and Logout functionality is working fine. I have checked the code against the gihub and all looks ok. I think I have done a silly error and missing something. The relevant traceback is below: Please help. Thanks File "e:\microblog\venv\lib\site-packages\jinja2_compat.py", line 37, in reraise raise value.with_traceback(tb) File "E:\microblog\app\templates\index.html", line 1, in top-level template code {% extends "base.html" %} File "E:\microblog\app\templates\base.html", line 29, in top-level template code {% block content %}{% endblock %} File "E:\microblog\app\templates\index.html", line 4, in block "content" Hi, {{ user.username }}! File "e:\microblog\venv\lib\site-packages\jinja2\environment.py", line 430, in getattr return getattr(obj, attribute) jinja2.exceptions.UndefinedError: 'user' is undefined - - [17/Jun/2018 14:48:55] "GET /index HTTP/1.1" 500 -

  • #114 Miguel Grinberg said 2018-06-17T14:11:27Z

    @Ashwani: the error that you get is "user is undefined", that means that the variable "user" does not exist in the context that you are using it. The stacktrace shows that the error comes from the index.html template, so my guess is that you haven't passed the "user" variable as an argument in the render_template() call.

  • #115 Ashwani Duggal said 2018-06-18T06:59:07Z

    @Miguel: Thanks. I located the issue yesterday. The code in the chapter for / and /index mentioned the following: return render_template('register.html', title='Register', form=form)

    I changed it to return render_template('index.html', user=current_user, title='Home', posts=posts) It worked.

    Am i correct in changing it OR was I missing something else?

  • #116 Miguel Grinberg said 2018-06-18T14:18:16Z

    @Ashwani: Please review the "Showing the logged user in templates" section in this article. What you did is fine, but I used current_user directly in the template instead of passing it as an template argument.

  • #117 Paul said 2018-06-19T01:53:54Z

    Hi Miguel!

    In the 'RegistrationForm' class in forms.py, I am wondering why you added the validator DataRequired().

    We already have this in place for the password field, and so we know that for the EqualTo('password') validator to be met it must not be empty. This check seems redundant/unnecessary, but is it?

    I currently work as a design/quality engineer I write lots of perl scripts and tools. I often find myself in similar situations where I do redundant checking for my sanity more than anything.

    Is there general rule for this? Or is it always about trades-offs (ie speed vs reliability, context in which the fxn/class we be used)?

    Thanks! Paul

  • #118 Miguel Grinberg said 2018-06-19T05:37:41Z

    @Paul: if you look at it strictly as a pass/fail thing, validation will work exactly the same with or without the DataRequired validator. The difference is in the error message, which you can argue that it will be a bit more friendly if DataRequired is checked before EqualTo, so that you get the message "password2 field cannot be empty" instead of "password2 must match password field" or something similar. It's a small thing though, it would be totally fine to remove DataRequired.

  • #119 Victor Carvalho said 2018-06-29T11:18:10Z

    Thank you for this awesome material, Miguel! The password field response on login form is very slow. Do you have any clue about this problem?

  • #120 Miguel Grinberg said 2018-06-29T19:03:04Z

    @Victor: what do you mean slow? Is slow to type? That happens entirely in the browser, the Flask application has no involvement. Try a different browser to see if the problem goes away.

  • #121 Nicolas Loffreda said 2018-07-02T19:45:50Z

    Hi Miguel! Thanks for this tutorials, they are very helpful.

    I'm getting the following error: werkzeug.routing.BuildError: Could not build url for endpoint '/index'. Did you mean 'index' instead?

    Basically, one of the for_url functions is getting as parameter '/index' instead of 'index', but I don't know what is generating that extra '/'. Any suggestions?


  • #122 Miguel Grinberg said 2018-07-03T00:12:57Z

    @Nicolas: this is likely your code doing it. Look at the stack trace of the error from bottom to top until you find any line that is in your own code. That should give you a pointer on where to look for the error.

  • #123 Benoit Bourgault said 2018-07-10T01:12:34Z

    First, Thanks for this tutorial, I'm learning a lot by following it.

    I just wanted to point out that the reason why we get different hash for the same password is not because of the number of iteration of the hashing function but because it's a salted hash. The salt is the substring between the 2 $ in that hash string.

  • #124 zeev said 2018-07-13T17:31:58Z

    Hello Miguel, thanks for your enormous work! You are really a great educator. I have the question regarding password. You return it from the client completely unsecure. It means anyone may sniff it and use it latter on. Isn't it necessary to use hash before returning login/register forms data? Of course, using https will help.

  • #125 Miguel Grinberg said 2018-07-13T18:10:24Z

    @zeev: If you hash the password in the client, then the hashed password can also be sniffed, so hashing in the client does not help at all. If you encrypt it, then the encryption key needs to be sent from the server to the client, so it is subject to the same sniffing risks. The best way to protect the data in transit between the client and the server is to use public-key encryption, and this is exactly what https does. If you have https, then any other measures that you take are inferior in security, so there is no point. If you don't have https, then you are at risk no matter what you do with these inferior techniques. Note that the password is hashed in the server and stored hash, the original password is discarded by the server once the hash is calculated.

Leave a Comment