Python Flask Google Login: [HOW TO] Google Login for Flask (2021)

  Рет қаралды 64,138

Code Specialist

Code Specialist

Күн бұрын

Learn about how to build a Google Login for your Python (Flask) Web Application. By using a third party like Google to authenticate users, you allow users to save a lot of time and you save time with your web development. Also, you reduce the time you have to spend developing complex flask authentication systems.
This video shows you how to utilize OAuth2, Python Flask, and the Python Google OAuth Library to create a login function everyone likes to use.
We start from absolute scratch and upload all the code here so you can jump right into it. Happy Coding!
Video Chapters:
00:00 - Intro
00:16 - Installation
01:43 - Basic Flask App
03:17 - Modifications for Login
06:22 - Google Cloud Console
09:11 - Modifications to use Google Login
Source code via GitHub repository:
github.com/code-specialist/fl...
Sources mentioned in the video:
Flask - flask.palletsprojects.com/en/...
Google OAuth Library - pypi.org/project/google-auth-...
OAuth 2.0 Framework formal description:
datatracker.ietf.org/doc/html...
Social Media:
Twitter - / specialist_code
Facebook - / specialistcode
Instagram - / specialist_code
LinkedIn - / code-specialist
For more information, check code-specialist.com

Пікірлер: 109
@code_specialist
@code_specialist 3 жыл бұрын
Anything left unclear or you run into problems? Comment and we will come back to you as soon as possible!
@mateuszfijak3938
@mateuszfijak3938 2 жыл бұрын
Hi, Im getting CORS error while running flow.authorization_url()
@codeMasteryHq
@codeMasteryHq 11 ай бұрын
thank you for the great video. my id_info doesn't have email in it.
@caiomazza7489
@caiomazza7489 5 ай бұрын
hey, great tultorial, i have a problem, when i login with my email a "403: access denied error", how do i solve this?
@jens6005
@jens6005 Жыл бұрын
For anybody getting an error with request.session() >>> the solution is to: (1) pip install requests and (2) import requests and (3) make it: request_session = requests.Session() Took me ages to find out...
@nimitmore5830
@nimitmore5830 8 ай бұрын
took me minutes to this solution, Comment section == stackoverflow
@ashutoshmahawar7939
@ashutoshmahawar7939 3 жыл бұрын
Thank you for providing an overview of what the flow is while doing social login integration.
@code_specialist
@code_specialist 3 жыл бұрын
Thank you!
@NM_kawaii
@NM_kawaii 10 ай бұрын
thanks a lot man!! been trying to do it for 3 weeks now and finally it worked
@abhijeetsinha9333
@abhijeetsinha9333 2 жыл бұрын
Amazing explanation, loved it!!
@promisesheggs8863
@promisesheggs8863 3 жыл бұрын
Hi, Thanks for this video, it's really informative, will be looking forward to more flask videos. Keep on the good work.
@code_specialist
@code_specialist 3 жыл бұрын
Thank you!
@grege6564
@grege6564 2 жыл бұрын
I know this is an older video, but everything worked smoothly in your code. However, I encounter a strange issue. I keep getting a Key Error 'state' from the line: if not session['state'] == request.args['state'] If i comment out that line, it works. I printed the state in both /login route and /callback route, and the state key is being read SOMETIMES. Sometimes, it just doesn't exist. Any ideas as to why sometimes the state key doesn't exist?
@AISolutionsPH
@AISolutionsPH 4 ай бұрын
what should be client_secrets_file value if im about to host the code in the cloud? seems to have an issue with errors not being able to find client_secret.json file
@Dr.Cosmar
@Dr.Cosmar 2 жыл бұрын
Yep, that's 1.5 hours I'll never get back. You blasted through the last 3 mins (really should have been stretched to 10) making my efforts in following along less than worthless...
@yumindev
@yumindev 2 жыл бұрын
sir, in the callback function, is it "request_session = requests.session() " or "request_session = request.session()" ? Your code and your video show different.
@yuvrajsurve3825
@yuvrajsurve3825 2 жыл бұрын
Hi, I am trying login through google sign-in on my mobile phone(which is connected to my local area network ), I am getting redirected to the Google sign-in page but after that, it just keeps loading but on my system (on which website is hosted)I am not facing any issue everything is working fine. can you please help me .
@abeer_nawaf_sul
@abeer_nawaf_sul 3 жыл бұрын
Thank you this was easy and actually works! I hate all the text documentations I found on this, they were all complex and time-consuming and code just doesn't work!!
@code_specialist
@code_specialist 3 жыл бұрын
Thank you! Neither do we like endless and useless documentations
@user-ml3ku5km6r
@user-ml3ku5km6r 5 ай бұрын
HI. You said that in production we can not use the flask session, how can I do so? Thank u
@akshatadhadambe5812
@akshatadhadambe5812 3 ай бұрын
worked like a charm thankyou!!!
@nadeemqureshi9779
@nadeemqureshi9779 3 жыл бұрын
Thanks a lot for this very 'to the point video!
@code_specialist
@code_specialist 3 жыл бұрын
Thank you!
@snippletrap
@snippletrap Жыл бұрын
I get a key error from line 44 (using latest packages in March 2023). The session object does not persist from `login()` to `callback()`... if I print "'state' in session' as the first line of `callback()` the value is False.
@tomasdavid1643
@tomasdavid1643 2 жыл бұрын
Hi and big thanks for this straightforward tutorial! Can you give me a hint how to proceed if I want to create a user restricted areas with data from their APIs (i.e. Google Analytics) please?
@user-dk2tz1ww9x
@user-dk2tz1ww9x 6 ай бұрын
Hey great video! You said session shouldnt be used in production for storing secrets. So what to use instead?
@darshilmehta4948
@darshilmehta4948 2 жыл бұрын
I never knew this could be this easy although I would like if you can describe the flow and all the other methods in little more detail
@yogeshwarangovindarajan8817
@yogeshwarangovindarajan8817 3 жыл бұрын
Really Superb.
@reuhakz9540
@reuhakz9540 2 жыл бұрын
thanks alot bro.. very usefull..
@mattbrown4275
@mattbrown4275 2 жыл бұрын
I don't think you can use the @login_is_required on multiple routes or it will throw an AssertionError? but something like, should stop it asserting.. wrapper.__name__ = function.__name__ return wrapper
@RomeshEtulgama
@RomeshEtulgama 2 жыл бұрын
Thank you!
@RacsoNagem
@RacsoNagem Жыл бұрын
Amazing!
@nemanjatrivic9505
@nemanjatrivic9505 5 ай бұрын
better solution is wraps because it mimics the function completely including docstrings. @functools.wraps(function) def wrapper(*args, **kwargs):
@jaypatel-vy9qw
@jaypatel-vy9qw 2 жыл бұрын
Would you be open to join a zoom session so I can learn how to implement this into my code?
@maikelberbi5210
@maikelberbi5210 Жыл бұрын
Gracias, muy buena explicacion y muy facil
@sergioromero5146
@sergioromero5146 Жыл бұрын
te sirvió?
@KaiTan111
@KaiTan111 3 жыл бұрын
Can I use this in production? Or is there anything required to be changed for use in production? Thanks in advance!
@code_specialist
@code_specialist 3 жыл бұрын
You may use this in production. But we would advise you not to do so. This video shows how the Google API in terms of the OAuth2 protocol may be consumed. It doesn't show how to secure apps, and as that's a legal matter, we can't give any advice on it either
@_REETKHANCHANDANI
@_REETKHANCHANDANI 3 жыл бұрын
session.clear() does not logout the user , even after inspecting the page and manually deleting the cookies , I do not see any option to login again .. The user credntials entered for the first time are always present there .
@code_specialist
@code_specialist 3 жыл бұрын
I can't reproduce the behavior of your app. May you upload your code somewhere so we can check it?
@brettcrowley6729
@brettcrowley6729 3 жыл бұрын
Thanks for the video! Is there some way to restrict access to the app to specific Google accounts?
@code_specialist
@code_specialist 3 жыл бұрын
Yes, there is. Under Project > APIs and Services > Consent (console.cloud.google.com/apis/credentials/consent) there is an test user option. If you enable it, you may restrict access to certain users
@udaydeepyadav
@udaydeepyadav 2 жыл бұрын
Hi , your way of explaining is very and simple, i learnt a lot from this video, i had dew doubts on this concept but thanks to you, also i have a strong suggestion, n your video you are almost whispering, which took all my nerve to understand even after putting on the headphones, dont take me wrong, but its a strong suggestion for you.
@Justindewittt
@Justindewittt 2 жыл бұрын
Error: TypeError: protectedArea() takes no arguments (2 given) The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a function. help?
@code_specialist
@code_specialist 2 жыл бұрын
You missed a call somewhere and passed protectedArea as a function, due to that it gets called with args and kwargs. It’s a guess. Need to see your code in order to help properly
@animeshmishra4282
@animeshmishra4282 2 жыл бұрын
Is it a good practice to create html pages and put them in template folder then render it using jinja ! Or should i make a pure flask api then how will i do redirect if my web app is at different domain !!!!?
@code_specialist
@code_specialist 2 жыл бұрын
Using flask for full stack web applications might be a poor choice depending on your experience and use case. However you may use Flask as API provider and a Frontend Technology such as Angular, React or whatever or simply static HTML Pages with some vanilla JS fetch requests. It really depends on your specific case.
@animeshmishra4282
@animeshmishra4282 2 жыл бұрын
@@code_specialist thanks alot, i have mutual thoughts but needed confirmation ♥️
@godofwinetits3826
@godofwinetits3826 3 жыл бұрын
I am not familiar with pycharm, can I just use the python ide notepad?
@code_specialist
@code_specialist 3 жыл бұрын
Code is not bound in any way to the IDE. You may use whatever editor you want
@theteam8677
@theteam8677 3 жыл бұрын
Please is there way I can use this code with a word press website, Is it possible
@code_specialist
@code_specialist 3 жыл бұрын
This is meant to be used with Python. It could be easily translated to PHP, though I guess that doesn't answer your question. The easiest way to integrate a Google Login with your WordPress would be to use a plugin such as "Google Apps Login": de.wordpress.org/plugins/google-apps-login/ 😊
@yashkamble2849
@yashkamble2849 2 жыл бұрын
Can i use this code to secure a dash by plotly app?
@code_specialist
@code_specialist 2 жыл бұрын
Short anwser: No. This video exemplifies how you may consume the Google API by terms of the OAuth2 protocol. It doesn't show how to secure apps, and as that's a legal matter, we can't give any advice on it either
@laserspud
@laserspud 3 жыл бұрын
Hi i need help, how do i make it that i have to relogin when i logout? because say i have multiple users, then i want to be able to login to each individual user
@code_specialist
@code_specialist 3 жыл бұрын
Google saves some of the data on your local browser. If you enter incognito mode or remove the google related cookies, you may simply choose another user next time you hit login
@laserspud
@laserspud 3 жыл бұрын
@@code_specialist ooh ok thk u!
@danomics7674
@danomics7674 2 жыл бұрын
You mentioned that the Flask "session" should not be used in production. What is a better method for doing this in production that you could recommend?
@code_specialist
@code_specialist 2 жыл бұрын
Miguel Grinberg whom we can recommend without reservation got an interesting article on the flask session: blog.miguelgrinberg.com/post/how-secure-is-the-flask-user-session . TLDR; the flask sessions are stored client side and not encrypted (basically they are just cookies). A valid alternative is the flask session library, which saves sessions server-side: pypi.org/project/Flask-Session/ . But there are also countless other solutions we didn't test personally. However, storing mere access tokens client side is common practice and is a valid production ready solution. The traditional flask session just isn't the right fit for any kind of sensitive data
@AnuragHalderEcon
@AnuragHalderEcon 27 күн бұрын
This is very useful, thank you, can you please help in case I need to protect more than one page. Thanks in advance.
@CalibanDev
@CalibanDev Жыл бұрын
Hi, i got: KeyError: 'state' on: if not session["state"] == request.args["state"]: What can i do?
@code_specialist
@code_specialist Жыл бұрын
Seems like the response didn’t contain a state. That’s most likely because your authorization url also had none
@sreyasbekkam5211
@sreyasbekkam5211 3 жыл бұрын
what should i do to add a public domain in the URI it is not accepting
@code_specialist
@code_specialist 3 жыл бұрын
To our knowledge there are no restrictions on public domains besides the fact that you must support https
@sreyasbekkam5211
@sreyasbekkam5211 3 жыл бұрын
@@code_specialist thank you it worked and .... where should we change our app name which should appear to users
@code_specialist
@code_specialist 3 жыл бұрын
@@sreyasbekkam5211 You can use the "edit application" option at console.cloud.google.com/apis/credentials/consent to change the application name
@adarshamin3942
@adarshamin3942 2 жыл бұрын
Hello, thank you for your helpful tutorials. I am working on a group project creating a flask app. I used your walkthrough for setting up an unsecure login which is perfect for our needs and works. We would like to be able to GET the users email from the google login. I am finding a lot of conflicting information and no luck yet. Would you know how to do this with the setup you utilized, I can also share our repo if that would help Greatly Appreciate Your Time! I sent an email if that is easier as well!
@code_specialist
@code_specialist 2 жыл бұрын
In the step of the callback we create an object „id_info“ that contains user information provided by Google by default. It also contains an „email“ field. There should also be something like an „email_verified“ field. However, that requires the scope to be „profile“ and „email“ at least. Our example already set those scopes. Check developers.google.com/identity/sign-in/web/backend-auth for more information
@vandriichuk
@vandriichuk 3 жыл бұрын
Hi. Thnx for you lesson. How I can add google authenticator to this code? # The user will get an authorization code. This code is used to get the # access token. code = input('Enter the authorization code: ') flow.fetch_token(code=code) Now I don't understand.
@code_specialist
@code_specialist 3 жыл бұрын
I am not sure I got you right, but I am afraid this flow doesn't suit your use case. 2FA however, is an implementation detail by Google not by the flow itself, there's no additional code required to allow users with 2FA enabled to login.
@imvickykumar999
@imvickykumar999 Жыл бұрын
I am getting this error Error 400: redirect_uri_mismatch You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy. If you're the app developer, register the redirect URI in the Google Cloud Console.
@chaifps
@chaifps Жыл бұрын
click on error details, they will give you the new URI to add, go to credentials page, select your credential, scroll down and add the given URI to it.
@code_specialist
@code_specialist Жыл бұрын
Your redirect uri does not comply with the standard. Maybe your redirect uri points to something like 0.0.0.0… or 127.0.01? However it must be a hostname e. g localhost
@okopyl
@okopyl 2 жыл бұрын
"Flask comes with a session package... you shouldn't use it in production..." Could you please tell what and how should I use in production?
@code_specialist
@code_specialist 2 жыл бұрын
Check out this post: blog.miguelgrinberg.com/post/how-secure-is-the-flask-user-session . There are several solutions to this, such as flask-session, that rather saves data server than client sided e. G: pypi.org/project/Flask-Session/
@okopyl
@okopyl 2 жыл бұрын
@@code_specialist thanks
@anantmulchandani709
@anantmulchandani709 3 жыл бұрын
How to create without access to GCP?
@code_specialist
@code_specialist 3 жыл бұрын
You need the client id and the client secret in order to enable the login with google. They are exclusively for your application. You may, however, use a third-party service such as Auth0 (auth0.com). One last thing: Accessing GCP is totally free (worldwide) so there's no reason not to use it in our opinion.
@ppariventhan6647
@ppariventhan6647 2 жыл бұрын
Thanks for the descriptive step by step video.Following these steps i could use google authentication to login into my application successfully.But even after logout from my application the google authentication is kept alive and leads to login to the application without authentication again.How to close the google authentication session?
@code_specialist
@code_specialist 2 жыл бұрын
That’s most likely due to cookies that save the state of your Google auth requests. To clear the sessions you have to delete the cookies related to your Google login. Most browsers offer an overview of cookies in their developer console. By default the shortcut is F12 in Firefox and Chrome.
@code_specialist
@code_specialist 2 жыл бұрын
Check out policies.google.com/technologies/cookies#types-of-cookies for more information on the topic
@ppariventhan6647
@ppariventhan6647 2 жыл бұрын
@@code_specialist Thank you for the immediate response.How to delete the google login cookies programmatically?
@code_specialist
@code_specialist 2 жыл бұрын
Flask offers a delete_cookie method on the response object. However, you may encounter difficulties as the cookie at hand isn’t yours. It’s also bad practice to touch cookies that ain’t yours.
@blinkchannel5366
@blinkchannel5366 2 жыл бұрын
tks for this demo i have error when try run code : KeyError: 'state'
@code_specialist
@code_specialist 2 жыл бұрын
Nobody will be able to provide help to you with this amount of information given. Sorry.
@proszeno
@proszeno 2 жыл бұрын
adding import requests should fix your problem Dung
@hickasso
@hickasso Жыл бұрын
Man, u need to show us what you are using as import. Like in the end, you have imported google package, cachecontrol and others, but was hard to understand this.
@nimitmore5830
@nimitmore5830 8 ай бұрын
True, i fed up with errors, then went straight to his github and copy pasted his code, it ran sucessful 1 time... :D 1 time :D
@paggiechen8866
@paggiechen8866 2 жыл бұрын
love your voice(though this is not the point lol
@soosbot2244
@soosbot2244 Жыл бұрын
Dam I think chatGPT based its answer on your code
@christophechouinard7619
@christophechouinard7619 2 жыл бұрын
Well. This is rough hahaa
@mcnutley
@mcnutley Жыл бұрын
Hello, I keep getting this error using the GitHub Repo: from google.oauth2 import id_token ModuleNotFoundError: No module named 'google'
@marcinajman6256
@marcinajman6256 2 жыл бұрын
if anyone face this problem: AttributeError: module 'google_auth_oauthlib.flow' has no attribute 'from_client_secrets_file' try: from google_auth_oauthlib.flow import Flow
@chaifps
@chaifps Жыл бұрын
HI I am getting this error, please help out ValueError: Token used too early, 1665681789 < 1665681803. Check that your computer's clock is set correctly.
@CalibanDev
@CalibanDev Жыл бұрын
Use the syncronize option that comes with the clock of windows.
@code_specialist
@code_specialist Жыл бұрын
Most likely a synchronization issue, yeah
@audywboonanake3125
@audywboonanake3125 Жыл бұрын
clock_skew_in_seconds = id_info = id_token.verify_oauth2_token( id_token=credentials._id_token, request=token_request, audience=GOOGLE_CLIENT_ID, clock_skew_in_seconds=10 )
@cookiemilk3347
@cookiemilk3347 Жыл бұрын
Hey I seem to be getting this very strange error when trying to login... it was working just fine before: Token used too early, 1663292036 < 1663292037. Check that your computer's clock is set correctly
@CalibanDev
@CalibanDev Жыл бұрын
Use the syncronize option that comes with the clock of windows.
@marcinajman6256
@marcinajman6256 2 жыл бұрын
InvalidGrantError oauthlib.oauth2.rfc6749.errors.InvalidGrantError: (invalid_grant) Bad Request :////
Authenticating a Flask API Using JSON Web Tokens
20:33
Pretty Printed
Рет қаралды 173 М.
Add Google Hosted Authentication to a Python Flask App
12:55
Vincent Stevenson
Рет қаралды 18 М.
Sigma Kid Hair #funny #sigma #comedy
00:33
CRAZY GREAPA
Рет қаралды 36 МЛН
Finger Heart - Fancy Refill (Inside Out Animation)
00:30
FASH
Рет қаралды 21 МЛН
Опасность фирменной зарядки Apple
00:57
SuperCrastan
Рет қаралды 9 МЛН
Why Is He Unhappy…?
00:26
Alan Chikin Chow
Рет қаралды 15 МЛН
Implement login with google in python flask applications with authlib
26:50
FastAPI, Flask or Django - Which Should You Use?
9:49
Tech With Tim
Рет қаралды 59 М.
Set up Google OAuth with Next.js using Next-Auth!
21:00
Build SaaS with Ethan
Рет қаралды 23 М.
Python Flask Authentication Tutorial - Learn Flask Login
29:35
Arpan Neupane
Рет қаралды 218 М.
Python REST API Tutorial - Building a Flask REST API
1:14:01
Tech With Tim
Рет қаралды 756 М.
An Illustrated Guide to OAuth and OpenID Connect
16:36
OktaDev
Рет қаралды 570 М.
Flask (Python) - Google oAuth 2.0 (Authlib)
11:40
Vuka
Рет қаралды 52 М.
Authentication and Authorization With Flask-Login
35:20
Pretty Printed
Рет қаралды 101 М.
Здесь упор в процессор
18:02
Рома, Просто Рома
Рет қаралды 422 М.
Rate This Smartphone Cooler Set-up ⭐
0:10
Shakeuptech
Рет қаралды 4,9 МЛН
Samsung laughing on iPhone #techbyakram
0:12
Tech by Akram
Рет қаралды 4,4 МЛН