Skip to content

Commit 6c38c5d

Browse files
committed
Added tutorial for google authentication with flask #45
1 parent 2a13669 commit 6c38c5d

File tree

1 file changed

+247
-1
lines changed

1 file changed

+247
-1
lines changed

docs/technologies/flask/oauth-google.mdx

Lines changed: 247 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,250 @@ import SubHeading from "@site/src/components/SubHeading";
1010

1111
> Related Sample: https://github.com/app-generator/flask-google-oauth
1212
13-
This content is work in progress (soon available)
13+
## Introduction to OAuth
14+
15+
OAuth which stands for Open Authorization is a protocol that allows users to grant third-party applications access to their data without giving away their passwords. OAuth works by giving each user a unique identifier and secret, which they can use to authorize applications to access their data.
16+
17+
OAuth is a secure protocol that protects user data. The user's password is never shared with the website or app. The OAuth authorization server only grants access to the user's data if the user explicitly grants permission.
18+
19+
OAuth is a widely used protocol. It is supported by many popular websites and apps, including Google, Facebook, Twitter, and Amazon. OAuth is a secure and convenient way for users to share their data with third-party applications.
20+
21+
Here are some of the benefits of using OAuth:
22+
23+
- Security: OAuth protects user data by never sharing the user's password with the third-party application.
24+
- Convenience: OAuth makes it easy for users to share their data with third-party applications.
25+
- Flexibility: OAuth is a flexible protocol that can be used to access a wide variety of data.
26+
- Interoperability: OAuth is a widely supported protocol that can be used with a wide variety of third-party applications.
27+
28+
If you are developing a website or app that needs to access user data, OAuth is a good option to consider. OAuth is a secure, convenient, and flexible protocol that can help you to protect user data and make it easy for users to share their data with your application.
29+
30+
## Creating a Google OAuth Client ID
31+
32+
To create a Google OAuth Client ID:
33+
- You will need to create a Google Cloud Platform project. Open Google Cloud Platform [here](https://console.cloud.google.com/)
34+
- Once you have created a project, you can go to the API Credentials page and click the "Create Credentials" button.
35+
- Select "OAuth Client ID" and then "Web application".
36+
- Enter a name for your application and click the "Create" button. You will then be given a Client ID and Client Secret.
37+
38+
## Setting up Flask application
39+
Flask is a microframework for Python web development. It is a simple, flexible, and extensible framework that can be used to create a wide variety of web applications.
40+
41+
This tutorial will focus on setting up OAuth for an existing Flask template. The template is hosted on Github and will be modified to accept user authorization using OAuth.
42+
43+
- Open the terminal and clone the repository using the command
44+
```bash
45+
$ git clone https://github.com/app-generator/flask-google-oauth
46+
```
47+
48+
- Create a virtual environment to install the packages needed for the application. From the terminal execute the command
49+
50+
On `Linux/MacOS`
51+
```bash
52+
$ cd flask-google-oauth
53+
flask-google-oauth$ virtualenv venv
54+
flask-google-oauth$ source venv/bin/activate
55+
(venv) flask-google-oauth$
56+
```
57+
58+
On `Windows`
59+
```bash
60+
$ cd flask-google-oauth
61+
flask-google-oauth$ virtualenv venv
62+
flask-google-oauth$ ./venv/Scripts/activate
63+
(venv) flask-google-oauth$
64+
```
65+
The virtual environment has been created and activated, now we can start installing packages needed for the project.
66+
67+
- Install the packages needed for the template from the terminal using `pip`
68+
```bash
69+
(venv) flask-google-oauth$ pip install -r requirements.txt
70+
```
71+
72+
- We will be adding some environmental variables to aid in the running of the web application
73+
On `Linux/MacOS`:
74+
```bash
75+
(venv) flask-google-oauth$ export FLASK_APP=run.py
76+
(venv) flask-google-oauth$ export FLASK_ENV=development
77+
(venv) flask-google-oauth$ export GOOGLE_OAUTH_CLIENT_SECRET=<google_client_secret>
78+
(venv) flask-google-oauth$ export GOOGLE_OAUTH_CLIENT_ID=<google_client_id>
79+
```
80+
81+
On Windows:
82+
```bash
83+
(venv) flask-google-oauth$ # CMD
84+
(venv) flask-google-oauth$ set FLASK_APP=run.py
85+
(venv) flask-google-oauth$ set FLASK_ENV=development
86+
(venv) flask-google-oauth$ set GOOGLE_CLIENT_SECRET=<google_client_secret>
87+
(venv) flask-google-oauth$ set GOOGLE_CLIENT_ID=<google_client_id>
88+
(venv) flask-google-oauth$
89+
(venv) flask-google-oauth$ # Powershell
90+
(venv) flask-google-oauth$ $env:FLASK_APP = ".\run.py"
91+
(venv) flask-google-oauth$ $env:FLASK_ENV = "development"
92+
(venv) flask-google-oauth$ $env:GOOGLE_OAUTH_CLIENT_SECRET = "<google_client_secret>"
93+
(venv) flask-google-oauth$ $env:GOOGLE_OAUTH_CLIENT_ID = "<google_client_id>"
94+
```
95+
96+
## Installing Flask-Dance
97+
Flask-Dance is a Flask extension that makes it easy to add OAuth authentication to your Flask apps. Flask-Dance provides a single, consistent API for working with OAuth providers, making it easy to add authentication to your app without having to learn the specific OAuth protocol for each provider.
98+
99+
Flask-Dance supports a wide variety of OAuth providers, including Google, Facebook, Twitter, GitHub, Bitbucket, Instagram, Reddit, Spotify, and many more
100+
101+
- Install `flask-dance` by executing the command on your terminal
102+
```
103+
(venv) flask-google-oauth$ pip install flask-dance
104+
```
105+
106+
## Configuring Flask-Dance with Google OAuth
107+
Some changes will be made to the project files to add an authentication mechanism using Google OAuth. Below is the current folder structure of the project.
108+
```bash
109+
.
110+
├── apps
111+
│ ├── authentication
112+
│ ├── config.py
113+
│ ├── home
114+
│ ├── __init__.py
115+
│ ├── static
116+
│ └── templates
117+
├── package.json
118+
├── README.md
119+
├── render.yaml
120+
├── requirements.txt
121+
└── run.py
122+
```
123+
- We will be creating an authentication schema that will be used to save authentication tokens when a user login using Google authentication. Make the following changes to `apps/authentication/models.py`
124+
125+
```py
126+
# apps/authentication/models.py
127+
128+
from flask_login import UserMixin
129+
from flask_dance.consumer.storage.sqla import OAuthConsumerMixin
130+
131+
from apps import db, login_manager
132+
133+
from apps.authentication.util import hash_pass
134+
135+
class Users(db.Model, UserMixin):
136+
137+
__tablename__ = 'users'
138+
139+
id = db.Column(db.Integer, primary_key=True)
140+
username = db.Column(db.String(64), unique=True)
141+
email = db.Column(db.String(64), unique=True)
142+
password = db.Column(db.LargeBinary)
143+
oauth_google = db.Column(db.String(100), nullable=True) # <-- NEW attribute
144+
...
145+
146+
class OAuth(OAuthConsumerMixin, db.Model): # <-- NEW class
147+
user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="cascade"), nullable=False)
148+
user = db.relationship(Users)
149+
```
150+
151+
- We will be creating an `oauth` module to handle the signup and login using Google authentication. Create a file `oauth.py` in the `apps/authentication` folder and add the following code
152+
```py
153+
# apps/authentication/oauth.py
154+
import os
155+
156+
from flask_login import current_user, login_user
157+
from flask_dance.consumer import oauth_authorized
158+
from flask_dance.consumer.storage.sqla import SQLAlchemyStorage
159+
from flask_dance.contrib.google import google, make_google_blueprint
160+
from sqlalchemy.orm.exc import NoResultFound
161+
162+
from .models import Users, db, OAuth
163+
164+
client_id = os.getenv('GOOGLE_CLIENT_ID')
165+
client_secret = os.getenv('GOOGLE_CLIENT_SECRET')
166+
167+
google_blueprint = make_google_blueprint(
168+
client_id=client_id,
169+
client_secret=client_secret,
170+
scope='user',
171+
storage=SQLAlchemyStorage(
172+
OAuth,
173+
db.session,
174+
user=current_user,
175+
user_required=False
176+
),
177+
)
178+
179+
@oauth_authorized.connect_via(google_blueprint)
180+
def google_logged_in(blueprint, token):
181+
info = google.get('/user')
182+
183+
if info.ok:
184+
account_info = info.json()
185+
print(account_info)
186+
username = account_info['login']
187+
188+
query = Users.query.filter_by(oauth_google=username)
189+
try:
190+
user = query.one()
191+
login_user(user)
192+
except NoResultFound:
193+
user = Users()
194+
user.username = username
195+
user.oauth_google = username
196+
user.save()
197+
198+
login_user(user)
199+
```
200+
We have created a blueprint that makes use of Google's authentication. We connected the blueprint to the `OAuth` schema.
201+
202+
- Next step is to register the blueprint to our Flask application to make it accessible from the browser route. Update `apps/__init__.py` to register the blueprint
203+
```py
204+
# apps/__init__.py
205+
...
206+
def register_blueprints(app):
207+
from apps.authentication.oauth import google_blueprint
208+
app.register_blueprint(google_blueprint, url_prefix='/login')
209+
...
210+
211+
def configure_database(app):
212+
with app.app_context():
213+
db.create_all()
214+
...
215+
216+
def create_app():
217+
app = Flask(__name__)
218+
register_extensions(app)
219+
register_blueprints(app)
220+
configure_database(app)
221+
return app
222+
```
223+
224+
- Next step is creating a route for the google blueprint that will handle requests for the authentication. Update `apps/authentication/routes.py` with the following code
225+
```py
226+
# apps/authentication/routes.py
227+
...
228+
from flask_dance.contrib.google import google
229+
from apps.authentication import blueprint
230+
231+
@blueprint.route("/google")
232+
def login_google():
233+
""" Google login """
234+
if not google.authorized:
235+
return redirect(url_for("google.login"))
236+
237+
res = google.get("/user")
238+
return redirect(url_for('home_blueprint.index'))
239+
```
240+
Now requests to `login/google` route will be handled by this route. From your terminal you can run the command `flask routes` to see all the routes present in the application.
241+
242+
- Start up the application from the terminal using the command
243+
```bash
244+
(venv) flask-google-oauth$ flask run
245+
```
246+
From your browser visit [`127.0.0.1:5000/login/google`](http://127.0.0.1:5000/login/google). Once you have logged in, you will be able to access protected resources in your Flask app.
247+
248+
## Conclusion
249+
In conclusion, this article has provided an overview of OAuth and its importance in modern web applications. We explored the process of creating a Google OAuth Client ID, which is essential for enabling user authentication and authorization using Google accounts. Additionally, we discussed the steps involved in setting up a Flask application, a popular Python web framework, to handle OAuth authentication.
250+
251+
To facilitate OAuth functionality in our Flask application, we installed and configured Flask-Dance, a Flask extension that simplifies the integration of OAuth providers. Specifically, we focused on configuring Flask-Dance with Google OAuth, allowing users to authenticate with their Google accounts in our application.
252+
253+
By following the steps outlined in this article, developers can leverage the power of OAuth and Google OAuth specifically to enable secure user authentication and authorization in their Flask applications. This process not only enhances the user experience but also provides a seamless integration with widely used social media and identity platforms.
254+
255+
## Resources
256+
- 👉 [Flask-Dance] Documentation(https://flask-dance.readthedocs.io/en/latest/)
257+
- 👉 [Google Cloud Platform](https://console.cloud.google.com/) - the official website
258+
- 👉 Free [Support](https://appseed.us/support/) via Email & Discord
259+
- 👉 [Custom Development Services](https://appseed.us/custom-development/) provided by experts

0 commit comments

Comments
 (0)