Fullstack OAuth2 - Angular, Spring Boot & Keycloak

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi and welcome to a fullstack development coding session today we will build a complete O2 secured web application and API backend o 2 is the state-of-the-art authentication and authorization mechanism involving a client identity provider and an oo2 secured API we will set up a locally running key cloak which we will use as an identity provider we will also build an angular web app which will redirect the user to a login page of the identity provider if the user is not already logged in after the login the web app can request an access token and use it to access a secured o or through resource server o or through resource server is just another term for an oo secured API server we will build that with spring Boot and Spring Security all with proper authorization so that only users with a specific role can access certain endpoints so after building a complete end to end oo secured web platform you will become a true fullstack Master let us begin with key Keak so keycloak is an open source identity provider capable of o 2 eventually you will encounter it when working in an Enterprise company we will start kylo as a Docker container eventually you find pre-made Docker and Docker compost files which you can copy paste and just use so that I and I will show and explain to you the most important parts of it don't forget that you can simply get my files from my GitHub link below the video starting with the docker file which is more or less a copy paste from the official key clo guide you notice that we set the environment variable kcdp to postgress that indicates keycloak to use a postgress database also it creates a self-signed certificate for local development purpose now moving on to the dock compose yaml file keycloak needs a database to run that's why we have a post database here the settings are straightforward just some default username and password and create a database with the name keycloak for the keycloak service the previously shown Docker file is used to build a Docker image first that Docker image is run using a bunch of environment variables here you can find settings such as the database URL and credentials also the keycloak admin console credentials which we will use later with this exposed Port we can access the keycloak admin console you notice that we mount a Jason file here this one is used to import a full realm configuration this Json file is pre-made by me and it contains user client and user role config configuration you can reuse that or you can configure it manually I am going to show you how to do that after we start key clo in order to start the postgress and the key cloak open a terminal where the docker compose file is located and then run the command Docker compose up the parameter hi knif and build and forces a Docker build with the keylock docker file after that simply open the keylock admin console URL and log in with the credentials which you can find in the doc compose file if you have imported my realm configuration via the Json file you can find my created realm in this dropdown here are a few important Management areas for example the clients the client with the name my web app client was created by me also in the Realms role area you can find the role fullstack developer which was also created by me and in the users area you can find a user with the name test user one which was also created by me you notice that the user has assigned roles one of them is my own created role and in case you want to configure it yourself just follow these instructions at first create a new realm then create a new client for that client you have to configure a bunch of URLs such as for example valid redirect URLs because our client is a locally running angular web app we set everything to Local Host 4200 then create a new realm role after that create a new user for that user you have to specify a default password and also assign the previously created realm role to that user congratulations the key clo is up and running now let's move on to the angular web app we're going to need an oou Library which implements the login flow and fetches and refreshes the access tokens for that I am using the library angular O2 oidc I have already shown this lip in other videos it is quite good maintained and fully compatible with a variety of oo providers such as keycloak so after creating a fresh angular project we can add the lip via NG at angular O2 oidc so having that lip installed we need to bootstrap our application to initialize the oo service of that library for that I am going to the main.ts file and in there we see the boostrap application function this is responsible for bootstrapping the main app component provided some application configurations in that we must add a few things to the provider's array for once we need to provide the HTTP client this one is needed by our O2 service and we are going to use it to send requests to our spring boot API server additionally we need to provide the oo client this one is from the oou library let us create an out configuration object in this object we add the issuer and the token end points we can get these URLs from the key clo open ID configuration URL it returns ajacent config object containing our needed issuer and token endpoint alongside with a bunch of other config values also in the O config we add a redirect URL which is the current browser location pointing to our angular web app after the user is logged in this is the URL where the user is being redirected also it is important to add the client ID which we have created in our key clo realm another important config parameter is the response type which we set to code there are two different flows implicit flow and code flow the implicit flow should not be used anymore as it is less secure at last we can set the scope of our web app client here I just set some default ones let us create a function to initialize our oo service the function input is of type oo service from the library the function initializes the service as synchronously so do it within the promise at first we provide the recently created o config object after that we set up automatic silent token refresh this is quite handy as the oou service automatically refresh access tokens before they expire then we call the method load Discovery document and login this is a shortcut method which makes the service to load the configuration Json file from keyo and let the user log in if the user is not already logged in and after that happened we resolve the promise so let us add another provider in the provider's array this provider will use the inject ction token app initializer this one is used when you want to invoke some initialize functions when the web app is started that is what we want to do initialize the oo service right when the web app is started by the user so add a factory method with the oo Service as an input and call the initialize oo function declare the oo Service as a dependency and it should work we can actually now test if the user login is working so let us open the angular app and then we see that we are redirected to a keycloak login page in here we see the name of our realm so we can log in with our recently created user so let us analyze what the web app is doing in the browser's developer tools Network monitor for one we see that our web app is calling the open ID configuration endpoint of the key clo this is part of the open myconnect protocol to get a config so the clients can configure themselves using this config Json if you wait long enough you see that the web app is calling the token endpoint of keylo this endpoint returns alongside with some other things the access token keylock returns tokens as Json web tokens the abbreviation of it is JWT you can copy the access token and inspect it on the page JWT doio in here you can see the payload of the Json web token the items here are called claims for example you can find that the user has realm roles assigned along them is our custom role fullstack developer also you can find the name and the email of the user we will extract this information later in our spring boot API server before we continue with the spring boot service let us go back to the app component and add some functional I am going to add a button for the logout functionality in the app component class let us inject the oo service the logout is very straightforward just call the log out function of the service and the user is logged out let us quickly verify that it actually works open the angular web app login if necessary and click on the logout button after the click the user is redirected to the login page again the last missing piece is an oo secured API let us create a new spring boot app with the spring initializer we have to add a few dependencies the first dependency is spring web which enables us to create rest API endpoints with rest controllers the second one is Spring Security obviously we want to secure our API end points with all our access tokens we will configure a security filter chain to enforce security rules the third dependency is O2 resource server our spring boot app acts as a O2 resource server such a server verifies the exess token against the token issuer the key cloak after we open the fresh project in an IDE we create a custom JWT class which extends from JWT authentication token this class will be a container for all revent token data which we will extract from the Json web token this token will be created by converting a generic JWT class into our custom JWT class for that let us create a new class which implements the spring converter interface the input of the converter is a generic JWT class and the output is our custom JWT class we have to override the convert method and implement the conversion logic for the time being let us create an empty list of granted authorities we will take care of that later then let us extract the first and the last name of the user from the generic Json web token class and set those things to our custom JWT object now it is time to configure the security filter chain create a new class for security config here we have to set the configuration annotation so spring recognizes it as a config class also add the enable web security config annotation to enable security chain create a new Bean function which returns a security filter chain the input of the function is a HTTP security object and here we Define the chain at first enable cross origin resource sharing with default settings this is important so the course pre-flight request of the browser is not rejected by the security chain then configure the authorize HTTP request all incoming requests must be authorized then configure the O2 resource server step in here we specify to use our custom Json web token converter in order for the token verification to work we must go into the application properties file and configure adjacent web token issuer which is in our case the key cloak remember that you can find the issuer url in the open ID configuration file from keycloak at last we have to create a controller class the rest controller is the entry point for our API we have to enable course for our angular web app so set the correct allow origin allot haers and allow method let us Define a record which will be used as the return type of the API it contains a message string let us create a function with a get mapping hello it Returns the message record in this function we can access the security context holder to get the authentication we can cast it to our custom Json web token class because we know that our custom Json web token converter is being used in the security filter chain let us prepare a message which we will return containing the first and the last name of the user the API is now secured and ready to be used finally start the spring boot service and then go back to the angular web app to implement the API call in the app component let us inject the HTTP CL Cent after that add a button to trigger the API call when the button is pressed we dispatch a HTTP get request and expect adjacent response with a message text the URL is pointing to our locally running spring boot app also we have to add the access token from the oo Service as a barer token in the HTTP authorization header after receiving the result we simply display the text in a HTML division so now we can actually do an end to endend oou test simply open the angular web app and login if required and then press the button to call the hello API endpoint and let us see if it actually works works there is one final detail left to take care of how do we actually authorize the hello endpoint to be used only by users which have a specific user role we remember that the Json web token contains assigned user realm roles let us go to the custom Json web token converter and extract granted authorities in the generic Json web token we access the realm realm access and in there we access the property row then we iterate all rows and add them into the list of granted authorities with the prefix rcore let us go to the security config class and add The annotation enable method security with that we can add a certain annotation to our hello endpoint function go to the hello controller class and add The annotation pre-authorized to the hello function in there we can use the spring expression language and say has Authority roore fullstack developer this annotation makes sure that only users which have the extracted Authority from the Json web token can access this endpoint we can test if we are still able to call this endpoint with our user so log in again and let's push the button to get the hello text now let us do the negative case and remove the rule from the user in the keycloak admin console so when we log in again and press the button we see in the browser network monitor that our request is rejected with the Response Code 4003 forbidden now you have learned how to secure and authorize API endpoints using O2 and Json web tokens congratulations you have become a true fullstack master goodbye and have a nice day
Info
Channel: Genka
Views: 7,584
Rating: undefined out of 5
Keywords: springboot, spring, springsecurity, oauth, angular17
Id: DLszg2ul85U
Channel Id: undefined
Length: 26min 34sec (1594 seconds)
Published: Sun Nov 19 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.