Python Flask Google Login: [HOW TO] Google Login for Flask (2021)
Вставка
- Опубліковано 4 лип 2024
- 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 - Наука та технологія
Anything left unclear or you run into problems? Comment and we will come back to you as soon as possible!
Hi, Im getting CORS error while running flow.authorization_url()
thank you for the great video. my id_info doesn't have email in it.
hey, great tultorial, i have a problem, when i login with my email a "403: access denied error", how do i solve this?
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...
took me minutes to this solution, Comment section == stackoverflow
thanks a lot man!! been trying to do it for 3 weeks now and finally it worked
Thank you for providing an overview of what the flow is while doing social login integration.
Thank you!
Amazing explanation, loved it!!
Hi, Thanks for this video, it's really informative, will be looking forward to more flask videos. Keep on the good work.
Thank you!
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...
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?
worked like a charm thankyou!!!
Hey great video! You said session shouldnt be used in production for storing secrets. So what to use instead?
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!!
Thank you! Neither do we like endless and useless documentations
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
sir, in the callback function, is it "request_session = requests.session() " or "request_session = request.session()" ? Your code and your video show different.
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?
Thanks a lot for this very 'to the point video!
Thank you!
HI. You said that in production we can not use the flask session, how can I do so? Thank u
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
Really Superb.
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.
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 .
thanks alot bro.. very usefull..
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.
Thanks for the video! Is there some way to restrict access to the app to specific Google accounts?
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
Would you be open to join a zoom session so I can learn how to implement this into my code?
Can I use this in production? Or is there anything required to be changed for use in production? Thanks in advance!
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
Gracias, muy buena explicacion y muy facil
te sirvió?
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
Thank you!
Amazing!
better solution is wraps because it mimics the function completely including docstrings.
@functools.wraps(function)
def wrapper(*args, **kwargs):
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 !!!!?
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.
@@code_specialist thanks alot, i have mutual thoughts but needed confirmation ♥️
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?
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
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 .
I can't reproduce the behavior of your app. May you upload your code somewhere so we can check it?
This is very useful, thank you, can you please help in case I need to protect more than one page. Thanks in advance.
What if someone edit session cookie and add a random google_id? There must be a better way to check if user is logged in.
Usually you store the access token locally and verify it each time the client makes a request.
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?
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
I am not familiar with pycharm, can I just use the python ide notepad?
Code is not bound in any way to the IDE. You may use whatever editor you want
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!
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
Can i use this code to secure a dash by plotly app?
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
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
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
@@code_specialist ooh ok thk u!
Please is there way I can use this code with a word press website, Is it possible
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/ 😊
Hi, i got:
KeyError: 'state' on: if not session["state"] == request.args["state"]:
What can i do?
Seems like the response didn’t contain a state. That’s most likely because your authorization url also had none
what should i do to add a public domain in the URI it is not accepting
To our knowledge there are no restrictions on public domains besides the fact that you must support https
@@code_specialist thank you it worked and .... where should we change our app name which should appear to users
@@sreyasbekkam5211 You can use the "edit application" option at console.cloud.google.com/apis/credentials/consent to change the application name
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?
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.
Check out policies.google.com/technologies/cookies#types-of-cookies for more information on the topic
@@code_specialist Thank you for the immediate response.How to delete the google login cookies programmatically?
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.
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.
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
"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?
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/
@@code_specialist thanks
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.
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.
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
love your voice(though this is not the point lol
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.
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.
tks for this demo
i have error when try run code :
KeyError: 'state'
Nobody will be able to provide help to you with this amount of information given. Sorry.
adding import requests should fix your problem Dung
How to create without access to GCP?
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.
Dam I think chatGPT based its answer on your code
Well. This is rough hahaa
Hello, I keep getting this error using the GitHub Repo:
from google.oauth2 import id_token
ModuleNotFoundError: No module named 'google'
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
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.
Use the syncronize option that comes with the clock of windows.
Most likely a synchronization issue, yeah
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
)
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
Use the syncronize option that comes with the clock of windows.
InvalidGrantError
oauthlib.oauth2.rfc6749.errors.InvalidGrantError: (invalid_grant) Bad Request
:////