Spring Cloud Gateway with KeyCloak and OAuth2 | Authorization Server with Spring Security 3

Sdílet
Vložit
  • čas přidán 27. 08. 2024
  • In this video I will show how to configure a KeyCloak server. And I will use it in a Spring Cloud and Spring Boot architecture as an authorization server where a Spring Cloud Gateway will try to authenticate.
    This video belongs to a playlist where I show how to implement an Authorization Server with Spring Security: • Authorization Server
    Content:
    * Create a Keycloak instance;
    * Create some necessary components for an OAuth2 workflow as a Realm, a client, an end-user and some scopes;
    * Configure a Spring Boot resource server to communicate with Keycloak;
    * Configure a Spring Cloud Gateway client server to communicate with Keycloak.
    Repository: github.com/ser...
    My NEW eBook: sergiolema.dev...
    Blog: bit.ly/47ornJL
    LinkedIn: bit.ly/41Nn61q
    Facebook: bit.ly/47rc9nh
    Boost your APIs with API Monitor: bit.ly/4d7C0ny

Komentáře • 109

  • @Encodeum
    @Encodeum Před rokem +5

    The content you have been publishing is very helpful and valuable. It deserves tens of thousands of subscribers and I am sure you gonna reach that number very soon.

  • @calamaroweb
    @calamaroweb Před rokem +1

    Advanced content edited with quality. This channel should have more subscribers. Thanks and keep it up!

  • @ChinyONE
    @ChinyONE Před 9 měsíci

    It´s like your looking into my soul. Great Overview, getting started video. ^^

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před 9 měsíci

      😂 Yes, many people told me the same.
      I try to correct my look in my new videos 😅

  • @wayneyu3031
    @wayneyu3031 Před rokem

    Love your content and useful, i can even apply it in my workspace portal login.. many thanks keep going bro

  • @lannisnguyen
    @lannisnguyen Před rokem

    This is absolutely helpful ♥ Please do more videos about automation CICD pipeline. Maybe sharing about devops culture that your are experiencing or deployment strategies, cost management, risk management, etc. BTW, after attending to a microservice application, I found it painful to setup CICD for the whole system without patterns and guideness 🤣

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      Glad I helped you!
      I was thinking about making some videos about deploying on the different main platforms (AWS and GCP) with different approaches (VM, Docker, Kubernetes, Lambda, static...). What do you think?

    • @lannisnguyen
      @lannisnguyen Před rokem

      @@TheDevWorldbySergioLema It would be extremely fascinating. Give it a little bit of seasoning of automation processes or practicle advice. You could make another tutorial series like the others. Tbh, it really excites me when thinking about it

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +3

      Ok, I will try to do my best. Don't hesitate to share my channel or my playlist in your network, I'm sure you know a lot of people who will be interested too.

  • @narendraingle9668
    @narendraingle9668 Před rokem

    Thanks looking for this contain from long time

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      I try to be consistent with the content I upload. the messages of the community are the motivation to continue

  • @marypaul9627
    @marypaul9627 Před rokem

    here again for your short and on point texcellent tutorials,am implemnting this n am looking how do i create users in keycloack n login from a web app built in either react js or any other framework?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      thanks. In this case, you just call the login endpoint of your API Gateway, the redirection received will be the one of the login form of Keycloak. The rest will be handled by Keycloak until the callback you've configured

  • @lts8683
    @lts8683 Před rokem

    Thanks.
    Can you please talk about the advanced configuration, such as what are the resource that you want to protect and the others that are public...?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      In fact, you should protect everything but the login and create account endpoints.

    • @lts8683
      @lts8683 Před rokem

      @@TheDevWorldbySergioLema but there are some endpoints that is should be public, for example in e-commerce site, we don't oblige users to be authenticated to see the products, to add products to the cart...

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      Ok, I see your point. In this case you have to create multiple routes in the gateway configuration, and add the TokenFilter only on the protected endpoints: github.com/serlesen/authorization-server/blob/main/backend-gateway-client/src/main/resources/application.yml

  • @kennycuevas5175
    @kennycuevas5175 Před rokem

    Hi, I've seen a few of your videos and they are pure quality. At the moment I have the following doubt, in my current architecture I have a database where users register and can access it using your email and password provided at the time of registration. I would like to know if it is possible that keycloak uses those registered credentials to allow access to the user.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      Thanks for your interest!
      You can import your existing users to Keycloak with the Import feature (www.keycloak.org/server/importExport). I've never did it, I don't know how it works.

  • @bartomiejdziadosz8616
    @bartomiejdziadosz8616 Před rokem +1

    The material is very very helpful and powerful like every content from your side bro, I have a question about how I can mock a valid bearer token from Keycloak? In my IT i need to call the keycloak's API for token, and use it for bunch of tests but maybe you know the better way?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      First of all, thank you. Which part are you trying to test/mock? The resource server or the client server? I think that just overriding the Security Filters in the test suite, you should be able to mock the Keycloak part.

    • @bartomiejdziadosz8616
      @bartomiejdziadosz8616 Před rokem

      @@TheDevWorldbySergioLema I have API Gateway as a resource server and functional microservices (name it InvoiceMicro) also as a resource server's. In my case i am trying to mock authenticated request, right now it looks like beforeAll my InvoiceMicro make a call for keycloak for token, save the response as a string and add them to every test with WebClient.
      I am not sure if it's understandable :D

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      The resource server uses the OAuth2 protocol to authenticate the requests. Take a look at the testing with the OAuth2 as done in the following link, stackoverflow.com/questions/29510759/how-to-test-spring-security-oauth2-resource-server-security

  • @dawidd6356
    @dawidd6356 Před rokem +1

    Great video i have learned a lot. Could you help me with choosing an authorization flow for my first party mobile app ? I want to use my app's login/registration screen for it without opening my browser, i have read that i should use authorization code flow + PKCE but without client id/secret on the mobile app but i cant find any information on how to implement it in android - spring / keycloak, what should i request from the app ? the api gateway or the keycloak server directly ? what endpoints should i use ? Only guides i could find were for third party mobile app's using the browser for authorization.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      Hi. Thanks for following me. I've never done it for a mobile app. Did you check this guide, developers.google.com/identity/protocols/oauth2/native-app?hl=en? Your mobile app should request the api gateway. Then the api gateway will redirect the user to the keycloak server. The endpoints to use are the same as done in a frontend application. About not using the browser for the login form, I'm not sure how to do it, as the keycloak server is the one which handles the authentication, and it's the one which informs the user about the scopes. Overriding all of this is like a Man-In-The-Middle attack.
      If you find something more, i would be interested in your results.

    • @dawidd6356
      @dawidd6356 Před rokem

      @@TheDevWorldbySergioLema Ok i have learnt that i should use "Trusted Web Activity" in android and that its a security risk to run authentication on the app native screen so i am doing that sadly with that approach i wont be able to utilize on many android features for example on the dynamic wallpaper colors but i will have to live with it.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      Ok, I see. What you can simply do in your API Gateway, is redirect all the oauth2 requests to an internal microservice (as the Authorization Server) which will be responsible for the authentication. Don't know if this can help you.

    • @dawidd6356
      @dawidd6356 Před rokem

      @@TheDevWorldbySergioLema Thanks for the advice i have actually considered this but decided that going with the standard secure way (using keycloak) will be optimal as i have no real experience in DevSecOps. And thanks again for this video i have seen it countless times trying to understand oauth with keycloak and spring cloud gateway and it helped me a lot

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      Yes, using the standard way is the best choice. And thanks again for following me (don't hesitate to share my channel in your network, maybe some more can be interested in my content).

  • @tonybroadbent2993
    @tonybroadbent2993 Před rokem

    Good tutorial thanks, but I do have a question, I tried to follow the tutorial but use a MySQL db in the docker-compose of backend-keycloak-auth and ran into a number of errors arround Access Denied to the db etc. Does this iamge have to use Postgres, or do you have an example of it using a MySQL db?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +2

      Thanks. I'm sorry, but the project only works with PostgreSQL. Still it should't be hard to adapt it to MySQL. Check this docker compose file offered by Keycloak, github.com/keycloak/keycloak-containers/blob/main/docker-compose-examples/keycloak-mysql.yml

    • @tonybroadbent2993
      @tonybroadbent2993 Před rokem

      @@TheDevWorldbySergioLema Thanks for the quick reply. Would the Postgres db used in this project, also used be used for other micro services in a wider project, or is this db only for the keycloak instance?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      For security concernes, I recommend you to leave this database isolate to other systems. As you already isolate the logic (having Keycloak as a separate authentication service), isolate the data too.

    • @tonybroadbent2993
      @tonybroadbent2993 Před rokem +1

      @@TheDevWorldbySergioLema Great thanks again for the quick reply!

  • @treefrog9392
    @treefrog9392 Před rokem

    hello, what if we wanted to have multiple microservices and secure them with tokenRelay?
    how would I create users? Or how would I submit a post request at all? I'm always getting a csrf error, even though I disabled csrf on all my spring security filters.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      In this case, letting the Gateway being the resources server will be the best option. This way, you only have one microservice (the API Gateway) which has all the configuration about the OAuth2 flow, then, the inner microservice use the JWT and always trust the incoming requests from the API Gateway (I'm preparing a video with this configuration, hope it will be ready soon).

  • @TheZiomartin
    @TheZiomartin Před rokem

    Hello Sergio, thank you very much for your tutorials on Spring OAuth2. I'm learning so many things.
    I have some concerns about using the Gateway as a client, if for example i have a spring boot client application trying to access my services via the Gateway, how will i configured it since Gateway is already implemented as a client ? Isn't it better to rather have spring cloud gateway implement as a resource server ?
    Hope you will have time to answer.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      First, thank you for following me. As indicated in the first video of this playlist, you can have just 3 Spring Boot application to handle this authentication pattern. If you want to introduce a Spring Cloud Gateway application, you can do it as the client server (as done in my second video of this playlist) or as the resource server. Using a Spring Cloud Gateway in any of those cases won't change the way the pattern is implemented. It will depend on how your architecture is implemented: if you have a lot of resources microservices to dispatch the information, I would put the Gateway as the resource server; if you have a complete microservice architecture which reads a single resource server, I would put the Gateway as the client server; or you can even combine both and have a Gateway in both places. The usage of the Gateway will depend on what's behind: a single service or multiples. I hope my answer helped you.

    • @TheZiomartin
      @TheZiomartin Před rokem

      @@TheDevWorldbySergioLema Oh thank you for that detailed answer, i though the same too. Once again your w are really Amazing. Thanks for taking your time to share things with us.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      Glad it helped you. Don't hesitate to share my channel, maybe someone in your network will also be interested by my content 😉

  • @user-zt7tn3xy3y
    @user-zt7tn3xy3y Před 3 měsíci

    What is "etc/hosts". You just showed random picture with some strings, but where is it and how to add it there?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před 3 měsíci

      It's a file in the Linux-based OS where you can create aliases for localhost.
      It's at "/etc/hosts". You need to add the lines I've shown in the video to add another alias for localhost.
      The aliases are needed, otherwise, Keycloack won't be able to distinguish the authentication server from the resources server from the client server (as all are localhost).

    • @user-zt7tn3xy3y
      @user-zt7tn3xy3y Před 3 měsíci

      @@TheDevWorldbySergioLema Thanks for explanation! :)

  • @johncerpa3782
    @johncerpa3782 Před rokem

    Nice !

  • @snowy0110
    @snowy0110 Před rokem

    How the setup would look like if several resource servers a behind the gateway, each with their own scopes? Every time a developer creates a new resource server behind the gateway, there will be a need to update application.yml of the gateway with all new scopes? I don't get it

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      Yes. You must adapt your gateway each time a new resource server is added: the redirection route must be specified, the authentication protocol, the scopes...

  • @TikTokTrendsCompilation

    what is the difference between implementing normal jwt with spring security vs using this keycloak?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      Using a JWT, you need to store username credentials into your application. This way you can generate a JWT once validated manually the credentials.
      Using Keycloak, you don't need to store the credentials into your application. All is managed by Keycloak. And Keycloak may be managed by another team or company.

  • @poomc5462
    @poomc5462 Před 11 měsíci

    Hi!
    I followed your tutorial and got up to the login with keycloak. Once I logged in, the backend-gateway returned a 404 error. The routing for request to through the gateway is not registered because the backend-resource on its own works. Do I need any kind of service discovery such as Eureka in order for the routing to work?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před 11 měsíci

      A problem I saw was that the browser stored the authentication cookie for localhost (which is the address of all the services) and is unable to distinguish the services. That's why I used alias for each service. This way, even having different port numbers, there is a different name for each service.
      Did you try adding the alias?

    • @poomc5462
      @poomc5462 Před 11 měsíci

      @@TheDevWorldbySergioLema yes I did try adding alias in the etc/ route with the three different names for keycloak, gateway, and resources. The resources and keycloak login work on its own but not through the gateway. I tried commenting out keycloak and oauth from my code, and test the gateway + resources alone, but still 404 error when I call through the gateway.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před 11 měsíci

      Try adding more verbose logs on the Gateway. Sometimes the 404 hides another error. Create a simple unprotected redirection from the gateway to the resources, it must work. Then add gradually, the headers redirection and the authentication to see which one is causing the problem.

  • @seatconnect224
    @seatconnect224 Před rokem

    what is the real case of using KeyCloak on production, may be there is some API for creating users instead of doing its manually in console?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      The best scenario to use KeyCloak is when you want to have a single authentication system for multiple applications. Let's say you're working on a company which have a backoffice to manage the products, some APIs built by other clients but consumed by the company, a mail server...
      All those applications are used by the same people. Instead of creating an account on each system, you can have KeyCloak as a SSO (Single Sign-On).

    • @seatconnect224
      @seatconnect224 Před rokem +1

      @@TheDevWorldbySergioLema thank you for reply!
      May be you can create some video with real case example, but any way thank you for your work

  • @andreamonte851
    @andreamonte851 Před 11 měsíci

    Hi. Useful tutorial. How can I add method authorization using Keycloak and spring security 6.1 ?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před 11 měsíci

      That's a good point. I've never use the Authorization in a Resource Server. I'll take a look at the documentation

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před 11 měsíci

      From what I've read quickly:
      * You need to add the roles to the users in Keycloak
      * In the resources server, you add the annotation EnableGlobalMethodSecurity
      * in the endpoints, you add the PreAuthorize annotation
      About the 2 last points, you can check this video for more details: czcams.com/video/ZBeyy4Q3nIw/video.html

    • @andreamonte851
      @andreamonte851 Před 11 měsíci

      @@TheDevWorldbySergioLema client roles or realm roles? I need also a JWT converter? I tried with method annotation without success...

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před 11 měsíci

      User's roles. And you don't need a JWT converter, as the roles come in the JWT and are translated to the Authorization bean (which is used in the PreAuthorize annotation).
      That's the theory, I didn't test it.

    • @andreamonte851
      @andreamonte851 Před 11 měsíci

      @@TheDevWorldbySergioLema It works!

  • @light.yagami787
    @light.yagami787 Před rokem

    Why would you use the legacy image of keycloak?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      You're right, I should have used a fixed version (don't remember the one available when making the video).

  • @DamLee88
    @DamLee88 Před rokem

    hello! good one! how can we have one single project that uses at one side backend-resources with controller/config and on the other the gateway at port 8083 for the Kc login? thanks

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      Thank you.
      Maybe I didn't understand the question, but I think that was what I explained in the video.
      You have the backend-resources behind an API Gateway. Aside, you have the Keycloak which handles the authorizations.
      Check the Github project, github.com/serlesen/authorization-server/tree/chapter_3

  • @codingstyle9480
    @codingstyle9480 Před 11 měsíci

    Hi thanks for the video. Would you have any idea as to how could one integrate this setup to an angular application with role-based authorization?

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před 11 měsíci

      I've done the integration with React, czcams.com/video/hfeOqvHxHO8/video.html (not yet with Angular 😉)
      About the role-based, you must define the user's roles in Keycloak, then add the annotation EnableGlobalMethodSecurity and use the annotations PreAuthorize on the controllers to control the access per roles.

    • @codingstyle9480
      @codingstyle9480 Před 11 měsíci +1

      @@TheDevWorldbySergioLema Thanks for the reply. I meant the angular side actually? The backend side is OK. Let me have a look at your React version.

    • @codingstyle9480
      @codingstyle9480 Před 11 měsíci +1

      @@TheDevWorldbySergioLema Hi, I have just had a look at your react-cloudgateway-resourceserver-keycloak combination. I deduce the following fom the code. Please correct me if I am wrong, or you might need to add something more to my deductions. 1)Cloudgateway server has no spring security code other than the cors setting and relaying the request from the front-end to the required end-points in the resource server. 2) Front-end has an "auth_helper.js " file which creates a UserManager object by way of oidc-client.js file using the keycloak-settings parameters related to the client. So the Keycloak only knows the front-end. 3) When sending a request from the front-end to the gateway server(and then to the resource server), the front-end gets the access-token from the keycloak server (front-end does not store access-token in local storage) by way of UserManager object and does its request adding the token to the request header(Here you use axios to send the request). One question here: Probably we need to get from the token the role of the user so that we can carry out a role-based preliminary request-filtering at the front-end side. 4) Resource server has all the code and settings to accept the keycloak server as the token provider plus the role based authorization of its end-points. Thanks.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před 11 měsíci +1

      I think this is about the video of the React integration with Keycloak.
      1) Yes, the Gateway has no security logic;
      2) All the authentication is handled by the frontend, that's why we need to configured the Keycloak client differently, without client-id, client-secret;
      3) Yes, the frontend use the token from Keycloak to request the API gateway and the resources server. If you add the roles to the user, the JWT will have them, then it's the job of the resources server to check the roles of the JWT with the annotations PreAuthorized
      4)That's right, the resources server will consume the JWT and accept of deny access if you configure a role based authorization

  • @mailtoharutyunyan
    @mailtoharutyunyan Před rokem

    Hi friend, I have one questio. It is possible to create some registration forms in angular and create users in keycloak. Thanks.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      The users must be created in Keycloak. But you can have your own login page, you only have to say to Keycloak if you want to use the default Keycloak login page, or your login page.

    • @mailtoharutyunyan
      @mailtoharutyunyan Před rokem

      @@TheDevWorldbySergioLema thanks for answer, can you create tutorial how we can do it ?.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      I'll put it on my todo list 😉

  • @rajivkumar-ub6uj
    @rajivkumar-ub6uj Před rokem

    How to apply concurrent session control per user in this architecture? If I say it should not allow multiple login sessions per user across the devices

    • @rajivkumar-ub6uj
      @rajivkumar-ub6uj Před rokem

      I know about session management in sprin security not sure how it fits in this oauth 2 flow with spring Authorization server kindly provide your views on this

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      You can do it from keycloak: stackoverflow.com/questions/43347758/disable-multiple-login-at-keycloak

    • @rajivkumar-ub6uj
      @rajivkumar-ub6uj Před rokem

      @@TheDevWorldbySergioLema yeah we are aware of this feature at keycloak but trying to achieve with spring Authorization server

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      I've never used this approach on the authorization server. Maybe you can try something like what I did in this video (serializing the session in Redis): czcams.com/video/YWVjnJsJRG0/video.html

  • @mars3142
    @mars3142 Před rokem

    Can you create a tutorial without the "legacy" mode of Keycloak?

  • @user-df9lg3og6z
    @user-df9lg3og6z Před rokem

    Don't want to record a video in which the bundle is OAUTH 2.1 + OAUTH-Server + Gateway + RegisterServer + Angular (with registration form)

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      Woauh! That's very specific.

    • @user-df9lg3og6z
      @user-df9lg3og6z Před rokem

      @@TheDevWorldbySergioLema Do you mean to say that such a bundle is almost not used? As far as I understand, Spring has released a new version of OAUTH 2.1. It is completely redesigned and very different from the old one. Perhaps this is a very good solution. You will be the first to provide material on this topic.

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      I will take a look

  • @aloisvollmaier344
    @aloisvollmaier344 Před rokem

    Can you please show how to handle a 320 redirect in Angular? My app is not working as expected :( - i have the same setup: 'angular -> spring cloud gateway -> some data
    service'

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem +1

      I've done it with React. You must just read the HTTP code, check if it's a redirection, and call the Location header if needed. If you delegate the request to the browser, the redirection is done automatically.

    • @aloisvollmaier344
      @aloisvollmaier344 Před rokem

      @@TheDevWorldbySergioLema is your project open source? Would be great :)

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      Yes, you have it in the description of the video. Here is the link, github.com/serlesen/authorization-server/tree/chapter_3

    • @aloisvollmaier344
      @aloisvollmaier344 Před rokem

      @@TheDevWorldbySergioLema i mean the react part :)

    • @TheDevWorldbySergioLema
      @TheDevWorldbySergioLema  Před rokem

      Oh sorry, I've just made a quick test and deleted the code. Sorry

  • @MaximShvedov
    @MaximShvedov Před 5 měsíci +2

    тяжело

    • @user-xb2dv2ew6j
      @user-xb2dv2ew6j Před 4 měsíci +1

      Та что то материалов нормальных нет... Тоже туго так, жесть

  • @ElRaizBTSid
    @ElRaizBTSid Před rokem

    bro calm down, who holds you against your will?