Spring Security Oauth2 Tutorial with Keycloak - Part 1

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this tutorial we are going to discuss what is oauth 2 and how to implement overthrow features in springboot applications using spring security we will also have a look at how to implement ore through patterns for different kinds of applications like server-side rendered applications which are developed using spring mvc single page applications which are developed using frameworks like angular and also have a look at how to implement machine to machine authorization like in the case of micro services we'll use key clock as our identity server or authorization server to help us implement these orders to patents if you are not aware of these terms over to an identity server don't worry we will cover everything in this tutorial so to follow along this tutorial a basic understanding of spring boot and spring security is recommended so without any further delay let's start the video [Music] so what is oauth 2 the term oauth stands for open authorization and it's an industry standard protocol that was developed for authorization between services or applications and this protocol is right now in version 2.0 that's why is usually known as oauth2 let's understand this better with an example so i am a user of a website or mobile application which is an image gallery application this application's functionality is simple the user uploads a photo and can apply different filters and frames around the photo which he or she uploaded and we can also print these photos so now in recent times everyone is using cloud services to store images like google photos icloud or google drive so if you want to access the photos which are stored inside your google account or maybe facebook account from this image gallery application you have to provide permissions for this application to access your google or facebook account you can't just hand over the username and password of your google or facebook account to this application because that is very risky as this application can store your credentials to the database and if a hacker gets access to this database you're in trouble so we need a safe way to authorize the image gallery application so that it can access our google or facebook account the oauth framework was developed for this reason it's a standard way of providing authorization that means that means permission for the service a in our case the image gallery application to access service p which is a user's google or facebook account when the framework was initially developed it was just called as oauth but later an updated version 2.0 was released in 2013 so which is called as oauth2 also as i mentioned before the a in oauth stands for authorization but not authentication because we are providing authorization for a service to access another service for this reason oah2 is also called as delegated authorization now as the overt concept is clear let's zoom in a little bit and see how the actual authorization flow looks like so we have our user accessing the image gallery application and this application wants to access the photos stored in google drive so instead of asking for google credentials the application will redirect us to the login page of google and once we log in we can grant our permissions for the image gallery application to access the google account thereby the google drive account we can also restrict what all permissions we can give to the image gallery application in this example we want the application to only view our photos but not edit or delete them once we grant the permission the google server will return a unique access token back to the application and our application can use this access token to access the photos from our google account once the google server receives this access token it verifies whether it's a valid token or not if it confirms whether it's a varied token that means a token which is generated by the google server itself it will grant access to the photos in this way we can only provide limited access to our photos in the google drive so that it can just so that the image gallery application can just view our photos but do nothing else and if required we can also revoke the access of this application by changing the settings in your google account so this is a high level overview of how the oauth protocol works in the next section we'll have a look at commonly used watch terminology to understand this better so we saw on a high level how oath works but to implement oauth and understand different kinds of workflows you need to get familiarized with different types of oauth terminology the first one is called as a resource or a protected resource in our image gallery application example we saw earlier the resource or a protected resource either image or photos stored inside our google drive account so anything which needs to be accessed by an external service and which needs the authorization to access it is called as a resource the next term is called as a resource owner as the name suggests this means the owner of the resource in this case it would be me or you the person who is the owner of the photos the next term is called resource server so this is the server that stores or hosts the resource in our case it's the google drive server that stores our photos the next term is called a client which is the service or application which is accessing the resource in our case it's the image gallery application so this client can be a web mobile desktop application or it can be a standalone service like a microservice or even a device like a smart tv so we also have a couple of categories in clients a client can be a public client which means a mobile application or a web or desktop application and the other type of category is a confidential client so this can be a micro service or a cron job running on a remote server so for each client we have different kinds of authorization flows also called grant types which means for different kinds of client we have different ways or mechanisms to get the access tokens we will discuss this also in details in the coming sections so the last term we are going to have a look is the authorization server so this is the server that will generate and provide access tokens to the client and will also verify whether an access token is valid or not there are many options available for the authorization server in the market so you have amazon's aws cognito google's identity platform and okta as the famous authorization servers if you want to manage the authorization on your own key cloak is a very good option it's an open source offering and in this tutorial we'll mainly see how to implement oauth 2 patterns using key clock finally spring framework is working on its own authorization server offering which is still in early stages at the time of creating these videos so if this project if so if you're interested this project is something you have to track so as you understand what is oauth2 you also need to know something called as oidc also known as open id connect this is a protocol which is built on top of oauth 2 which mainly acts as an identity layer so what do i mean by identity layer so previously we saw that when the client wants to access a resource like your photos on google drive it needs an access token from the authorization server this access token is basically a random alphanumerical set of characters which basically does not provide any context or information about the user so which makes it hard for the clients to understand and get the user information for this reason the identity layer will send an additional token called an id token which contains basic information about the user like email first name and last name so when the user requests the token he or she will receive now will now receive two tokens as part of open id connect one is an access token and the other one is an id token the access token will be used to verify whether the user contains necessary permissions to access the user or not and the id token will be used to verify the user information itself so this is the main difference between oauth 2 and openid connect in the later chapters we will also have a look at how this id token and the access token looks like so you can understand it much better so for now let's move on to the next topic so as i said before we are going to use the key clock authorization server in this tutorial and if you are not already aware of quick look kick look is an open source identity and access management server it's a very popular and widely used authorization server in the industry to get started with key clock you can download it by going to the downloads page you can either select a standalone installation or docker download i'm going to go ahead with the standard installation and i already downloaded the key clock software to my machine so once you download key clock you have to unzip and open the bin folder in the terminal and to start the clock server you have to type the command standalone.bat minus d jboss.http dot port equals eight one eight zero so key clock by default uses the server 8080 but as we are as we'll be running our spring boot application on the port 8080 i want to start the key clock server on the port 8180 so when you run this command key clock will start on the port 8180 once the server is up and running open the browser and go to the address http localhost 8180 you will be asked to create an initial admin user account to get started and access the server just provide a username and password of your choice and click on the create button once the user is created we can log in to our authorization server by clicking on the administration console option and now you can see the login page i'm going to type in my admin account credentials and click on login so now you can see that i'm logged into the admin console and the first thing you will observe is something called as a master something called a master which is the default realm in key cloak so a realm is like a placeholder where you can manage a set of clients users and their rules so each rel is not create is not connected with each other so if i create a user in one realm they are not available or accessible from another realm okay so the first thing we are going to do now is to create our own rel by clicking on add rel button here i will provide a name to the realm and click on create button so now you can see that the realm is created and activated automatically now i can create as many clients under this realm and also as many users and role i want under this realm so now let's go ahead and create a client this client is going to be a spring mvc application which is developed using timelife so this is going to be a server side spring mvc application so to create this client i'm going to click on client section and click on create this will bring up an add client page in here i have to provide the client id i'm going to provide this as oauth demo time leave client and click on save so if you remember we discussed a while ago when we registered our client with the authorization server we will get a client id and client secret so this is the client id we received already and now you can see that we see much more details inside the client page the first one you can see is the client protocol this we are going to leave it as open id connect next we have the access type this is also the client type we discussed some time back can either be public confidential or bearer only as we are now dealing with the server side rendered spring mvc application i am going to choose the client type as confidential and i'm going to leave the standard flow enabled option as on because this is also called as authorization code flow and that's what we want to implement as part of this demo and the next field we are interested in is the valid redirect uri this will be the redirect uri which the authorization server will use to send us the authorization code as we saw earlier so for this field i am going to provide the value http localhost 8080 slash login slash oauth2 slash code slash oauth 2 code demo time leaf client so which is the client id which we have provided before so this is the default redirect uri which spring boot supports and which is also according to the oauth 2 conventions so this is recognized by our spring embassy application you don't need to implement this endpoint spring will automatically handle the request when key cloak will redirect to this particular uri so that's all we need to do now we can click on save okay now we have to do one last thing inside the client page that is to generate a client secret we can do that by clicking on the credentials tab the client secret was already generated for us so if you need we can regenerate the secret and we will come back to this once we configured our spring mvc application and also we have to create a user so that we can log into our application we can do that by clicking on the user section on the left side so here we can view all users and also add a new user i am going to click on add new user and here i am going to type the username and click on save this will create the user successfully and to set a password i am going to click on the credentials tab and in here i'm going to provide a random password here we also have the option to select whether the password is going to be a temporary password or not if you select this option the very first time you log in it will ask you to change the password so let's leave this option on and click on ok and set password okay so we've installed key clock configured admin credentials created a realm a client and a user so that's all we need to do now let's go ahead and implement our demo application all right now let's see how the authorization code flow works in practice we're going to develop a spring mvc application to implement authorization code flow i already have the finished application ready and running so what i'm going to do right now is open a browser window and open the browser tools in this and the network tab in this way we can see the network calls our application is going to make so i'm going to open the url http localhost 8080 home as soon as i press enter you can see that an initial authorization request is triggered by the browser to the endpoint to authorize and if you check the request parameters we have a response type as code a state parameter and a redirect uri so the key clock server will make a request to this redirect uri after the successful authentication along with the authorization code we'll have a look at it shortly and lastly we also have the client id as one of the request parameter so as soon as the key clock server received this request it responds with the login page so i am going to provide the credentials of the user i created in the previous section and observe carefully here right after click on login you can see that we now have a call to the redirect uri as i mentioned before and if you look at the query string parameters you can see the parameters state session state and the important parameter code so this is the authorization code our application will use to request the token now as this is a server-side rendered application i cannot show you how i cannot show you the call to the token endpoint as it is done in the background by our springboot application however i am going to add a breakpoint to the class oidc authorization code authentication provider inside the authenticate method you will see how to access the source code shortly after the demo so let's continue and refresh our page in the browser and now you can see that the execution has paused at the breakpoint and if we observe the variables we have a variable called access token response and id token where we can see the values for access token and id token and if we observe the claims section of the id token we can find the user information here as i mentioned before so the user information like username and also email i didn't provide the email here but if you provide the email when creating the user you can also see that information in here so we can also see the token value of the id token so this is the demo part now let's go ahead to the more interesting section that is for the implementation for that the first thing you have to do is to download the starter code you can find the link to the source code in the description section of this video and once you open the github code you can check out the code and switch to the branch name initial so this branch contains the starter template for this tutorial so we can get started right away and we don't need to spend time in setting up the initial project so once you check out the code make sure you run the class demo application it should be starting without any errors so now let's set up the application the first thing we are going to do is to add the what to dependency to our springboot application i am going to open the form.xml file and under the dependencies section i am going to add the dependency spring boot starter work to client after adding this annotation make sure to refresh the maven configuration by clicking on the icon to the top right side corner if you are using intellij so if you love if you now have a look at the pom.xml we have dependencies for spring web which will activate the spring mvc module in our project and also the time lift starter which will enable the timely features and the last dependency is for testing which we are not going to cover as part of this tutorial however if you are interested i covered this part already in my channel through a practical example so you can you can have a look at the playlist in the description section now our spring boot application is ready to be configured with the oauth 2 capabilities so the first thing i'm going to do is to create a package called as controller under the root project and under this package now i'm going to create a class called as home controller this is going to be the controller which will serve our initial request to the application above the class i am going to add the controller annotation and inside the class i am going to create a method called as home which contains the written type as string and inside the method i am going to return the string called home this is going to be the name of the html file which is going to serve the request no surprises here it's pretty straightforward spring mvc code and lastly i am going to add the get mapping annotation to the method with the value as home so whenever the browser sends a request to the server with the request mapping home it will redirect the request to the home.html page now let's go to the resources folder and here i'm going to create the home.html file under the templates section and this is going to be just a boring html file nothing special here i'm going to add a h1 tag with some welcome message inside the body tag okay so next we are going to configure the oauth 2 client properties inside our spring boot application for that i am going to open the application.properties file and i'm going to type spring.security.org2.client.registration followed by a registration key i'm going to provide the same name as the client id we gave before word to demo time leave client so you don't need to provide this exact name you can give any name you like and i'm going to add the property key client id the value of this property is going to be the client id of the client we created in the previous section the next property is going to be client secret so i'm going to copy the whole property i'm going to copy the client seek from the key clock server and copy it inside the application.properties file if needed you can regenerate this client secret and the next property is going to be scope here you can define different scopes and rules if you want to deal with roles in your application by default we are going to have the scope as open id profile and rules the next property is going to be the type of authorization grant type which is authorization code which is the present example we are dealing with so followed by the property redirect uri as i mentioned before this is the url which our key clock server will call when the authentication is successful we don't need to implement any logic to handle the redirect spring boot security will do this for us out of the box and also this redirect uri is defined according to the oauth 2 specifications so all the magic will be done by spring security here and lastly we have to provide the property called issuer uri this value you can find it by by going to the key clock url open your realm settings and click on the endpoint open id configuration here you can see all the urls which belong to our realm and which are defined as part of the as part of the over through conventions so we have the end point to start the authorization flow and the end point to get the token for this reason instead of adding all these values one by one we can provide only the issuer uri to spring boot and it can refer to this endpoint to make any calls that it needs so if it needs to request a token it can call the token endpoint and if it needs to verify the token it can call the introspection endpoint and if it needs to get the user info it will call the userinfo endpoint and so on and so forth so i'm going to copy this value and paste it inside the application.properties file so that's all we need to do to configure the oauth to client properties in our springboot application so we provided all the necessary information now let's start our server and open the url http localhost 8080 slash home again so you should be redirected to the key clock login page i'm going to type in my credentials and log in and now you can see that the program execution is paused at the breakpoint i added before if not add the breakpoint inside the authenticate method and refresh your browser back to your ide you can see the values for the access token and id token inside the debug section so i hope you understood how to how the authorization code flow mechanism works now the next in the next section we are going to understand how the pixi authentic authorization code flow mechanism works so this is it for this video i will see you in the next video until then happy coding techies
Info
Channel: Programming Techie
Views: 34,590
Rating: undefined out of 5
Keywords: spring security oauth2 tutorial, spring security oauth2, spring security oauth2 authorization server, spring security oauth2 client, spring security oauth2 jwt, spring security oauth2 jwt tutorial, spring security oauth2 keycloak, spring security oauth2 resource server, spring security, spring security authorization code flow, spring security with oauth, spring security with oauth2, oauth spring security example, spring boot security oauth2 - access token
Id: 3BUm0ZlzBLk
Channel Id: undefined
Length: 22min 20sec (1340 seconds)
Published: Sun Jun 13 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.