Microservices Security Using JWT | Spring Cloud Gateway | JavaTechie
ฝัง
- เผยแพร่เมื่อ 30 ก.ย. 2024
- This tutorial will guide you How to secure your microservices with with JWT Authentication using Spring Cloud Gateway.
We are going to discuss an architecture in which one microservice will act as a api gateway service which does central authentication, redirect an incoming request to other microservices. The main advantage of this architecture is you can easily add multiple microservices to the system and all authentication, authorization will be taken care from a central unit
#Javatechie #Microservice #Security #JWT
Spring boot microservice Live course Just started (Recordings available)
Hurry-up & Register today itself!
COURSE LINK : javatechie5246...
PROMO CODE : Java40
GitHub:
github.com/Jav...
Blogs:
/ javatechie
Facebook:
/ javatechie
guys if you like this video please do subscribe now and press the bell icon to not miss any update from Java Techie
Disclaimer/Policy:
--------------------------------
Note : All uploaded content in this channel is mine and its not copied from any community ,
you are free to use source code from above mentioned GitHub account - วิทยาศาสตร์และเทคโนโลยี
Could you explain me : Client -> Security Service (GenerateToken) -> API Gateway -> MicroService1 (validate JWT) this flow is fine . What happen we request come directly to Client-> Microservice1 . How to check JWT for each endpoint.
How to block each microservice endpoint to access??
I feel like your explanations are even better than people who have english as their first language lol. You really do have a gift for this!
Hi Basant ,
Very useful tutorial however I have one doubt, In production when the token is generated by passing a valid username and password it should automatically pass the token to the gateway right but here I saw that you are manually passing the token to the gateway through Postman for accessing microservices, My question is how we can automatically pass the token to the gateway for accessing microservices when the token is generated
Your question is genuine but this automatically stuff needs to handle from UI not from the backend
@@Javatechie ok thank you!
I love you. Finally the architecture I'm looking for. A lot of tutorial are covering authentication for only one microservice and you are probably the only one that approaches the problem keeping in mind the whole microservice architecture.
Thank you so much Lukasz for appreciating my work 🥰🥰
you worth millions of like
Hi sir! I am grateful for this tutorial. In this tutorial you have two client services, one gate way, one security service and you added security in Api Gate. I like the way you did it. But i need to move forward and add some Authorization. Suppose in swiggy service there are some end points what only admin can access and some end points normal user can access. How to apply this type of Authorization. Would you please make second part of this tutorial please? I am following this tutorial and trying to learn. I tried to implement the security directly in the API GATE-WAY service. But that was not easy because gate-way supports webflux not the web.
make use of method level authorization and roles
Yes I am still not finding any solution for this approach. Will check and update you
@@Javatechie Thanks
@@Javatechie I saw others using OAuth2 to solve this problem. KeyCloak is one of them.
@@Javatechie Hey, I found your video helpful, however I wanted to inquire, did you find any solution for this approach?
Bro, thank you!!! God bless you!!!
1:11:00 The rest call from gateway to auth service is not working. It is throwing an error saying cannot call from java.lang.illegalstateexception: block()/blockfirst()/blocklast() are blocking, which is not supported in thread reactor-http-nio-1. Please let me know if someone can help in this
why did you copy the code of "/validate" to gateway? It's useless now in the identity-service if you run this piece of code from the gateway
Rather than doing another rest call to identity service i have used it in gateway itself
@@Javatechie i get that, but if this was the goal all along, then why did we implement this in the id-service to begin with? I want to avoid duplicate code.
This Video is really helpful, Pls. Can you cover Role base authentication and Authorization on the individual microservices?
Wow Very Nicely Explained In Easy To Understand Manner.
1 Request can you please show how to implement role based authentication with Spring API Gateway ?
Yes buddy it's in queue i will upload soon
I am new to microservices & your videos helped me a lott🙌🙌 also can you please tell me, what should I use for role based authorisation in microservices.
I am working on project which is a web portal for sanctioning government applications, It has user & admin as roles.
Please guide🙌
I am working on jwt token microservices.
How to logout user or expire token imediate?
Great Video sir, completely Awesome...Add the role based security through api gateway.
Finally found an understandable tutorial about securing a Spring Cloud Gateway microservices architecture! A thousand times thank you sir!
Awesome videos. Hats off to you in explaining it in a very simple and easy manner. One question.
May I know if we have a requirement to secure our swiggy and restaurant service endpoint and grant access based on role, then how we can achieve this requirement .
Hello sir. there is api still open for each microservice. like calling the order in it's own microservice with port like localhost: 8082 then api is open . if anyone can call that api wihout gateway and security then what is the usage of jwt ???
Simple question can you please answer me how the user will know about the endpoints of your microservice ?
@@Javatechie using url or somehow user know the endpoint or hacker know the endpoint. so the endpoints are not secured for each MS. you have to reconsider your code and try to figure out how to secure all the endpoints separately also
@@hkkabir2024 no buddy it will be known by user only if you exposed it . If we are doing that then it's the wrong approach then what is the need for a gateway?
This video is very useful for me . Thank you for your time and explanation
In Gateway service, can you please show us role based authentication. You just showed authentication part but not authorisation. Please show us. It’s very important
Brother " Set interface how remove duplicates internally " please explain because yesterday interview i am unable to answer simply rejected for this reason
It internally uses map buddy i already explained in my interview QA videos please check
@@Javatechie ok thanks 😔
Thanks for sharing this video.
I have one question. Do we need of validator.isSecure for endpoints /token, /register, /validateToken? I think no because we are not applying filter for IdentityService then obviously API Gateway will not use the filter. Please correct me I am wrong.
Yes it's required otherwise wise how can we bipass the request. Currently I am not calling identity service api but as per best practices it's good to do rest API call to validate the token hence above URL required to bypass
great job Sr. does it come with new spring boot verison
Hi @javatechie
I have a question. What is i dont want to validate the token in cloud-gateway. every request which is coming to gateway and cloud-gateway has to call identity-service to validate the token and send back to cloud-gateway and based on the response it will call the endpoint or throw an exception. Is it possible ??
Yes it's absolutely possible that is what I explained in PPT but while explaining code I have added validateToken logic in gateway but you can do that easily just refer flow it will be dead easy
My English is poor. Maybe you talked about this. I understood correctly that in a real project we do not need to create a method for validating tokens in the identity service, because validation needs to be implemented only in Spring Gateway?
We can keep it in the gateway that's what I did in this video but it's a bad practice because the key thumb rules of microservice is to segregate functionality to different modules so if I keep security and routing in the same application then it violates the principle isn't it?
Basant can you tell me how to JWT token pass through one service to another service as we only sent the payload (order details) to call restaurant API. Here how JWT propagation happening
Jwt will only pass to api gateway for authentication It won't pass to other microservices Please debug the filter class you will understand
Quite informative, thanks!
instead of completely using spring cloud stack we can make this more OSS (open source stack) like every micro service is containerised (dockerised) then use KONG as API gateway. this way we can make the configuration more simple and reduce tight coupling.
Could you please explain more about how that works?
can you please come with your hands on similar like this using KONG.
For h2 db modify the securityFilterChain in AuthConfig as below
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.headers().frameOptions().disable()
.and()
.csrf().ignoringRequestMatchers(PathRequest.toH2Console()).disable()
.authorizeHttpRequests()
.requestMatchers("/auth/save","/auth/token","/auth/validate").permitAll()
.requestMatchers(PathRequest.toH2Console()).permitAll()
.and().build();
}
Hello Sir ,
In spring data mongodb one annotation is there @Encrypted , How can i use for Encryption with AWs KMS please make a video for this topic
One more , How to modify RequestBody, response body in Interceptor and pass to controller.
Okay i will do this
really helpful, but I have a doubt, what if someone directly access the microservice url by bypassing the api gateway. how to handle that?
How does someone know your URL, if you are sharing then it strictly breaks the microservice contract
sir please provide the link from where i can start from developing swiggy and restuarent microservice along with service registry in eureka server....Thanks
Please checkout the video description I have shared the code
Thaaaaaaaaaaaaanks man! nice video
Won't the rest template call to identity service will be blocking and will lead to an issue?
Yes it should be synchronous
the source coude keeps crashing with intenal server error. Do you have any suggestions about it? Thanks in advance
Can you please share the exact stack trace in javatechie4u@gmail.com
i have a question, what if i have 3 microservices (agency -> service -> activities ) and i want to get all activities from the services that an agency offers, do i need to ask for the token 3 times?
It should be done in one go , simply we are applying security on the entry point not in individual microservice
Thank you so much !!
But how can we restrict direct access to individual microservices
Only one way to avoid exposing them
Thank you! but i have a question! is this enough in term of security in my application and how can i add more security layers
This is the way to implement in microservice but if you want more secure then better use 3rd party identity providers like okta or keyclok. I already uploaded a video of keyclok using microservice
Thanks for sharing ❤
But how can we authenticate based on role.
Here we can access the whole microservice but how can we access some end points of one microservice and other endpoint for another role.
I've been waiting this long, thanks java techie greetings from peru😎
At last, how to send user info from api gateway to swigy app after filterchain in api gateway validates token
You can set it to the header of the api call . I will do a video since i found multiple viewers having the same doubts
How to exclude some API from applying Jwt in the headers.
Configure those api which you want to bypass in security config class with antMatchers
Awesome video.
How could I add roles authorization? Thanks from Colombia
Roles even i am looking for that solution.will update you
Hey Basant, Once again you delivered nice content which we were looking since long time. I locally setup up and tried it working fine. I have a concern here
If user directly request to 'Swiggy App' or 'Restaurent Service' then he able to get all details without providing JWT token.
How secure these 2 apps if user directly send request?
Hi Rahim think practically why you will expose swiggy and restaurant microservice endpoints directly to the end user. If that is the case API gateway itself is no use right .
So we should only expose api gateway endpoints that is how we can force everyone to use gateway with token
@@Javatechie Hi that was a great explanation, but I have a question. Is there any way we can secure swiggy and restaurant microservice and use it in gateway as well?
Again we landed in the same context . If this is your requirement then you should avoid using gateway
@@Javatechie We can make secure swiggy and restuarent apps too.
Currently I am on similar kind of project where we secure each microservices app.
I will update here later.
@@rahimkhan-fh9dd Can you provide more details. It would be helpful. Thanks.
Nice work man, please implement the swegger this application which is used for api documentation, thanks in advance
Best course available in youtube. Thankfully it is free. Keep up the good work
How to stop direct access to swigging and restaurant, and only access via gateway?
You need to configure cross origin
Hi Basant, Its really good explanation, I have one doubt, how should we handle @PreAuthorize in our microservices in case we are following this pattern.
Please do answer me , its really urgent for me.
Hello Shivansh , I am also not sure about your question if we will go with pre Authorize annotations then in every microservice we need to implement security but that's what is not advisable.i am looking into solution will update you once I find
@@Javatechie thanks
Explained very well. My doubt is if there are 100s of microservices all the call will go through API gate way and the auth Service, how to handle API gateway or auth service failure ?
You need to handle it through DR . In microservice world 🌎 no guarantee of 0 downtime
@@Javatechie thanks
Great explanation, but you only cover authentication part dosnt cover authorization , can explain that
Thank you so much. Can you do a video share how to config authorization with JWT in microservices ?
Thank you very much for the video., if restaurant service has to call swiggy service using rest template, now we have to include jwt token in httpheaders otherwise we will get 401 authorization as we have implemented jwt authentication is my understanding correct please let me know
No phani , we haven't implemented security in microservice level we have added on gateway level so inter communication doesn't require any authentication mechanism
@@Javatechie 🙏🙏👍thanks
bro why you make video too long, why you not make video per part or per episode?
YPdw this content needs to be delivered in a single video otherwise it's difficult for both of us to sync with context .
I agree the video duration might be more because we have not compromised on content each and every concept i delivered with clarity .
Hi Sir, actually regarding sso in every TH-cam tutorial up to okta telling, but how to modify the database of existing application because already users everything is present, please suggest any video on this.
I will cover this
@@Javatechie thank you so much sir for your quick reply
How to get current authenticated user from all other microservices?
The only way I need to pass principal info as part of the request header while calling api from other microservices
Thank you! how is it going if i have the UserData in an other service, is there any video with this case ?
In our case also user data available in other services right
Why did you create bean UserDetailsService if CustomUserDetailsService anotated with @Component?
Wouldn't it be better create argument UserDetailsService into authenticationProvider method?
Buddy i create a bean of interface where the implementation is CustomUDService
@@Javatechie Isn't it unnecessary to create a bean? @Component itself creates the bean, you can simply pass it to the method?
Got your points and Agree buddy
bro you helped me a lot, thank you very much and greetings from Argentina
Its a very best content which i ever seen in across youtube .. thanks basant keep it up..
me too
Hi, How do i access current user from other microservices? such as restaurant-service?
From api gateway extract logged in user ID or name then pass it as part of headers while redirecting it to other API
Excellent work , but the website u use for getting the secret is not working any more . so people are suffering to get the secret and cant able to use the full potential of the work you have done here . pls give an alternative way to get secret from else where . i was suffering for a week for validating JWT and routing . this came as a life saver . Thanks much for a fablous work . i would like to do a donation . if u have any payment portal pls let me know .
Ohh is it , the last time I tried it works since these are open-source we can't predict from any website will check alternative and update in thread
Hi @@Javatechie , Appreciate you're reading the comments . if you make shorts for generating the secret please share the link here and the spring security video description .
52:00 Auth service integrate with Gateway
56:00 Validate token
Sir u have used only user name and password with token to validate the api of other service like swiggy and other service but how to do when I add role based authentication to active the different api of different service (role based authentication using in api gateway) plz make a video
I haven't found a direct solution for role based authentication and Authorization but what i understand is that we need to create a separate service for admin and users and can define that in the api gateway.
@@Javatechiesir can you make a video plz... So that i will be helpful. Multiuser login is very important concept in microservices design pattern
Thank you for this wonderful video❤️❤️
THIS IS THE VIDEO I WAS LOOKING FOR, THANKS SO MUCH FROM COLOMBIA
Nobody explains like you do..Thank you very much for the video.
Thanks aTon Sir ❤, No one can match your Explanation level 👍
Hello Sir, is it possible each microservice to have its own user and password. A token generated to only access the specific service to which the user belongs?
Yes you need to play with an api key specific to the microservice
@@Javatechie thank you very much, let me check and apply
Very good explanation, have one doubt in jwt tutorial you mentioned to validate token you passed token and user details object , but here in api gateway you are passing just token , what if I modify token , and how api gateway is validating modified token since we are not passing user details object
In jwt from token we extract user details . We Don't pass user details explicitly
@@Javatechie was mentioning about below method , can u plz explain here we are just passing token we r not extracting username
public void validateToken(final String token) {
Jwts.parserBuilder().setSigningKey(getSignKey()).build().parseClaimsJws(token);
}
Please Debug parseClaim method you Will understand from token what all we are extracting
it's awsome,,
I was trying to solve this kind of problem and this tutorial helps me a lot.
Thank You so much for the video tutorial.
Why did you not use the api gateway port number to get the token?
Yes I have used the api gateway port only because gateways interact to identity service
Hello basant, should I define the sessionCreationPolicy to SessionCreationPolicy.STATELESS inside the securityFilterChain to precise I don't want to use jsessionid ?
It's good to have
It is authenticated only when it routes through the gateway. But the end point for the micro services are still open how to secure that?
I think we need to implement spring security at service level for each service
Is there any solution for this issue?
@@ahammedhussain9335 I think the services need not to be public, so we cannot access them directly, we can only access them through gateway as the end user, and at gateway we filter request to check for the token and authentication for routing the request to the appropriate service.
No no just implement cross origin bro
@@darshanrajashekhar5914 please elaborate
How i will get current user and its roles in other microservice
In each service you can call UserdetailsService to get user info
I keep on getting 401 Unauthorized when I try to access other endpoints available from my API-Gateway. I can get the token with /auth/token, I can validate it, but for other endpoints I always get 401. I checked the code over and over again, it doesn't look like I missed something.
Please check the configuration and compare it with my code . I guess there is an issue with antMatchers or what I have definitely secured url
@@Javatechie problem solved
What was the issue
@@Javatechie If I try to dockerize my app with docker-compose I run into the same problem, I keep getting 401. Do I have to somehow provide a new secret to the docker image than the one used in the app?
Awesome video Bhai.. much needed.. thanks a lot for the content shared. 🎉
Let me ask you a question. If, for example, I try to access the restaurant service directly (giving the restaurant service port), that is, without going through Gateway, I will skip the validate token part, right? So the restaurant service isn't protected at all, is it?
Then what is the need of the API gateway buddy? If you will directly expose your microservice endpoints to users
@@Javatechie The point is, if a hacker knows the port of my services (for somehow), he can easily access them.
Do you get any solution regarding this
@@Javatechie then how disallow it...?....bcz if somebody knows our port...he can access it
Knowing only port how someone can access buddy? We shouldn't expose our microservice endpoints even though it's exposed then we need to implement cross origin so that if the request comes from only api gateway then only allow that.
Thank you so much Basant for this tutorial, but getting one issue which integrating api gateway to angular,
Failed)net::ERR_NAME_NOT_RESOLVED preflight Preflight
Please tell me what to do to resolve this,
Thanks in advance!!
Please drop me an email to javatechie4u@gmail.com with complete error stack trace
Thank you very much for providing such a detailed explanation. Your video is undoubtedly superior to paid courses that tend to overcomplicate things and stretch on for more than 8 hours.
I have a question: If I were to call Swiggy or a restaurant service directly, bypassing the gateway or discovery service, how would I handle authentication?
you can't but you can make that api endpoint in api gateway itself
Nice video we learn couple of thing related to microservices and spring security ❤❤❤
How to implement with role and permission on security?
Firstly Thank you for all your tutorials. I tried this api gateway implementation and getting "An expected CSRF token cannot be found" when calling authenticate or register apis through gateway. It works if I directly call authentication service. Could you please help with this.
Hi Sir,
I have implemented filter as per ur logic but I need to call identity-service in order to validate the token, but when I call the identity service using resttemplate I get the following error :
java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-3
So can u please help how can we resolve this.
Yes simple please use web client instead of rest template
Sir since we are in already in reactive phase, and we need to somehow need to block the code to validate the token, so once I used webclient with blocking , I get the same exception, and I can't use reactive response here
It shouldn't give an error let me check and update you
Thank you so much sir for ur quick response, I will be waiting for ur answer
since springboot 3.0 you dont have to do @EnableDiscoveryClient annotation. It is enough that dependency is defined in pom.xml
I haven't tried , will check and update you
Hi Basant sir, Jwt in microservices explanation is so good. Thank you so much...
Is it possible to show flow diagram , how it goes?
Beginning I already explained flow of this security mechanism
Nice explanation! Only thing I'm concerning is that why did you filter and authenticate user in gateway directly rather than routing to IDENTITY service and authenticate?
Great Video! Need some more info : How do we avoid scattering secret? it can be stolen from code repo. How will the services be talking to each other? How will they get the token? Also how to enable HTTPS with proper handling of secrets.
Grateful for such a wonderful insight on Microservices security. It will definitely help me to improve skills in my projects. Thankyou so much for the efforts. I'm learning a lot from your channel. Awaiting for more interesting videos.
Thanks buddy keep learning 😃
after implementing spring security to microservices it will only validate token when URL passed through the API Gateway, what if we try to hit the URL of the particular service, how to stop that?
Loved the explanations!! But, how can i do a role based authentication, like admin and user for example? I've faced with this question and got stucked. I wonder if you can help me.
Hi Basant, similar to this video can you make one video to secure microservices for authentication, authorization, and re-authorization of OAuth tokens using the OAuth2.0 protocol and IDAnywhere/Okta as authentication servers?
Okay i will do this
Why calling validate endpoint from auth-service(identity-service) was bad idea? I don't understand.
Thank you bro 🎉
What if I hit the swiggy service end-points instead of API gateway end-points ? it should be accessible right how we can call swiggy service is secure ?
Hello Can I directly come to this video withOut watching your previous videos of springSecurity?
13:44 Comienza a crear el proyecto identity-service (lo hace desde el Spring initializer de su IDE IntelliJ)
I have a use case. Can someone suggest a solution pls? I am trying to invoke a third party api, with the token embedded in the request headers. This api returns me a huge json response. While this api is returning some response, what if the token expires midway? How can we fetch a new token and resume from where it failed?
When I'm trying to access with gateway url postman is throwing 404 error , when I'm trying with the service url it's working fine kindly help with this issue
how spring cloud check that request came from web or mobile app and executes corresponding version of RequestMapping method. can you please clarify my query?
There is no such mechanism whether it's mobile or web app endpoint will always be the same buddy .
@@Javatechie i am facing interview questions about it. i can't able to answer that. what could expert answer from you. plz help me on this.
For desktop or mobile view frontend team needs to design responsive pages. Nothing to do from the backend
thanks @@Javatechie
Hi all.
Here I dint understand how role based Authorization will work. I see Authorization is happening at idm service and authorisation happens in filter of api gateway but how wil spring know to do role based Authorization.
You have one of the best educational channels out there. I would love to give you a constructive opinion: It would be great if you could change your microphone into something clearer, like what the java brain and Navin have. Trust me, it makes a huge difference.
Thanks Filz , i noted it and going forward i will come with better audio quality. Need to look into rode configuration
@@Javatechie 🎉d o 😢😢😢😮😊😂😅😅😅😅😮😮😮😮😮😅😮fq😢😢😢😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮😮
Archana not getting you
@@Javatechie I think, that's a bot.
Even not getting you buddy. What do you mean by bot