Spring Security JPA Authentication in Spring Boot
ฝัง
- เผยแพร่เมื่อ 6 ก.พ. 2025
- If you need to use Spring Security to authenticate against a database using Spring Data JPA, you're in the right place. In this tutorial, you will learn how to use Spring Data JPA for authentication against a database using Spring Security.
🔗Resources & Links mentioned in this video:
Github Repo: github.com/dan...
👋🏻Connect with me:
Website: www.danvega.dev
Twitter: / therealdanvega
Github: github.com/dan...
LinkedIn: / danvega
Newsletter: www.danvega/de...
SUBSCRIBE TO MY CHANNEL: bit.ly/2re4GH0 ❤️
I was overwhelmed with others people tutorials about Spring Security but you made it so easy to see what is actually going on, thanks man I appreciated, +1 sub
thanks Dan. You are only person who finally clearly explained all things with Bean approach. all tones of tutorials on YT have only old approach
Thank you, Serhii. I'm glad I can help out.
what i like about Dan is he uses the most basic approach when teaching something, leaving out unnecassry details that might confuse newbies. this video is to teach us on JPA Authentication no more no less. this is what a tutorial should be. Thanks sensei
Thank you so much for this tutorial it really helped me visualize and understand how security in spring boot works.
I'm glad it helped you out.
Another great tutorial from Spring advocate Dan Vega
Great video as always Dan! I think @Arsalaan suggestion makes a lot of sense. This will be kind of an "endgame" like video for this series - where everything is combined - JWT, Roles (User,Admin,etc), Connecting to PostgresSQL (running locally via docker).
Thanks for the idea!
@@DanVega And maybe add a little frontend to configure CORS. I'm struggling to get it working.
Thankyou so much Dan for this video, I am following your entire spring security playlist and it's very helpful. 🙏 looking forward to more such learning content.
I'm glad my content is helping. Thank you for the kind words.
this video is kickass reference. Easy to implement, helps 100% in any backend development.
Hi Dan. Thanks for the continuous tutorials on Spring Security. It is very important and also very clearly explained.
Could you please use a "real" database like Postgres for demonstrating. Thanks!
I just created this video, not sure if that will help you out. th-cam.com/video/_Gdb-jK3Sr4/w-d-xo.html
If it doesn't please suggest a new video using this github.com/danvega/office-hours/discussions
Really awesome stuff here! Awesome channel! Love your videos! 💛
So clear to follow along and really great content! Thanks Dan.
This makes me happy. Glad you enjoyed it!
Great video Dan!!!
Appreciate it.
Hello Dan . Code works without setting userDetailsService in SecurityConfig class...
Very well explained. worked like butter.... Thanks Dan. It will be great if you can comeup with a complete production ready like projects which caters for best practices security security over microservices security with OAuth and may be keycloak SSL cross scripting cors all in one course........it will be kinda like EndGame series
Great Content! Thanks for sharing your experience. Amazing teachi !
Would be amazing to see a complete backend API with PostgreSQL and JWT and how to store password in the Database !
Hi Dan,
Can you drop a guide on implementing JWT in a Spring Boot App
BUT include roles (user, admin), connected DB (to verify details) and UserNamePassword Authentication where the user calls an endpoint with username/password as body and the token generation happens based on that.
Basically, a continuation of your videos
"Spring Security without the WebSecurityConfigurerAdapter" and
"Spring Security JWT: How to secure your Spring Boot REST APIs with JSON Web Tokens"
Please consider this, it would be so useful and applicable to many projects!!
Thank you.
You got it. Thanks for watching and the suggestion.
@@DanVega Is that video online already? I also don't seem to get the roles active in my authentication.
@@DanVega Was it done already? Would use it quite a lot right now!
Love your videos, looking forward to more Dan 😊
great video as always Sir, miss one thing thought ... the logout 😅
Quality Tutorial. Thanks, Dan!
Thanks Dan, it was a great session
Thank you!
Great video about Spring Security. Can you please make video about how can we apply more than 1 approach (like JWT based security, JPA based security) using Spring security?
Awesome Contents, as usual 🎉🎉🎉
Thank you, Anish
Great tutorial. Thanks Dan
Nice, thank Dan!😍
You're welcome!
great video, thanks!
Hi Dan. Firstly It's a great tutorial beginners can easily learn spring security. Secondly I'm working on my project where I'm facing an issue that "user are able to access the data of other users".
In simple words no user should have the authority to read or manipulate data of other users except theirs.
There's no scope of admin and user-based authorization. because there's no such content that users should not see. Every user has their own data, and it should not be visible to others except the current authorized user.
Please suggest me how to do customized authorization on each user.
Thanks in advance
Dan
Interesting. If I am an authenticated user do I have access to all data of all the other users in the system?
@@DanVega Yes Dan you should not have the access to other users' data but at present the application giving access to the data of other users too. I'm not able to configure that issue, Please help me in fixing it.
Great tuttorial! Thanks a lot! =)
Yes lombok can help with boilerplate code like getter and setter
Same here! When fo you start using lombok? Maybe it us some kinde of internal rejection 🤔 from using lombok?
I assure you i have no problems with Lombok but I don't use it when teaching. If someone has never used it than its one more thing you need to learn I just find it easier to be verbose here and let the IDE help me out. In a single class or 2 I'm not gaining a whole lot by using Lombok vs in a real world project you are.
Thanks Dan
Hi Dan couple of questions
Q1 : 24:45 you have autowired an entity, just like spring bean however we didn't had any @Component on User Entity how is this working, for me it was giving unsatisfied dependency exception.
Q2. I was reading that it's not a recommend way to Autowire JPA entites as entity are not regular Spring bean but sometime that is managed by JPA provider, what's your recommendation, is my understanding correct ??
You don't need an annotation on User because you are not asking the Spring Framework to manage instances of that class for you. Here you are creating instances of User by calling its constructor new User(...)
Can you provide me with a Github Repo that has this error? Someting else is going on here.
Great video!!
Thanks!
after this video i know a few things more :D
I love learning new things! Glad you were able to learn something
Hi Dan
could you do videos on Spring Security OAuth2
creating OAuth2 Authorization Server
or using existing Authorization Server
Thank You Dan so much!
You're welcome
Hey Dan, great video! After watching almost all of your spring security videos, I believe I know a little bit more about how to secure a REST API haha.
I have a question, why did you use Ouath2 on your JWT video and on this one you chose to pick up the bare Spring Security dependency?
As @Arsalaan suggested, it'd be nice to see a complete road map of how to secure a real life API using JWT, real users with roles and data base!
Thank you! Keep with the great job!
In this video I am focused on JPA authentication and not the JWT bits, thats all.
quality material as usual Dan, I absolutely love it, one little question: any benefit of using an Authentication Manager as a bean in the security config class and passing the user details service to it instead of passing it directly to the security filter chain?
No, just wasn't sure if I was going to use that elsewhere or not.
Thanks for the lesson
Hello Mr. Dan Vega, I wanted to thank you for providing such helpful tutorials. I really appreciate your effort in helping others. Could you please tell me what plugin you used to help auto complete your tutorials? Keep up the great work!
Github copilot
What is better? To check authorization inside controller via PreAuthorize annotation or in the securityFilterChain method with .hasRole/.hasAnyRole methods?
Hi Dan,
Really thanks for the video.
Could you please do a video and authentication/authorisation using Okta or separate Auth server.
Thanks 👍
I am going to work on one for Spring Authorization Server soon!
Thanks a lot! Really helpful!
Hi Dan. Congrats for your small tutorials. Well, Maybe Spring Security LDAP Authentication in Spring Boot?, just for having the full sequence. Thanks
Thank you for your suggestion github.com/danvega/office-hours/discussions/42
hey guys ı want to ask something if i changed My Role Types String to List what ı have to change my code ?
Hi! Dan. Do you have any video on Spring Boot (specifically- Microsoft Active Directory) Authentication? Thank You!
Thankyou for this great video.
What if we have two user tables that we wanna use to authenticate, do we add both of them to the securityConfig file?
Hello, how do i write testcases to test the authorizations of the home controller since its a different type of authentication
Really enjoyed this great tutorial. Thanks !!
Glad you enjoyed it!
Dan > Spring Boot! That's it!
You just made my day Fred! Thank you!
Hello Dan, thanks for lesson it's so helpful. Can you please tell what plugin do you use to help auto complete ?
Thank you@@lykkos290
GitHub Copilot
Hey Dan , what is the difference when we are using this for Springboot 3+ version
Hi Dan, can you please show a case where API Key is used for the authentication?
I have done this in other tutorials. If you look for Spring Security JWT on my channel I have a few videos.
@@DanVega thanks Dan, will definitely check it out.
In the case of `SecurityUser` since we only get data without setting anything, can we use `record`?
Thanks Dan)
what about if i implements userdetails in users class like public class users implementes userdetails ?
where will the session token stored in this approach?
If I use this, how do I send a post request for login to my frontend? I cannot seem to get to the actual endpoint of the login page that form login generates.
Nice session, Thanks Dan! May I know what is the plugin/feature you are using for code prediction, looks amazing.
Thank you. That is GitHub Copilot.
Hi, Dan! I tried to implement separated entity and user detail like you, but a have a problem with spring-boot session: when I restart an application I have to log in again, but if I implement UserDetails in User entity spring session remembers logged user and I can continue without re-authorization.
Thank you for your wonderful guidance.
Can you please assist me in enabling HTTPS and installing CA's SSL certificate in spring boot app? I will really be glad.
Thank you for the content suggestion github.com/danvega/office-hours/discussions/48
Thanks for the great explanation and the playlist of Spring Security. Actually you can use @RequiredArgsConstructor for constructor injection and avoid the boiler plate code of declaring the constructor by yourself.
Could you make this video without leaving the jwt tokens part out of it please? I do not understand why the configuration happes without the .sessionManagement and oauth2Resourceserver here.
Hey Dan thanks for the video.My application is unable to sign in even with correct credentials even though I have done all steps correctly.Could you please help me out
Thanks for the video - Is there a way to do this without using .map??? my code is givng me strange error: "userRepo.findByUsername(username).map(SecurityUser :: new).OrElseThrow... " is giving me an error " The type SecurityUser does not define SecurityUser(UserEntity) that is applicable here" 29:24.1
Please make an example for Mysql
It is really as simple as replacing H2 with MySQL. Have you tried to do it? If you're facing any issues let me know.
thanks and my question at the end, we encoded the password but when will we decode it i mean shouldnt we decode it while checking password while logging in??
We don't need to decode it. Spring Security is comparing the encoded password that is part of the login credentials against what is in the database.
Every tutorial i watch for Spring security, it always fails at the configuration, methods are always depricated, same with this video.
A few things changed in Spring Security 6 (Spring Boot 3)... I did a video on those changes or you can check out the Spring Security documentation. If you have trouble upgrading this demo let me know.
@@DanVega I was able to create the demo except for the headers in the security config, i couldn't the updated version
Thanks Dan this was useful. Any chance you can now take this and expand it into auditing? A natural extension of using the Spring Security libraries to building auditing on to your entities like @CreatedBy and @ CreatedDate etc. I have managed to conquer this in my most recent app but as a general practice I put auditing on all entities as it can become so useful in sensitive changes of records and general troubleshooting.
Thank you for the suggestion Paul. github.com/danvega/office-hours/discussions/45
CoPilot rules!! :)
It certainly does.
Hi, thanks for the videos. Just a question please: I could not make it work using @PreAuthorize("hasRole('USER')"), but I needed to change to "hasAuthority('USER')"). Any clue why it happened?
You need to use the annotation EnableMethodSecurity(prePostEnabled=true)
by default prePostEnabled is false and PreAuthorize won't work
Hi Dan.
On exactly minute 37:00, you successfuly encrypted the String, so it's not able to see its value in the database.
Do you mind, giving a little suggestion or hint, on what to do, to make sure that the string "password" on line 23, also will be unreadable in the code, as it can easily be viewed on gitHub?
- Best
Before I give you my suggestion solution, please keep in mind that you should never put your passwords, keys, or any sensitive information inside your code.
Instead, keep them in a separate file and then gitigonre it, and my suggestion in this case is to manually encrypt it and replace it rather than encrypt it with this method.
@@developerbdarija Thanks for your answer.
I did manage to use a System method to access Environment Variables.
I stored these values that are secret in both the IDEA and where I deployed the app. Now they are hidden everywhere.
- best
Hi Dan - I'm using Spring Boot 3 (Spring Security 6) and I can't access the H2 console. With Spring Security 6 there is no antMatchers or mvcMatchers only requestMatchers which don't allow us the access the console - I have this line auth.requestMatchers("/h2-console/**").permitAll(). Is there a workaround to allow access?
use auth.requestMatchers(new AntPathRequestMatcher("/h2-console/**")).permitAll(), auth.requestMatchers(new MvcRequestMatcher(new HandlerMappingIntrospector(), "/api/posts")).permitAll(), and csrf.ignoringRequestMatchers(new AntPathRequestMatcher("/h2-console/**"))
Hi Dan,
Actually I was doing same kind of project and the thing is when I was doing InMemoryAthentication it was working smooth, but when I used authentication against db(MySql) it was prompting access denied, so can you please do it with MySql
Hi Dan, can you make a tutorial onto how to implement JWT in Spring boot GraphQL API?? Resources about this subject are very rarely
Thank you for the suggestion. github.com/danvega/office-hours/discussions/39
I was following the tutorial but I decided to have my Role as an entity. As I would like some users to have more than one role I have created many to many relation between users and roles. In getAuthorities() method inside SecurityUser class I map roles names but I get an exception "failed to lazily initialize a collection of role". I am scratching my head but still couldn't find a solution. Do you know what could be an actual fix to the problem?
I think you have to set the fetch on the JPA relationship to Eager.
07:22 can you please add the link to the video you mentioned here at 07:22
I didn't mention a video at 7:22.. did you get the timestamp wrong?
thanks
Do one using MYSQL
Great tutorial and big thanks from me for your hard work. Subscribe on and will watch more of your tutorials.
Awesome, thank you!
Merci
Why did you use Crudrepository?
CrudRepository gets me all of the CreateReadUpdateDelete methods
thats a nice video, but a big chunk of the infos u share are already deprecated and marked for removal. Please Update the video or at least leave a comment somewhere so people dont waste time watching
its good but you should use DDD
12:53
Dan your English We indians feel uncomfortable and please try to use normal English but explanation was good
What do you mean by normal English? Do the closed captions help out at all? Sorry you're having difficulties following along. I understand how that can be frustrating.
Hussein your comment about Dan's English is offensive and insolent, especially coming from someone whose country "speaks" a broken English. My suggestion to you is to get some REAL English classes from English speaking people not from the people in your country dude
why i get this error?
Field userRepo in com.auth.jpa.controller.ApiController required a bean of type 'com.auth.jpa.repos.UserRepo' that could not be found.
why i get this error?
Field userRepo in com.auth.jpa.controller.ApiController required a bean of type 'com.auth.jpa.repos.UserRepo' that could not be found.