Spring Cloud Gateway with KeyCloak and OAuth2 | Authorization Server with Spring Security 3
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
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.
Thank you for those kind words. I hope this will be true soon 😅
Advanced content edited with quality. This channel should have more subscribers. Thanks and keep it up!
Thank you. I hope this will be true soon 😅
It´s like your looking into my soul. Great Overview, getting started video. ^^
😂 Yes, many people told me the same.
I try to correct my look in my new videos 😅
Love your content and useful, i can even apply it in my workspace portal login.. many thanks keep going bro
Glad to hear that
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 🤣
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?
@@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
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.
Thanks looking for this contain from long time
I try to be consistent with the content I upload. the messages of the community are the motivation to continue
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?
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
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...?
In fact, you should protect everything but the login and create account endpoints.
@@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...
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
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.
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.
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?
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.
@@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
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
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.
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.
@@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.
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.
@@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
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).
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?
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
@@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?
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.
@@TheDevWorldbySergioLema Great thanks again for the quick reply!
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.
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).
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.
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.
@@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.
Glad it helped you. Don't hesitate to share my channel, maybe someone in your network will also be interested by my content 😉
What is "etc/hosts". You just showed random picture with some strings, but where is it and how to add it there?
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).
@@TheDevWorldbySergioLema Thanks for explanation! :)
Nice !
Thank you John
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
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...
what is the difference between implementing normal jwt with spring security vs using this keycloak?
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.
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?
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?
@@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.
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.
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?
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).
@@TheDevWorldbySergioLema thank you for reply!
May be you can create some video with real case example, but any way thank you for your work
Hi. Useful tutorial. How can I add method authorization using Keycloak and spring security 6.1 ?
That's a good point. I've never use the Authorization in a Resource Server. I'll take a look at the documentation
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
@@TheDevWorldbySergioLema client roles or realm roles? I need also a JWT converter? I tried with method annotation without success...
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.
@@TheDevWorldbySergioLema It works!
Why would you use the legacy image of keycloak?
You're right, I should have used a fixed version (don't remember the one available when making the video).
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
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
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?
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.
@@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.
@@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.
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
Hi friend, I have one questio. It is possible to create some registration forms in angular and create users in keycloak. Thanks.
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.
@@TheDevWorldbySergioLema thanks for answer, can you create tutorial how we can do it ?.
I'll put it on my todo list 😉
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
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
You can do it from keycloak: stackoverflow.com/questions/43347758/disable-multiple-login-at-keycloak
@@TheDevWorldbySergioLema yeah we are aware of this feature at keycloak but trying to achieve with spring Authorization server
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
Can you create a tutorial without the "legacy" mode of Keycloak?
I'm not sure about what is the "legacy" mode of Keycloak.
Don't want to record a video in which the bundle is OAUTH 2.1 + OAUTH-Server + Gateway + RegisterServer + Angular (with registration form)
Woauh! That's very specific.
@@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.
I will take a look
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'
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.
@@TheDevWorldbySergioLema is your project open source? Would be great :)
Yes, you have it in the description of the video. Here is the link, github.com/serlesen/authorization-server/tree/chapter_3
@@TheDevWorldbySergioLema i mean the react part :)
Oh sorry, I've just made a quick test and deleted the code. Sorry
тяжело
Та что то материалов нормальных нет... Тоже туго так, жесть
bro calm down, who holds you against your will?
😅
@@TheDevWorldbySergioLema really nice tutorial tho, thank you!
Thanks for watching Muhamad!