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
  • Наука та технологія

КОМЕНТАРІ • 111

  • @code_specialist
    @code_specialist  3 роки тому +4

    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 4 місяці тому +1

      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 Рік тому +7

    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 7 місяців тому +1

      took me minutes to this solution, Comment section == stackoverflow

  • @NM_kawaii
    @NM_kawaii 9 місяців тому

    thanks a lot man!! been trying to do it for 3 weeks now and finally it worked

  • @ashutoshmahawar7939
    @ashutoshmahawar7939 3 роки тому +2

    Thank you for providing an overview of what the flow is while doing social login integration.

  • @abhijeetsinha9333
    @abhijeetsinha9333 2 роки тому +2

    Amazing explanation, loved it!!

  • @promisesheggs8863
    @promisesheggs8863 3 роки тому +2

    Hi, Thanks for this video, it's really informative, will be looking forward to more flask videos. Keep on the good work.

  • @Dr.Cosmar
    @Dr.Cosmar 2 роки тому +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...

  • @grege6564
    @grege6564 Рік тому +6

    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?

  • @akshatadhadambe5812
    @akshatadhadambe5812 2 місяці тому

    worked like a charm thankyou!!!

  • @user-dk2tz1ww9x
    @user-dk2tz1ww9x 5 місяців тому

    Hey great video! You said session shouldnt be used in production for storing secrets. So what to use instead?

  • @abeer_nawaf_sul
    @abeer_nawaf_sul 3 роки тому +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

  • @darshilmehta4948
    @darshilmehta4948 2 роки тому +4

    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

  • @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.

  • @tomasdavid1643
    @tomasdavid1643 2 роки тому +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?

  • @nadeemqureshi9779
    @nadeemqureshi9779 3 роки тому +3

    Thanks a lot for this very 'to the point video!

  • @user-ml3ku5km6r
    @user-ml3ku5km6r 4 місяці тому

    HI. You said that in production we can not use the flask session, how can I do so? Thank u

  • @AISolutionsPH
    @AISolutionsPH 3 місяці тому

    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

  • @yogeshwarangovindarajan8817
    @yogeshwarangovindarajan8817 3 роки тому +1

    Really Superb.

  • @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.

  • @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 .

  • @reuhakz9540
    @reuhakz9540 2 роки тому +1

    thanks alot bro.. very usefull..

  • @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.

  • @brettcrowley6729
    @brettcrowley6729 2 роки тому +1

    Thanks for the video! Is there some way to restrict access to the app to specific Google accounts?

    • @code_specialist
      @code_specialist  2 роки тому

      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

  • @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?

  • @KaiTan111
    @KaiTan111 3 роки тому +1

    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

  • @maikelberbi5210
    @maikelberbi5210 Рік тому

    Gracias, muy buena explicacion y muy facil

  • @mattbrown4275
    @mattbrown4275 2 роки тому +3

    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):

  • @animeshmishra4282
    @animeshmishra4282 2 роки тому +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 роки тому +1

      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 роки тому +1

      @@code_specialist thanks alot, i have mutual thoughts but needed confirmation ♥️

  • @danomics7674
    @danomics7674 2 роки тому +4

    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 роки тому +3

      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

  • @_REETKHANCHANDANI
    @_REETKHANCHANDANI 3 роки тому +2

    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?

  • @AnuragHalderEcon
    @AnuragHalderEcon 3 дні тому

    This is very useful, thank you, can you please help in case I need to protect more than one page. Thanks in advance.

  • @robinsdeepak
    @robinsdeepak 3 роки тому +1

    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.

    • @code_specialist
      @code_specialist  3 роки тому

      Usually you store the access token locally and verify it each time the client makes a request.

  • @frisbyninja
    @frisbyninja 2 роки тому +1

    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

  • @godofwinetits3826
    @godofwinetits3826 2 роки тому +1

    I am not familiar with pycharm, can I just use the python ide notepad?

    • @code_specialist
      @code_specialist  2 роки тому

      Code is not bound in any way to the IDE. You may use whatever editor you want

  • @adarshamin3942
    @adarshamin3942 2 роки тому +3

    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

  • @yashkamble2849
    @yashkamble2849 2 роки тому +1

    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 2 роки тому +1

    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  2 роки тому +1

      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 2 роки тому

      @@code_specialist ooh ok thk u!

  • @theteam8677
    @theteam8677 3 роки тому +1

    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/ 😊

  • @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 2 роки тому +1

    what should i do to add a public domain in the URI it is not accepting

    • @code_specialist
      @code_specialist  2 роки тому

      To our knowledge there are no restrictions on public domains besides the fact that you must support https

    • @sreyasbekkam5211
      @sreyasbekkam5211 2 роки тому

      @@code_specialist thank you it worked and .... where should we change our app name which should appear to users

    • @code_specialist
      @code_specialist  2 роки тому

      @@sreyasbekkam5211 You can use the "edit application" option at console.cloud.google.com/apis/credentials/consent to change the application name

  • @ppariventhan6647
    @ppariventhan6647 2 роки тому +1

    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.

  • @hickasso
    @hickasso Рік тому +1

    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 7 місяців тому

      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

  • @okopyl
    @okopyl 2 роки тому +1

    "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

  • @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

  • @paggiechen8866
    @paggiechen8866 2 роки тому +1

    love your voice(though this is not the point lol

  • @vandriichuk
    @vandriichuk 3 роки тому +1

    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.

  • @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

  • @anantmulchandani709
    @anantmulchandani709 3 роки тому +1

    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.

  • @soosbot2244
    @soosbot2244 Рік тому +1

    Dam I think chatGPT based its answer on your code

  • @christophechouinard7619
    @christophechouinard7619 2 роки тому +1

    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 Рік тому +1

    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 Рік тому +1

    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 Рік тому +1

      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 Рік тому +1

    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 Рік тому

    InvalidGrantError
    oauthlib.oauth2.rfc6749.errors.InvalidGrantError: (invalid_grant) Bad Request
    :////