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

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone this is janik from codespecialist.com and in this video we are going to show you how to build a google login for your flask application so first of all we're going to create a virtual environment which eases the way we handle packages a lot if you're using pycharm you can simply add a new python interpreter and it will pretty much do all the things on itself if you are not used to virtual environments yet i can really just recommend you to look into it so once we are done and you open up a console you will see that we got this little vent in front of our commands which means that pycharm has successfully set up the environment and activated it so first of all let's install flask and the google auth module there are a lot of functions in that module you really don't want to implement yourself and unless you know exactly what you're doing you shouldn't implement it yourself anyway to save you some time i'm going to use pip freeze and print all the requirements into a file by using pip freeze it's going to print all the requirements to the standard output and when i use that pipe it's going to pipe all the outputs into the requirements.txt if you download the source code from the link we provide in the video description you can simply type pip install minus r requirements.txt to install all the packages i just wrote to the file so let's create a new file let's call it app.pi which is going to hold our actual flask application so first of all let's import flask and let's create a simple app so we're going to instantiate flask and call it google login app and we need an app secret to secure the app by the way you should never do what i just did this secret shouldn't be easy to guess but it's all right for test purposes basically we need three functions we need to our login to redirect our user to the google content screen we need a callback that is going to receive the data from the google endpoint and we need to log out to actually clear our local session from our user and let's create two simple pages one is the index and the protected area that is only going to be shown if the user is logged in next we are going to add these routes to our application by using the app.route decorator so pretty straightforward we're just going to append login to the login call back to the callback log out to the logout and so on if a user opens this route on our flask application the application is going to execute the function below let's clean this up a bit by using ctrl alt l which is going to pretty print the code next let's say if under name equals thunder main which is just going to be the standard behavior if you call the file directly so let's say app.run here and set debug to 2. let's try to run this and as you can see it's now running on the localhost on port 5000. of course since nothing is returned and debug is set to true it's going to print an arrow let's return hello world here and try it again and as you can see he now gets hello world next we're going to modify our protected area to actually be a protected area so if we go to our flask application and type slash protected area we get the same arrow as before since we return nothing we simply say protected here we need to restart flask and now we check our route and it's working but we have no concept to protect this page yet so to protect this page we are going to create our own decorator and this decorator takes a function as an input and has a wrapper so the idea is whenever we decorate a function in our flask application it should be protected from unauthorized users to check if the user is logged in we are going to store the google id in the session laska already comes with a session package but it is client-side and stored in the browser cookies so you really shouldn't use this in production systems now we simply say if the google id is not stored in session we're going to board the request with a 401 which will simply return the http 401 unauthorized so let's return this and let's say else return function and last but not least we need to return the wrapper to use this decorator we can now use simply the add annotation but make sure your decorator is the first one because decorators get executed from bottom to top if we now refresh our page we get the http 401 which means our decorator is working fine now we need a kind of button or link to actually call the login and we are reaching that by simply appending some html to our return value of index usually you would use the ginger template engine but for simplification we're going to write everything in this file let's check this also let's go back to our root and now we have that simple login button that is going to redirect us to the login to test this we are going to fill google id with some random value and return a redirect to our protected area let's import flask.redirect and hardcode the path to our protected area [Music] if you now go to our route and click login it's going to write a google id and we are logged in now we need the logout button and we are simply going to copy the login button and change it to logout and our logout function is not going to do anything else than redirecting us to the index and clearing the session so the user information in the session is going to be cleared and as you can see this is working pretty fine all that's left now is we need to send the user to the google login and receive the confirmation but first we need to create a google app so go to console.cloud.google.com and log in with your information once you're logged in go to select a project and create a new project give it a simple name i'm going to call it google login flask app and create the app [Music] now open up the project you just created and go to apis and services and create credentials we now need to configure our content screen and as long as you're not using this for your company you should choose external next we need a name and we are going to call it google login flask app again and you have to provide a user support email as well as the email of the developer so that google or any users using your app can contact you let's save and continue we leave scopes as they are and we are also not going to use any test users check your information once more and go back to the dashboard and now we can create a google off to client go to create credentials or off to client id and select web application as your application type we need a name for our client we're going to call it flask client and we need to add a authorized redirect uri this is going to be our callback route this is a security feature of evolve and should protect users from being redirected to malicious sites so for our tester we are going to enter the localhost at port 5000 slash callback which is going to call our callback function we defined so let's create this and now you can download your credentials by clicking the download button i'm going to include the client secret but it's going to be invalid at the moment you see this so make sure to create your own client secret i'm going to paste this into a new file i'm going to call it clientsecret.json to load it later and identify as the flask app client so there's a lot of information in this file but we are only going to pass this to the google oauth and use the client id let's copy this to to save it in a local variable in the app i'm going to call this the google client id and now we can create a flow that is going to all the information about how we want to authorize our users create overflow we will call the from client secrets file method and pass in the sequence file we just created since python 3.4 we got the pathflip which really simplifies importing files [Music] let's import os and call the path dot join method to combine multiple strings into a path first part is going to be pathflip dot f under file dot parent which is going to return the current folder we're in and the second part is just the file name we just gave it our flow takes three parameters we're going to pass in the client secrets file the scope and the redirect ui the scope determines on which apis you're going to have access but as we don't want to use any apis we're just going to call user info profile user info email and open id which is pretty much the standard scope and we also pass in the redirect ui which is going to be the endpoint the google api calls this is sb4 the endpoint for the callback and thereby the localhost at port 5000 slash callback now we have to modify our login function to redirect the user to the google content screen and use the authorization function of the flow which returns an authorization url and the state so the state is basically a security feature of ohof it is a kind of random variable that will also be sent back from the authorization server so you should always check if the state you initially created and the state you received are the same to ensure no third party has hooked on your request we will do that by simply saving this date in the session let's add a return that redirects the user to the authorization url if this works we should now be sent to the google conson screen where we enter our google details and the answer should be sent to our callback function [Music] for now the function is going to raise an error because we return nothing but we see we called the callback and have all these fragments in our ul [Music] let's update our callback function and we start by calling the flow.fetchtalk method which is going to kind of trade the arguments we just received for an access token to the api the authorization response is simply going to be the url we just received so we pass in request.ul and now we can check if the state we received and the state we have saved in our session are the same [Music] if the states differ we are going to return http 500 and about the request so we can protect our app from cross site attacks after flow.fetch token has successfully been executed their credentials are going to be saved in flow.credentials to verify the data we just received we need to create a hook on the token request and call the verify oaf to talk method this function in turn takes an id token which is saved in our credentials the request talk we just created and the audience which is just going to be our google client id and now we return our id info to test if this works let's go to the login page enter your credentials and yeah we get an arrow by default of 2 only works with https but as this is a test we can simply bypass this by setting in an environment variable let's set off insecure transport to 1 and now callback is going to return id info finally let's modify our callback function so it doesn't return id info but append the google id and the username to the session and redirect the user to the protected area and there we go we can now use google off to log in and log out as i said we included all the source codes in the video description and you can now go and implement your own google login for your flask app if you like this video please subscribe and make sure to activate notifications so you get notified when we publish new [Music] videos you
Info
Channel: Code Specialist
Views: 11,049
Rating: 4.9272728 out of 5
Keywords: Flask Google Login, Python Flask Google Login, google login, google login python, flask web development, flask auth, flask google authentication, flask oauth 2.0, flask oauth
Id: FKgJEfrhU1E
Channel Id: undefined
Length: 14min 6sec (846 seconds)
Published: Mon Feb 22 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.