Add authentication to your web page
Now that you’ve got a simple web page, let’s add authentication to it!
The first thing you need to do is define a div in your HTML page that will eventually be transformed into a super stylish login form.
Configuring for flask-login
I wouldn’t be a gentleman unless I revealed my config.py file. Again, this should all be straightforward if you’ve been following the rest of our series:
Create a web page
Now that you’ve got the Okta stuff out of the way, go ahead and create a web page, any web page! You can use an existing page, create a new one, or use the one that I’ve provided below.
To use the one below, create an index.html file on your hard drive, and copy/paste the HTML below into it.
If you open this page in your browser, you’ll see the incredibly simple web page below:
Create an okta account
The first thing you’ll need to do is create a free Okta developer account.
Once you’ve got your shiny new Okta account and you’ve logged into the dashboard, you need to open a new file and copy down the Org URL from the top-right portion of the page.
Creating log-in and sign-up forms
Hopefully you’ve become somewhat acquainted with Flask-WTF or WTForms in the past. We create two form classes in forms.py which cover our most essential needs: a sign-up form, and a log-in form:
Creating our login routes
Let’s get things started by setting up a Blueprint for our authentication-related routes:
Getting started
Let’s start with installing dependencies. Depending on which flavor of database you prefer, install either psycopg2-binary or pymysql along with the following:
$ pip3 install flask flask-login flask-sqlalchemy flask-wtf
Important: login helpers
Before your app can work like the above, we need to finish auth.py by providing a couple more routes:
Integrating flask-login #
To initialize Flask-Login import LoginManager class from flask_login package and create a new instance of LoginManager as follows (changes are highlighted):
Logging in
You’ll be happy to hear that signup up was the hard part. Our login route shares much of the same logic we’ve already covered:
Login.jinja2
The login form template contains essentially the same structure as our signup form, but with fewer fields:
Step 1: create an openid connect config file
Create a new file named client_secrets.json in the root of your project folder and insert the following code.
Be sure to replace the placeholder variables with your actual Okta information.
This file will be used by the Flask-OIDC library which we’ll be configuring in a moment. These settings essentially tell the OpenID Connect library what OpenID Connect application you’re using to authenticate against, and what your authorization server API endpoints are.
The URIs above simply point to your newly created Okta resources so that the Flask library will be able to talk to it properly.
Step 1: store your org url
The first thing you need to do is copy down the Org URL from the top-right portion of your Okta dashboard page. This URL will be used to route to your authorization server, communicate with it, and much more. You’ll need this value later, so don’t forget it.
Step 2: configure flask-oidc
Open up app.py and paste in the following code.
What we’re doing here is configuring the Flask-OIDC library.
Finally, after all the configuration is finished, we initialize the Flask-OIDC extension by creating the oidc object.
There you have it
If you’ve made it this far, I commend you for your courage. To reward your accomplishments, I’ve published the source code for this tutorial on Github for your reference. Godspeed, brave adventurer.
Want more authentication awesomeness?
I hope you enjoyed learning how you can quickly add authentication to any web page in just 10 minutes using Okta. What I showed you in this article was just the tip of the iceberg, however. There’s a lot more you can do using services like Okta to quickly bootstrap the authentication component of your web apps:
Главная идея
Расширение предоставляет набор функций, используемых для:
- регистрация пользователей в
- выключение пользователей
- проверять, зарегистрирован ли пользователь или нет, и выяснить, какой пользователь это
Что он не делает и что вам нужно делать самостоятельно:
- не обеспечивает способ хранения пользователей, например, в базе данных
- не предоставляет способ проверки учетных данных пользователя, например, имя пользователя и пароль
Ниже приведен минимальный набор шагов, необходимых для того, чтобы все работало.
Я бы рекомендовал поместить весь код, связанный с auth, в отдельный модуль или пакет, например auth.py Таким образом, вы можете создавать необходимые классы, объекты или настраиваемые функции отдельно.
Завершение сеанса входа в систему
Хорошая практика тайм-аута после входа в систему после определенного времени, вы можете достичь этого с помощью Flask-Login.
Использование расширения для флажков
Один из простых способов внедрения системы авторизации – использование расширения для флажков. Веб-сайт проекта содержит подробный и хорошо написанный быстрый старт, более короткая версия которого доступна в этом примере.
Регистрация пользователей в
Расширение оставляет подтверждение имени пользователя и пароля, введенных пользователем. На самом деле расширение не волнует, если вы используете комбинацию имени пользователя и пароля или другой механизм. Это пример регистрации пользователей при использовании имени пользователя и пароля.
Создайте loginmanager
Расширение использует класс LoginManager который должен быть зарегистрирован на вашем объекте приложения Flask .
from flask_login import LoginManager
login_manager = LoginManager()
login_manager.init_app(app) # app is a Flask object
Как уже упоминалось ранее, LoginManager может быть, например, глобальной переменной в отдельном файле или пакете. Затем его можно импортировать в файл, в котором создается объект Flask или в вашей фабричной функции приложения и инициализирован.
Укажите обратный вызов, используемый для загрузки пользователей
Обычно пользователи загружаются из базы данных. Обратный вызов должен возвращать объект, который представляет пользователя, соответствующего предоставленному идентификатору. Он должен вернуть None если идентификатор недействителен.
Initialize your flask app
Now that the dependencies are installed, let’s start by creating a simple Flask app. We’ll build on this simple “hello, world!” app until we’ve got all our functionality included.
Create an app.py file and enter the following code:
Open the terminal and run the following code to start up your new Flask app.
Install python and flask dependencies
The first thing you need to do in order to initialize your Flask app is install all of the required dependencies. If you don’t have Python installed on your computer already, please go install it now.
NOTE: I also strongly recommend you get familiar with pipenv when you get some time. It’s a great tool that makes managing Python dependencies very simple.
Now install the dependencies required for this application.
Initializing flask-login
Setting up Flask-Login via the application factory pattern is no different from using any other Flask plugin (or whatever they’re called now). This makes setting up easy: all we need to do is make sure Flask-Login is initialized in __init__.py along with the rest of our plugins, as we do with Flask-SQLAlchemy:
"""Initialize app."""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
db = SQLAlchemy()
login_manager = LoginManager()
def create_app():
"""Construct the core app object."""
app = Flask(__name__, instance_relative_config=False)
# Application Configuration
app.config.from_object('config.Config')
# Initialize Plugins
db.init_app(app)
login_manager.init_app(app)
with app.app_context():
from . import routes
from . import auth
from .assets import compile_assets
# Register Blueprints
app.register_blueprint(routes.main_bp)
app.register_blueprint(auth.auth_bp)
# Create Database Models
db.create_all()
# Compile static assets
if app.config['FLASK_ENV'] == 'development':
compile_assets(app)
return app
This is the minimum we need to set up Flask-Login properly.