Spring Boot + Spring Security + JWT from scratch - Java Brains
HTML-код
- Опубликовано: 17 май 2024
- In this tutorial, we’ll be creating a brand new Spring Boot and Spring Security project and implement JWT based authentication and authorization. We’ll create an endpoint that can authenticate and return a JWT. And then we’ll wire in some code to check incoming requests for JWT in the Authorization header and authorize requests with valid JWT.
Java Brains website: javabrains.io
#JavaBrains #BrainBytes #HowTo #SpringSecurity #Spring #SpringBoot #JWT #Java #Tutorial
Important note: In the video, I provide the JWT secret as a constant variable in the Java class. As you might imagine, please don't do that in a real application!
It's not a good idea to check in passwords / secret keys in your code. You should get that from a setting / property file that's in a more secure location and not in your source code repository.
(Thanks to Olivier for pointing this out in the comments)
Thanks for the tutorial.
You have some unnecessary lines in your code.
in Jwtrequestfilter.class--->if "&& SecurityContextHolder.getContext().getAuthentication() == null" is useless
as well as
"usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));"
has no use as we are not using session.
AuthenticationManager bean already defined in config class. But still getting error
If spring security itself can do authorisation, then what JWT is doing ? Is JWT used to make application more secure ?
Priyak Dey Thank you so much .
Why are you requesting using header Authorization Bearer... As you are using shared secret key, should u use Authorization Basic
An Amazing video with 40 minutes of content. Best thing is how Koushik keeps the tempo throughout and keeps motivating. He holds on to the audience and such an amazing teacher and a humble human being. God bless
Who says Spring Security is complex to understand, we have such a great instructor like you
Thank you so much
With a good tutor, I feel like Spring security is Hello world level framework.
the world needs more teachers like you. thank you!
Your style and delivery is excellent, you are making a lot of java devs' lives better!
My man, you're like the Saint Nick of Java! Thank you so much for sharing such great content
I really want to meet and look at those people in their eyes who actually dislike this and other videos in this playlist. It is a real work that it teaches you for free and with a quality material. If you cannot like a video, the least you should do is to not dislike. It is basically you who might be missing the pre-requisites to understand the material used in these videos but nothing wrong with this quality playlist. I have learned a lot of stuff from these awesome examples. Excellent show Koushik (y)
Totally agree, but that is the internet for you!
Much love and respect
Very well said !!
Till the addition of the jwt filter everything is fine and the JWT is also getting generated but after injecting the jwt filter in the securityconfigurer class I’m getting the exception “JWT string can’t be empty” . Unable to resolve this even after googling. If anyone can help then please .
Koushik, you are the best instructor! I've been postponed jwt auth implementation in our project waiting for your video about it before implementing. Thanks a lot!
I haven't used Java in a while. Started a project to refresh Spring's Authenticatoin& Authorization. Then you post this video. Thank you for the great content! =)
OMG, you're an OG for this. I've been waiting for someone to explain this for over a year!!!
I have seen many tutorial videos but this is the clearest, most useful and most educational I have seen, I thank you very much for your time.
I cant Thank You enough for what you have done in my career through your tutorials . You explain everything in simple terms and great enthusiasm. THANK YOU!. Its the best content I have seen in the internet. And some ungrateful idiots will just downvote the videos.
If I get married , I will invite you because I feel you like a family after all these years.
*When
@@_robyn_ Yeah..I am not sure about that
@@valkon_ 😂😂 feels for u bro
you got married??
are you married bro??
What a nice Diwali gift. So thoughtful of you man!! Happy Diwali y'all!
That was clear, understandable, and easy to follow. Thank you very much.
Omg Kaushik.. you are a saviour.. I have followed your microservices series when I was asked to make a poc on that.. where I learnt a lot of new concepts from you. And now again I am asked to make a poc on Jwt and again you have made it so simple to understand and implement as well. Thank you so much. You are a trusted resource for me.
This tutorial is the best I have come across on the internet on spring security. You did a fantastic explanation. Thanks man!
The tutorial covers Spring Boot security pretty nicely, but I think there are some aspects to be pointed out here:
- Some people wonder where the token itself is validated. This was not mentioned in the tutorial, but actually the *extractAllClaims* method is responsible for the validation. It throws exception while parsing claims if token signature is invalid (secret key mismatch) or token is expired. Thus *validate* method in JwtUtils has redundant check of expiration time.
- The great advantage of JWT is that it is stateless, that means id doesn't have to be validated against queried data. This tutorial validates if data of user with provided userId matches the data of the same user fetched from somewhere else (usually from a database). This validation is redundant, since token has already been validated and we are ensured that provided userId is correct. There may be a need of fetching user while validating JWT token, but there is not in this scenario.
- To sum up - *validate* method in JwtUtils can be securely removed
omg thank you so much, sir. I have been scratching my hair off after watching the tutorial. I felt that the extract method already validate the signature, and that validateToken method will basically always return true, because the userDetail was fetched by the very same username extracted from the token, which means either no userDetail can be fetched or the username has to equal.
One more thing is that the validation filter is always fetching the user details from database, which is not needed since that is the purpose of JWT payload. As of now there is a DB call to get user information for each incoming request which defeats the purpose of JWT tokens.
Validation of jwt is required as jwt payload can be changed ,such as changing expiration and sending it. As it is simple base64 encoded . If any tampering of jwt occurs it will be verified with the signature. So the validation is required
@@harshaanirudh5787 It is required, but extractAllClaims method already does that. So if payload is tampered, the signature won't match and extractAllClaims will throw expection.
@@igorzuber1604 yeah, just realised it. Thank you. And if you are aware about refresh token implementation , could you please suggest any?
Any Spring + React tutorial? Love your videos man. Extremely helpful!
Great tutorial, simple, in details, I really love your way of explanation and without any error. Thank you so much
Java brains simply rocks - thanks Koushik for this video. Been following Java brains for almost 5 years now and the way you explain is outstanding compared to most tutorials out there !!
i drop out from collage and when i watch tutorials like yours, i feel proud of what i did
First time watched complete jwt configuration. Thanks.
Make some videos on Spring batch
Thank you, thank yo, thank you.... I wished I had a teacher like you for all my technical courses... You are so awesome in explaining the concepts and following up with an example....
I tried to learn SpringSecurity for at least five months, and finally I gave up and used JWT manually for my personal application. But you expained it perfectly and now I can implement both techs! Thank you, very much!
Thank you.. waited for last few weeks.
I love that guy saying that if he gets married, he will invite you. I've realised that you have helped millions, if not billions of devs out there! Keep going big bro
Millions? Billions? you evidently like large numbers
Simply one of the best videos on Spring Security + JWT
Simple and clean explanation. The code just works fine. Thanks a lot @Java Brains.
You are my goto person when i want to learn "how things work" not just "how to work".
Thank you and Congratulations.
Please OAuth2 next. I love your teachings
It's really impressive. Could you please do videos on OAuth2 + JWT. So that it will be complete tutorial on security.
Waiting for new videos on OAuth2 at least 3 videos.
Just exactly what I was waiting for, thanks for sharing.
Thanks sir, It's really very worth to watch complete video. Thanks for helping us over the years & years. Please keep posting such an outstanding videos for us.
Note the changes in the HelloResource class at 8:10 .
1) "RestController" instead of "Controller" and
2) Remove the flowery braces from the "RequestMapping"
That's just Spring MVC stuff and has nothing to do with Spring Security.
People coming here are mostly familiar with Spring MVC so that shouldn't be a big of a deal.
@@mahdyberriri5742 I was helping out people who might be copying the code word for word.
@@SaratchandraKasivajjala ah understood! that's kind of you man.
Thanks! Help solved my problem where cannot access the /hello path
Thanks.. This resolves 'resource not found' error..
Another amazing class from this channel!
But I got deeply concerned about the future of Java going this way.
I've just learned to do the same via Python, and it was far more simple.
Java is still far more robust and faster than Python in general; and specifically for server-side web development, Java shines bright (especially with Spring). Python simplicity comes with the cost of bad performance unfortunately.
You are definately right about that....java for hard boiled devs.
Till the addition of the jwt filter everything is fine and the JWT is also getting generated but after injecting the jwt filter in the securityconfigurer class I’m getting the exception “JWT string can’t be empty” . Unable to resolve this even after googling. If anyone can help then please .
Thank you , the world needs more awesome people like you.
Thanks man ! Really good content here. I've been reading comments below and maybe there are important info missing, but trust me this is gold. So many videos out there which don't get to the point, are sooooo long, let you with not working code, or are just baits for going purshase a full tutorial on private websites... This topic is pretty hard (at least for me) and this short video leads you to a basic working jwt springboot app ! I Guess there is more to do for a professional app, but this is a good start. I definitely will go through you channel to see if there is more about it !
Thanks for your video, I just have a question. Sorry if I am missing something. But I couldn't get it from this video. In "authenticate" REST API, What would be the issue if I dont use AuthenticationManager's authenticate method? (I mean I dont need authenticationManager completely there) . I can just verify the username and password with DB and return jwt even without it. Since it is just authenticate, we dont need context as well. Can anyone please explain?
Hi Java Brain,
1)In real time project what kind of signature algorithm would be used.
2)In real time project generally how much time they will set for token expiry?
3)So all these JWT configuration and setting are likely one time activity?
Also I would like receive reply on this from any helpers who is working in real time projects.
Thank you so much!!! It is a great tutorial for the one who want to understand how jwt works with Spring Security.
It was very helpful to understand the authentication/filters part in spring boot. Thank you so much for sharing this! 👍
just wanted to say Thank you :) Great job! But, it's not clear about where SecurityContext appeared from at the end in the filter :)
Thank you so much!
What about a JWT + OAUTH2 tutorial?
JWT + OAUTH2 tutorial Please........
You need new instance for oauth
www.baeldung.com/spring-security-oauth-jwt
I'm struggling with this authentication about 2 weeks and this video is really helpful thanks a lot
You rock. Thanks a ton for making these videos available. Honestly the instruction is better than some of the Udemy courses that I've purchased in the past.
Till the addition of the jwt filter everything is fine and the JWT is also getting generated but after injecting the jwt filter in the securityconfigurer class I’m getting the exception “JWT string can’t be empty” . Unable to resolve this even after googling. If anyone can help then please .
In HelloResource controller , you have changed the controller type from Spring streotype controller to RestController all of a sudden, Which could leads to confusion for beginners, Since @Controller will try to return a view which doesn't exist, and you haven't used @ResponseBody along with Controller to support a simple text as response. Maintain same coding across the video, if you have made correction point it out.
Awesome, this tutorial was super helpful, could you please create a new one with JWT + LDAP?
I've been trying to find good resources about that combination but there isn't anything with the quality your videos have.
Thanks!
Aren't JWT and LDAP will be sperate realm/filter in spring security?
Was looking into this , and also will have basic auth as default.
Thanks for this tutorial without wasting a single second make this tutorial understandable.
Great video as always. Looking forward to OAuth. Your efforts are highly appreciated,
Thanks for the video! Just FYI: Your LDAP Spring Security video is missing from your Spring Security Basics playlist. ;)
Thanks for the call out. Added.
Any tutorial with angular and spring boot
Kaushik, Is always gem and proved that he is the best one to help both freshers and experienced ppl to understand the concepts. Your videos saves more time and easy to remember , you are a nice person GOD bless you
What a great tutorial, easy to follow but, what is more important, really clear, and clarifying.
It would be great to see an example with at least 1 role, but anyway it was really helpful.
Thanks!
Thank you very much for your awersome videos, but I have something to say
In previus videos you said JWT token is used so we do not need database to validate them, incase of microservices..etc
also in JWT Filter in this step I think loading the user details from database is not neccesery..
UserDetails userDetails = authService.loadUserByUsername(email);
if (jwtUtil.validateToken(jwt, userDetails)) {
We can validate the JWT using the signature only, and thats enough right? also we can add other user details to the claims and retrive them, in case I do not want to use DB to validate JWT but I want more details about the user.
Please correct me If I'm wrong
Thank you
Yes, whenever "Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);" is called, the token is validated internally (you can see some exceptions are declared in the method signature). So I think this is enough to validate a token:
public boolean validateToken(String token) {
try {
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
return true;
} catch (JwtException | IllegalArgumentException e) {
// handle
}
}
Moreover, UNLESS you want every request to have newest/realtime data from the DB (e.g: role change, active/inactive...), you can build the Authentication object based on the token itself and pass it to SecurityContextHolder.getContext().setAuthentication() so that you can avoid querying to DB (i.e calling loadUserByUsername()). Reference: stackoverflow.com/questions/50572339/jwt-authentication-without-fetching-user-details-on-each-request
Just before watching I clicked like button
Me too
I'm waiting for it too!
Your teaching style is outstanding sir ...Amazing. Thanks a lot.
Finished the Tutorial! Great job man
19:05 I believe that in SpringBoot @RequestMapping can be replaced with @PostMapping so that we do need neither 'method' attribute nor to annotate the argument with @RequestBody
this video is about spring security and JWT authorization.
Hello Java Brains,
Nice Tutorial, I already implemented one real application with spring security and jwt but with this video I finally understand the background of it.
One of the best SPRING+JWT material on internet..
Hello, thanks for such a wonderful tutorial! Facing an doubt though.
When I'm trying to generate a JWT token by POST request to /authenticate, keeping the password correct and fiddling with the username, I'm still able to generate a JWT token. It's not authenticating in the correct manner against the user in MyUserDetailsService. Any idea where it might be wrong?
Try setting a breakpoint in your API method and see if you have incorrect logic. It's hard to tell without looking at the code
@@Java.Brains It's happening in your code too that is uploaded on git maybe the cause is you have created a static user which get created irrespective of username provided in loadUserByUsername(String username).
It should be something like this
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if(username.equals("foo"))
return new User("foo","foo",new ArrayList());
return null;
}
I am also having the same issue. Could you please help me
@@rikijha638 or for better clarity, let us have a map 1) foouser -> foouser'spassword 2) baruser -> baruser'spassword and get the password from the map for the username and return an "User" object.
Really nice video, I am just confused about something; what's the point of implementing the JWT since Spring Security already handles the authorization mechanism? Anybody have an idea here?
Now I get it! it's a matter of stateless vs stateful mechanisms ;) It does make sense! Thanks for the explanations and for your time Sir!
Great job, man. Amazing tutorial with the clear explanation.
Great explanation! Clearly explained, no fast talking like others (Telusko) and no (Indian) accent!
peculiar thing I noticed: if you create jwt with just the userName, it will introduce a vulnerability. When a single account has been logged into from two clients, if one of them changes his password, the other client's jwt will still be valid until he logs out. To invalidate the other client's jwt right away, create the jwt with both the userName and password, like: userName_password.
Hello ! Good video.
Can you show some code in the next videos for refresh access token flow and returning status code 401 if token is expired (i need it for an android client with retrofit authenticator)
Thank you.
Thanks! That's exactly what I was looking for. Very clear explanation, thanks!
Great tutorial.Thanks for providing it in so simple manner.
Hi)
What about refresh token? Why no body explain this topic?
Isn't that more easier than anything in this world now? ;)
The refresh token is the same. You have to create a new endpoint with GET method to handle that task. But we need to validate the current token, before process the refreshing request. And the most important thing to be noticed in case of when user changes his/her password before the refreshing request is sent to server.
Please, for those who watch this, you must make sure to not hard code any sensitive information (like passwords, or private key) in your code. This is a very dangerous practice and a vulnerabilitym even more if you use Git and commit code (even if you erase hard coded infos, it is always possible to go back and find it with Git). The use of environment variables is one of the solution to solve the problem.
Thanks for the comment. I realize this might mislead someone who doesn't know. I'll add a pinned comment
@@Java.Brains Hi ! I forgot to mention "Great video as usual" in my previous comment ;) . Yeah, It's pretty obvious for someone who has a little bit of professional experience that it is not a good practice, but as this video is a tutorial, and is somewhat intended for a less experienced audience (I suppose) , I thought the security warning was important to make.
Great koushik. Really great. Awesome teaching. Thx From deepest of my heart.
Thank you. It was a little hassle since a couple of libraries are updated. But anyway, I managed to make it work. Thanks to you! It brings joy to complete tasks.
Nice work ... but, ew. I would have expected Spring Boot's implementation to be a whole lot cleaner than that
Boot implementation is 1000 times cleaner and clearer than normal JWT with Spring Framework
Holy heck that is a lot of work, but I suppose that's just what it takes to secure an application. I'm a junior developer with zero experience in security and authentication/authorization but this video is a great start to implement what seems to be some basic security measures. Thank you for posting!
Finally found the place I was looking for. Thanks a ton.
Finally one that's very clear. Thank you.
You are a great tutor. Thank you so much for the nice content!!
Excellent video. Im working on LDAP integration along with JWT. This is the best tutorial that got my thing working. Thanks
very nicely explained JWT and spring security which is not easy to understand by reading. Hats off to Kaushik for preparing such a great video
Perfect! Really great content, congrats man!
Thank you Koushik, Great Job!!!
Thank you so much for your effort, i really appreciate your work and care about delivering explanation of everything.
Best explanation. Shortest code. Great! Thanks a lot!
This video helped a lot. This is really a gem. Exactly wt I was looking for. Thanks a lot for putting in so much effort!
I can't thank you enough this is so easy to understand and follow
I really thank you ! previously I have no idea about Spring Security now, I got what I need. I will advance it from now
Once again thanks Kaushik for yet another AWESOME video.
Great fan of yours, when I get some work on technology which is new to me . I simply first check the tutorials on Java Brains .Thanks for your effort sir.
Thanks for these videos, these are helping me a lot in understanding spring security.
In earlier video you said that JWT is for Authorization not for Authentication but in this video you mention that we are going to use JWT based authentication and authorization.
Please clear this.
Thanks a lot sir, you benefit millions, even though there are only 4.7K views for this video, each one of them would have adopted this topic to write code for so many customers!!
You're a life saver man. Thanks for the great content!!
Very very very thank you, i'm trying do this for 2 days and now work. Now i will study about jwt methods on java because i'm coming from Javascript and some choices are different, but thank you man!
Thanks a ton for this course. This is a kind of Deepawali wish come true! :) Happy festival to you and all...
This was intense, it was amazing!
Thanks a lot! .. when I look first time the spring boot security configuration i don't understand anything but now i have more clearly all the logic sequence.
Great tutorial Kaushik.. Perfect.
Viewers, If you have basic knowledge of spring security, you will fully understand it.
First of all Thanks for the video, this is great.
Just have a quick question, why is the hello resource without authentication header giving 403 instead of 401?
Excellent !! Crystal Clear
WoooW. Man, I neve understand Spring Security Framework, but with your explanation I finally got it!. I'm really thanked with you! :D.
You are doing an amazing job sir. :D Thank you very much.