This video hit the nail on the head, I watched countless other videos from other people before I found this one, and the content was either outdated or poorly explained. I appreciate that you did everything from scratch and explained each step. Wish I found this video about 8 videos earlier, but I finally understand the whole implementation process for Jwt's. 11/10 will watch again.
You just revived my passion for spring boot based backend development. Thank you so much. This is the best spring security crash course I've found on RUclips even better than the inspirations you mentioned in this video. The reason is, that you used less jargon and fancy Java. You showed basic Java skills to explain an already complex spring security concept which feels smooth. Most of the creators from the Java community tend to use a lot of fancy Java design patterns and advanced Java features which causes great difficulty for freshers to understand such complex concepts. Constructive Criticism: I have one small suggestion for you, the cutting of your voice is really not good. There are no pauses between your speech, leading to you sounding monotonous even when you're not. Also, it made me rewind many times since I never understood where one sentence ended and the other began. Love your content. keep going ♥
All I could say this is an extraordinary tutorial. I tried all of the spring security tutorials but they did not cover the nitty gritty aspects of it like the jwt token creation and authorization but you just were superb. Thank you very much for uploading a gem ❤
This video is a compilation of everything useful that is said in the other videos, discarding all the other useless things that are said, updating it to the latest versions of spring. Liked the video, keep it up.
Great video and working around the deprecated methods wasn’t too bad and was a very good practice of working with documentation. Thanks for putting this all together. 👏🏼👏🏼👏🏼
What a fantastic to the point video it is, Thank you so much Ethan for sharing valuable knowledge with all of us, my knowledge before and after watching this video has increased very much, looking forward to more of your videos. I had watched a bunch of videos on this topic, but your explanation made it much easy to follow and code along with you.
Holy crap. Thank you so much; this is amazing. Top tier content. I learned so much from this compared to hours of Amigoscode or Dan Vega. Nothing against those guys, they just have so much content to get through and a lot of it is outdated. Thank you so much for putting this together. I got what I needed out of it and then some.
Finally found a video for working around the older deprecated methods. Thank you very much. Edit: Unable to generate the jwt token during login, and getting a 401 Unauthorized error response back. Might be an issue with the deprecated jwt() method in oauth2ResourceServer(oauth2ResourceServerConfigurer::jwt()). But even with the new code oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())) which provides a default implementation of the oauth2ResourceServerConfigurer class its not working. If anyone has faced the same issue and solved it, Please let me know. Thank you.
I had exact the same issue but I skipped the line 'daoProvider.setPasswordEncoder(passwordEncoder());' under SecurityConfiguration class -> AuthenticationManager ... i had only "daoProvider.setUserDetailsService(detailsService);" hope it helps.
@@TheMrBatica Thanks, I had the same problem. Maybe someone has the same issue, so here I put proper code: @Bean public AuthenticationManager authManager(UserDetailsService detailsService) { DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider(); daoProvider.setUserDetailsService(detailsService); daoProvider.setPasswordEncoder(passwordEncoder()); return new ProviderManager(daoProvider); }
Man, this video is top notch. It is exactly what was missing from youtube. Could you, please, share with us, how did you figure all this out? What materials did you use for documentation or how was your thought process? Or maybe is it just experience? I watched Dan Vegas' video about JWT and I was really wondering how to achieve role authorization. I wouldn't have figured it out by myself.
Liked the video! Here's an idea for future tutorials, can you create git branches for each chapter? this way we can go back and forth between different chapters to compare and contrast the changes.
What I usually want to see in security videos is handling security for different type of roles. E.g a backend service for sellers and buyers, drivers and riders, students and teachers and so on
Wow, first time I get it right. Thank you! This channel should have much more followers. I had some issues using Lombok, but when I did all the constructors, getters, setters manually it's finally worked! I guess I need more experience with constructors first, then use lombok.
This was fantastic! I followed it, but changed JPA to jdbcTemplate, because the road to Hell is paved with too much abstraction. Doing it that way, everything made perfect sense. Thank you!
Good video, I watched it to the end, kinda hard to understand the whole thing because I've just started learning this framework but with the time for sure I will comeback and watch it again!
I have done exactly as you have mentioned in the video upto configuring basic authentication, I keep getting 401 unauthorized exception despite supplying the username and password correctly
Fantastic video...only problem I recieved was at 1:35:00 during login There is no PasswordEncoder mapped for the id "null" i don't know if I have done something wrong or need to update spring security....it doesnt work with admin as well
I double checked it and there was nothing missing..but when I copied all code from Config class it suddenly worked..thanks for the answer@@unknownkoder
I have one more question though..now that we have functional webapp working through postman.. how can I set up this to work within webpage ? I mean now we have working hashing and tokens.. I created login and register form.html but don't know how to connect those parts together
I had the same problem, for me I had not set the password encoder in the AuthenticationManager Bean in security config @Bean public AuthenticationManager authManager(UserDetailsService detailsService){ DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider(); daoProvider.setUserDetailsService(detailsService); daoProvider.setPasswordEncoder(passwordEncoder()); //this line I had not written return new ProviderManager(daoProvider); }
1:35:11 Here when i am trying to hit it on postman, i am getting 401 unauthorised error. The error was "No password mapped for id "null" . Please help !! Edit: This problem is solved using oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()) because jwt is depriciated. Another one that could be helpful is using (oauth2) -> oauth2.jwt(jwtConfigurer -> jwtConfigurer.jwtAuthenticationConverter(jwtAuthenticationConverter())) ) while using convertor.
I solved by the adding the line "daoProvider.setPasswordEncoder(passwordEncoder());" to the authManager method. @Bean public AuthenticationManager authManager(UserDetailsService detailsService) { DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider(); daoProvider.setUserDetailsService(detailsService); daoProvider.setPasswordEncoder(passwordEncoder()); return new ProviderManager(daoProvider); }
Much needed video on the upgraded ways of Spring Security, I'm glad that i was able to find it I have a request though, could you also post a video on formLogin using spring security
Hi man, i have this erro in my securityConfiguration. line : .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt) Error: 'jwt()' is deprecated and marked for removal Do you no fix?
fyi if you are struggling with deprecated methods, or other things (example: I was unable to run project due to an error with the security filter chain method, request matchers specifically. You can always just downgrade the version of Spring Boot in your POM.xml to use what was used in the video and everything will work.
great content video with proper explanation keep doing contents like this 😍, i was looking for this type content for many days, i just wasted a lot of time but this saved my time and can explain how to save roles in DB annd retrieve it from DB and also about OAuth 2.0
Hey @Unknown Koder, I fixed the bug you encountered at 1:41:35, apparently this stems from a deprecated use of the jwt() Method, this is the correct way of configuring it as of Spring Security 6.1.x: .oauth2ResourceServer((oauth2) -> oauth2 .jwt(jwtConfigurer -> jwtConfigurer.jwtAuthenticationConverter(jwtAuthenticationConverter())))
Greate tutorial, Am asking for getting an end-point which returns an access token by accepting refresh token, Note Access token should also be returned on login attempt.
the video is really helpful, but faced a problem, can you help me out ? 1:09:44 => there is no arg for httpBasic() method in Filtercahain config method 1:09:47 => Suddunly a the arg appeared as httpBasic(withDefaults()) can you explain the purpose of withDefault() method? did you create it or it will be refered from somewhere else
If you take a look at the repository in the description, and go to the AuthConfiguration class you will see that withDefault() is a static import from Spring Security.
@@unknownkoder Thanks for clarification, btw the actual problem is, I am facing while adding the permitAll() access to the auth/** for registraion at 1:09:50 , I got an error while starting the server after adding it i.e Factory method 'filterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher). so I think it may prevented by adding withDefaults(), but showing same even after addding, can you help me out ?
Lovely just what i needed ... i'm new to this level of spring security ... so I hope this question isn't a silly one ... i would like to know how and where you generated the public and private key in you code... thank you :)
There is a problem casting the Principal to UserDetails as per your implementation.. any ideas? Am trying to get the logged in user via SecurityContextHolder.. thanks
@@unknownkoder I got the error : "There is no PasswordEndcoder mapped for the id "null" ". I created PasswordEncoder bean follow your tutorial. I dont know why login not working, I test api in register and it works normally
@@nguyenhoanganh7228 In your SecurityConfig code the authManager like this: @Bean public AuthenticationManager authManager(UserDetailsService detailsService){ DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider(); daoProvider.setUserDetailsService(detailsService); daoProvider.setPasswordEncoder(passwordEncoder()); return new ProviderManager(daoProvider); }
Hi, this was an exhaustive example I've been looking for. Thank you very much! I would like to extend this project with static HTML pages. How can I do that? I've added HTML pages (e.g. an index.html under resources/static) but I can't access any of the pages. they're all blank and I get 401 responses to them. I tried to add the static path to auth request matchers, but no joy so far. Any ideas what's missing? Thanks in advance!
Hey guys! Is it normal for role authorization to not work without a Converter even if we set the role in DB as ROLE_ADMIN for example? Because I just spent a lot of time with it and it did not work at all even if I would use roles such as "ROLE_USER", "ROLE_ADMIN". It began working only after setting the roles in DB as simply "ADMIN" and "USER" then adding the converter as in the video.
Awesome video, I followed everything you said (mostly) and got postman working at the end, but Im a bit confused on how to implement a login page and move to a secured page?
Thanks very much for the vid! Really enjoy your teaching style! I am having a bit of a problem though, when I change the loadUserByUsername() method inside the UserService class to call findUserByUsername on the repo, the app stops accepting a valid username & password combination of admin. I have checked the database and the user admin tuple is definately there but I get an error 401 no matter what I enter? Have been stuck on this for a few days so would appreciate any help! Thanks very much in advance!
@@unknownkoder Configuration public class SecurityConfig { @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean public AuthenticationManager authenticationManager(UserDetailsService detailsService){ DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(detailsService); return new ProviderManager(daoAuthenticationProvider); } @Bean public SecurityFilterChain filterChain (HttpSecurity http) throws Exception{ http .authorizeHttpRequests((authz) -> authz.anyRequest().authenticated() ) .httpBasic(withDefaults()); return http.build(); } } This is my ssecurityConfig at 47 mins - Can you see anything that might be causing this? Thanks in advance!
@@paulosamvrosiadis3484 Yes! Turns out I wasn't sending the POST request properly. Using postman & ensuring I was sending a POST request properly helped solve it. Goodluck!
towards the end when we were setting up the jwt auth converter alot of the stuff you shown was deprecated. So i switched it over to the more recent stuff but when i coded it im getting an 403 forbidden error.
@@unknownkoder I have built one with react and Springboot before but I used Redux for my security and jwt tokens, but is there any other less complicated way?
Hi bro,i have face one problem there is no error in my code.i have been writing commandlinner runner after i run this mhy progrma there is no error and go to postman send the username,password i was face 401 error.what i made mistake.why we are using commanlineer interface instade of we can create any onther classes
Hey! I have just reached this problem in my app. I got 40-1 while login. I just added PasswordEncoder in authenticationManager. @Bean public AuthenticationManager authenticationManager(UserDetailsService detailsService, PasswordEncoder passwordEncoder){ DaoAuthenticationProvider daoAuthenticationProvider=new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(detailsService); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder); return new ProviderManager(daoAuthenticationProvider); }
After this step the program is not running and giving this error: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'filterChain' defined in class path resource [com/sanyam/springsecurity0609/configuration/SecurityConfiguration.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'filterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher). This is because there is more than one mappable servlet in your servlet context: {org.springframework.web.servlet.DispatcherServlet=[/], org.h2.server.web.JakartaWebServlet=[/h2-console/*]}. For each MvcRequestMatcher, call MvcRequestMatcher#setServletPath to indicate the servlet path.
@@sanyamsharma9526 I had the same issue. Below I am sending my solution. @Bean public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception{ MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); return http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests((requests) -> requests .requestMatchers(mvcMatcherBuilder.pattern("/auth/**")).permitAll() .anyRequest().authenticated() ) .httpBasic(withDefaults()) .build(); }
Hi! When I run the Maven app and try and access an endpoint in browser I get: “Request Method ‘GET’ is not supported. Do you know what could be causing this? The only difference between yours is I am using Postgres driver. Thanks!
Most of the security chain changes have moved them to similar styles with lamba functions. In this case I was able to solve it by using .oauth2ResourceServer((oauth2 -> oauth2 .jwt(Customizer.withDefaults())))
hmm how strange when i send a username and password like 1:10:40, the json response that i got said "authorities: null" eventhough i checked with my database and everything was correct
Do we really need to return user credentials (even if it's wrapped into some DTO without any sort of sensitive information)? I mean is it so-called "best practice" or we can just return simple status code? Is it mandatory to return anything or we can just use void methods in such cases?
Its not mandatory, however some applications may use some of the users information in the frontend of the application. This is why I send back basic info in the tutorial.
From your implementation, how will it be possible to add permission to a users roles? from what I can see, there can only be one authority/permission. I am not too clear on that part. Also previous videos I have seen usually have a secret in the application.properties file that the jwt encoder uses. why dont we have that? is it because we are using the RSA encryption thing? if you have links that explain this in springboot context, I will appreciate if you can share it. I also did notice one downside in that if the application restarts, users have to login again. Can you explain why this is so? And for some reasons, when I try to log the currently logged in user using @AuthenticationPrincipal, I get an error
One Question. When the token will be sent back to the user in JSONObject, how do i solve it in the FrontEnd actually? User has to insert the Token in order to log in and access the Website. Email it to the user is bullshit, isnt it? Or am i missing something?
I'm trying to do this with MongoDb as the database, and I lose myself when i end up trying to create the roles. Since MongoDb isnt a relational db, its a little confusing when im trying to make "join tables"
Hey, I get the following error trying to login following your tutorial: java.lang.IllegalArgumentException - There is no PasswordEncoder mapped for the id "null". Could you help me?
@@unknownkoder Ty for the reply. I fixed it by changing the PasswordEncoder bean to: @Bean public PasswordEncoder passwordEncoder() { String idForEncode = "bcrypt"; Map encoderMap = new HashMap(); encoderMap.put(idForEncode, new BCryptPasswordEncoder()); return new DelegatingPasswordEncoder(idForEncode, encoderMap); } This adds the {bcrypt} prefix to passwords stored in the DB and fixes the problem.
@@thomasvs2911 What you needed to do was @Bean public AuthenticationManager authenticationManager(UserDetailsService userDetailsService) { DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); daoAuthenticationProvider.setUserDetailsService(userDetailsService); daoAuthenticationProvider.setPasswordEncoder(passwordEncoder()); return new ProviderManager(daoAuthenticationProvider); } You forgot to set the password encoder here. Change your password encoder back to Bcrypt
You had me in the first 20 seconds , tutorial hell has brought me here i was almost loosing my mind on spring security
Spring is probebly the worst framework to learn their is so much bs
@@user-zj6iz1rl8dif it wouldnt be used so much in the industry, i would never fucking touch it again.
This video hit the nail on the head, I watched countless other videos from other people before I found this one, and the content was either outdated or poorly explained. I appreciate that you did everything from scratch and explained each step. Wish I found this video about 8 videos earlier, but I finally understand the whole implementation process for Jwt's. 11/10 will watch again.
if u get it can u help me ?
You just revived my passion for spring boot based backend development. Thank you so much. This is the best spring security crash course I've found on RUclips even better than the inspirations you mentioned in this video. The reason is, that you used less jargon and fancy Java. You showed basic Java skills to explain an already complex spring security concept which feels smooth.
Most of the creators from the Java community tend to use a lot of fancy Java design patterns and advanced Java features which causes great difficulty for freshers to understand such complex concepts.
Constructive Criticism:
I have one small suggestion for you, the cutting of your voice is really not good. There are no pauses between your speech, leading to you sounding monotonous even when you're not. Also, it made me rewind many times since I never understood where one sentence ended and the other began.
Love your content. keep going ♥
All I could say this is an extraordinary tutorial. I tried all of the spring security tutorials but they did not cover the nitty gritty aspects of it like the jwt token creation and authorization but you just were superb. Thank you very much for uploading a gem ❤
After thousands of videos on spring security, I finally found an excellent one
You are a true champion by not using Lombok Sir. Lol. When you did your first round of Encapsulation, I immediately implemented Lombok ;D
This video is a compilation of everything useful that is said in the other videos, discarding all the other useless things that are said, updating it to the latest versions of spring.
Liked the video, keep it up.
Great video and working around the deprecated methods wasn’t too bad and was a very good practice of working with documentation. Thanks for putting this all together. 👏🏼👏🏼👏🏼
how did you get the JwtAuthenticationConverter to work in the SecureityFilterChain ?
@@mathewfrancis4167 I’ll check in a bit and get back to you
@@fetterollie54I'll be infinitely great-full when you will :)
@@mathewfrancis4167
Not sure if you can put code blocks in here:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
http
// disable cross site request forgery
.csrf(csrf -> csrf.disable())
// any http requests are authorized
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/auth/**").permitAll();
auth.requestMatchers("/admin/**").hasRole("ADMIN");
auth.requestMatchers("/user/**").hasAnyRole("ADMIN", "USER");
auth.anyRequest().authenticated();
});
http
.oauth2ResourceServer((oauth2) -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())));
http
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
// build into security chain
return http.build();
};
Also I stepped away from the project a month ago and haven’t looked at it since. Hope this is what you are looking for…
Just one word about this video - PERFECT.
What a fantastic to the point video it is, Thank you so much Ethan for sharing valuable knowledge with all of us, my knowledge before and after watching this video has increased very much, looking forward to more of your videos.
I had watched a bunch of videos on this topic, but your explanation made it much easy to follow and code along with you.
Holy crap. Thank you so much; this is amazing. Top tier content. I learned so much from this compared to hours of Amigoscode or Dan Vega. Nothing against those guys, they just have so much content to get through and a lot of it is outdated. Thank you so much for putting this together. I got what I needed out of it and then some.
Thank you so much! I highly recommend this video to anyone who wants to learn about Spring Security. It is a comprehensive and informative resource :)
Fantastic Video, Thank you for putting all this together in one place and having it explained very clearly and at a steady pace. Great work!!!
Finally found a video for working around the older deprecated methods. Thank you very much.
Edit:
Unable to generate the jwt token during login, and getting a 401 Unauthorized error response back.
Might be an issue with the deprecated jwt() method in oauth2ResourceServer(oauth2ResourceServerConfigurer::jwt()).
But even with the new code oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())) which provides a default implementation of the oauth2ResourceServerConfigurer class its not working.
If anyone has faced the same issue and solved it, Please let me know. Thank you.
I had exact the same issue but I skipped the line 'daoProvider.setPasswordEncoder(passwordEncoder());' under SecurityConfiguration class -> AuthenticationManager ... i had only "daoProvider.setUserDetailsService(detailsService);" hope it helps.
Yes please help in this. I am facing the same issue in intellij.
@@TheMrBaticaBut here daoAuthenticationProvider.setUserDetailsService(detailsService) is used . So what did you exactly change
I wrote what was my problem. I didn't have -> 'daoProvider.setPasswordEncoder(passwordEncoder());
@@TheMrBatica Thanks, I had the same problem. Maybe someone has the same issue, so here I put proper code: @Bean
public AuthenticationManager authManager(UserDetailsService detailsService) {
DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();
daoProvider.setUserDetailsService(detailsService);
daoProvider.setPasswordEncoder(passwordEncoder());
return new ProviderManager(daoProvider);
}
Man, this video is top notch. It is exactly what was missing from youtube. Could you, please, share with us, how did you figure all this out? What materials did you use for documentation or how was your thought process? Or maybe is it just experience? I watched Dan Vegas' video about JWT and I was really wondering how to achieve role authorization. I wouldn't have figured it out by myself.
Well done. Had some troubles with dependencies but overall your video is quite amazing! Thank you so much!
Amazing video! Such a complex topic was explained in a relatively simple way, thank you!
Liked the video! Here's an idea for future tutorials, can you create git branches for each chapter? this way we can go back and forth between different chapters to compare and contrast the changes.
The Best explanation I have even seen for spring security and jwt authentication. Thanks alot.
What I usually want to see in security videos is handling security for different type of roles. E.g a backend service for sellers and buyers, drivers and riders, students and teachers and so on
lo que tu quieres es manejo de roles
hey have you figured it out ? any other resources you found ? cause I have to implement it in project
this logic is implemented in the SecurityFilterChain bean in your security configuration class
Wow, first time I get it right. Thank you! This channel should have much more followers.
I had some issues using Lombok, but when I did all the constructors, getters, setters manually it's finally worked! I guess I need more experience with constructors first, then use lombok.
I have also had issues with Lombok and I know others sometimes do as well. That is why I chose not to use it in this video.
This was fantastic! I followed it, but changed JPA to jdbcTemplate, because the road to Hell is paved with too much abstraction. Doing it that way, everything made perfect sense. Thank you!
Absolute gold of a video
Good video, I watched it to the end, kinda hard to understand the whole thing because I've just started learning this framework but with the time for sure I will comeback and watch it again!
Yeah, very true.about 80% of the videos sessions use deprecated modules
thanks for this amazing masterclass
Thanks, for this great tutorial. Concise and blazingly fast.
perfect video, everything will go smoothly without getting any blocker for me, thanks brother for such a nice video😍
Wow, you had me in the first 20 seconds. Got the problem absolutely spot on. thanks
I have done exactly as you have mentioned in the video upto configuring basic authentication, I keep getting 401 unauthorized exception despite supplying the username and password correctly
clear and concise, great video mate!
Fantastic video...only problem I recieved was at 1:35:00 during login There is no PasswordEncoder mapped for the id "null" i don't know if I have done something wrong or need to update spring security....it doesnt work with admin as well
Double check the repository in the description, I believe you are missing the mapping for the password encoder in the SecurityConfig class.
I double checked it and there was nothing missing..but when I copied all code from Config class it suddenly worked..thanks for the answer@@unknownkoder
I have one more question though..now that we have functional webapp working through postman.. how can I set up this to work within webpage ? I mean now we have working hashing and tokens.. I created login and register form.html but don't know how to connect those parts together
@@unknownkoder same error for me too.
I had the same problem,
for me I had not set the password encoder in the AuthenticationManager Bean in security config
@Bean
public AuthenticationManager authManager(UserDetailsService detailsService){
DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();
daoProvider.setUserDetailsService(detailsService);
daoProvider.setPasswordEncoder(passwordEncoder()); //this line I had not written
return new ProviderManager(daoProvider);
}
this guy is a true legend fr
Trust me I haven't started this tutorial, I just read the description and I know Spring Security is bagged already😆😅
Absolute legend for making this
GOAT
It was indeed an absolute Behemoth of a video! Great tutorial, loved the pacing and the explanations. My subscribe and like is your good sir.
1:35:11 Here when i am trying to hit it on postman, i am getting 401 unauthorised error. The error was "No password mapped for id "null" .
Please help !!
Edit: This problem is solved using oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()) because jwt is depriciated.
Another one that could be helpful is using (oauth2) -> oauth2.jwt(jwtConfigurer -> jwtConfigurer.jwtAuthenticationConverter(jwtAuthenticationConverter())) ) while using convertor.
same error and stuck
thanks for the comment. can you please also write the jwtAuthenticationConverter method? @manmitapatnaik2513
@@mytestchannel8256 the same as shown at 1:36:48
I solved by the adding the line "daoProvider.setPasswordEncoder(passwordEncoder());" to the authManager method.
@Bean
public AuthenticationManager authManager(UserDetailsService detailsService) {
DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();
daoProvider.setUserDetailsService(detailsService);
daoProvider.setPasswordEncoder(passwordEncoder());
return new ProviderManager(daoProvider);
}
Thank you for your solution! It helps me a lot!
Much needed video on the upgraded ways of Spring Security, I'm glad that i was able to find it
I have a request though, could you also post a video on formLogin using spring security
Hi man, i have this erro in my securityConfiguration.
line : .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
Error: 'jwt()' is deprecated and marked for removal
Do you no fix?
you can have it like this
http
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.jwtAuthenticationConverter(jwtAuthenticationConverter())
)
);
Is this some help for this part of code?
If anyone please help
fyi if you are struggling with deprecated methods, or other things (example: I was unable to run project due to an error with the security filter chain method, request matchers specifically. You can always just downgrade the version of Spring Boot in your POM.xml to use what was used in the video and everything will work.
Nice idea
Thank for the detailed explanation, please suggest how to do authentication for an application using Thymeleaf and MVC controller.
one of the best security tutorial, clear explanation, am now confidence about spring security. Thank you @Unknown Coder
my project is not running bro
Can you help me with something? I got stuck at some point
great content video with proper explanation keep doing contents like this 😍, i was looking for this type content for many days, i just wasted a lot of time but this saved my time and can explain how to save roles in DB annd retrieve it from DB and also about OAuth 2.0
How to validate jwt is invalid or expired?
This is a greate tutorial. Thanks for that!
Excellent tutorial. This is just what I needed to get started.
Absolutely amazing video, learned a lot from this, Thanks!!
Hey @Unknown Koder, I fixed the bug you encountered at 1:41:35, apparently this stems from a deprecated use of the jwt() Method, this is the correct way of configuring it as of Spring Security 6.1.x:
.oauth2ResourceServer((oauth2) -> oauth2
.jwt(jwtConfigurer -> jwtConfigurer.jwtAuthenticationConverter(jwtAuthenticationConverter())))
why there is no doFilterInternal to filter the JWT and check if it was valid, and as I remember there was a secret key that is used to generate JWT
This is a really great tutorial. Thanks for this
Thank you so much after searching alot i found this video that covered my ground up spring security and jwt thank you man.
thanks for a clear video. its incredible how spring security team has no good documentation for spring security 6
Greate tutorial,
Am asking for getting an end-point which returns an access token by accepting refresh token, Note Access token should also be returned on login attempt.
I am using DOMA, I can't declare the Set authorities as it says it is not supported as persistent type.
the video is really helpful, but faced a problem, can you help me out ?
1:09:44 => there is no arg for httpBasic() method in Filtercahain config method
1:09:47 => Suddunly a the arg appeared as httpBasic(withDefaults())
can you explain the purpose of withDefault() method? did you create it or it will be refered from somewhere else
If you take a look at the repository in the description, and go to the AuthConfiguration class you will see that withDefault() is a static import from Spring Security.
@@unknownkoder Thanks for clarification, btw the actual problem is, I am facing while adding the permitAll() access to the auth/** for registraion at 1:09:50 , I got an error while starting the server after adding it i.e
Factory method 'filterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher).
so I think it may prevented by adding withDefaults(), but showing same even after addding, can you help me out ?
Is there any need for the JWT Auth Converter to set the roles to "ROLE_ROLENAME" if you just set the roles in the DB to be begin with "ROLE_"?
tôi mới học khá lúng túng với spring security nhưng xem hết video của bạn tôi đã hiểu hơn rất nhiều, cảm ơn video của bạn.
Spring Security is confusing but you did a great job.
I found a lot of things in one place it helped me a lot.
Thanks
Lovely just what i needed ... i'm new to this level of spring security ... so I hope this question isn't a silly one ... i would like to know how and where you generated the public and private key in you code... thank you :)
Great Content!!! Can you make a video on how this authentication backend works with API gateway ? Any of the members if know
There is a problem casting the Principal to UserDetails as per your implementation.. any ideas? Am trying to get the logged in user via SecurityContextHolder.. thanks
I'm following the tutorial but I get problem with login, I get 401 . Can you explaint it for me . Thanks
401 means that the security configuration is not allowing connections through. So check that.
@@unknownkoder I got the error : "There is no PasswordEndcoder mapped for the id "null" ". I created PasswordEncoder bean follow your tutorial. I dont know why login not working, I test api in register and it works normally
@@nguyenhoanganh7228 I think later on in the video I made a correction where I missed a line of code for the password encoder.
@@unknownkoder I have the same error and there is no fix in the later minutes of the video
@@nguyenhoanganh7228 In your SecurityConfig code the authManager like this:
@Bean
public AuthenticationManager authManager(UserDetailsService detailsService){
DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();
daoProvider.setUserDetailsService(detailsService);
daoProvider.setPasswordEncoder(passwordEncoder());
return new ProviderManager(daoProvider);
}
Do I understand it correctly that in the client after login i need to save the token from server response and put it to every request made afterwards?
Hi, this was an exhaustive example I've been looking for. Thank you very much!
I would like to extend this project with static HTML pages. How can I do that?
I've added HTML pages (e.g. an index.html under resources/static) but I can't access any of the pages. they're all blank and I get 401 responses to them.
I tried to add the static path to auth request matchers, but no joy so far. Any ideas what's missing? Thanks in advance!
Hey guys! Is it normal for role authorization to not work without a Converter even if we set the role in DB as ROLE_ADMIN for example? Because I just spent a lot of time with it and it did not work at all even if I would use roles such as "ROLE_USER", "ROLE_ADMIN". It began working only after setting the roles in DB as simply "ADMIN" and "USER" then adding the converter as in the video.
Now I am experiencing dependencies cycle from AuthenticationService to SecurityConfiguration with the AuthenticationManager. How am I fix this?
Awesome video, I followed everything you said (mostly) and got postman working at the end, but Im a bit confused on how to implement a login page and move to a secured page?
Thanks very much for the vid! Really enjoy your teaching style!
I am having a bit of a problem though, when I change the loadUserByUsername() method inside the UserService class to call findUserByUsername on the repo, the app stops accepting a valid username & password combination of admin.
I have checked the database and the user admin tuple is definately there but I get an error 401 no matter what I enter?
Have been stuck on this for a few days so would appreciate any help!
Thanks very much in advance!
Sounds like a problem in the Spring security configuration most likely.
@@unknownkoder Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(UserDetailsService detailsService){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(detailsService);
return new ProviderManager(daoAuthenticationProvider);
}
@Bean
public SecurityFilterChain filterChain (HttpSecurity http) throws Exception{
http
.authorizeHttpRequests((authz) ->
authz.anyRequest().authenticated()
)
.httpBasic(withDefaults());
return http.build();
}
}
This is my ssecurityConfig at 47 mins - Can you see anything that might be causing this?
Thanks in advance!
i have the same problem , have you solved it ?
@@paulosamvrosiadis3484 Yes!
Turns out I wasn't sending the POST request properly. Using postman & ensuring I was sending a POST request properly helped solve it. Goodluck!
Same problem :(
towards the end when we were setting up the jwt auth converter alot of the stuff you shown was deprecated. So i switched it over to the more recent stuff but when i coded it im getting an 403 forbidden error.
after getting the jwt token right? did you find a solution?
How do you use this with frontend? Do you have a tutorial for this?
I dont have a one for one tutorial, but my twitter series shows building a login and registration system with react and spring security.
@@unknownkoder I have built one with react and Springboot before but I used Redux for my security and jwt tokens, but is there any other less complicated way?
Hi bro,i have face one problem there is no error in my code.i have been writing commandlinner runner after i run this mhy progrma there is no error and go to postman send the username,password i was face 401 error.what i made mistake.why we are using commanlineer interface instade of we can create any onther classes
Anyone else got stock with a error: "There is no PasswordEncoder mapped for the id "null" at 1:35 ?
Hey! I have just reached this problem in my app. I got 40-1 while login. I just added PasswordEncoder in authenticationManager.
@Bean
public AuthenticationManager authenticationManager(UserDetailsService detailsService, PasswordEncoder passwordEncoder){
DaoAuthenticationProvider daoAuthenticationProvider=new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(detailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
return new ProviderManager(daoAuthenticationProvider);
}
@@kadrimv5202 was having the same issue and this fixed it THANK YOU SO MUCH
I how to do to allow user to access and resource when his already been logged. and don't have toprovide access token again on the frond end?
At 1:09:43 - "public SecurityFilterChain ....." is at line 30 but,
at 1:09:44 - It is at line 32.
After this step the program is not running and giving this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'filterChain' defined in class path resource [com/sanyam/springsecurity0609/configuration/SecurityConfiguration.class]: Failed to instantiate [org.springframework.security.web.SecurityFilterChain]: Factory method 'filterChain' threw exception with message: This method cannot decide whether these patterns are Spring MVC patterns or not. If this endpoint is a Spring MVC endpoint, please use requestMatchers(MvcRequestMatcher); otherwise, please use requestMatchers(AntPathRequestMatcher).
This is because there is more than one mappable servlet in your servlet context: {org.springframework.web.servlet.DispatcherServlet=[/], org.h2.server.web.JakartaWebServlet=[/h2-console/*]}.
For each MvcRequestMatcher, call MvcRequestMatcher#setServletPath to indicate the servlet path.
@@sanyamsharma9526 I had the same issue. Below I am sending my solution.
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception{
MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector);
return http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests((requests) -> requests
.requestMatchers(mvcMatcherBuilder.pattern("/auth/**")).permitAll()
.anyRequest().authenticated()
)
.httpBasic(withDefaults())
.build();
}
Thank you for the video, do you know how i can be able to display this information in my next js project
excellent tutorial, and thank you for the timestamps!
Hi!
When I run the Maven app and try and access an endpoint in browser I get: “Request Method ‘GET’ is not supported.
Do you know what could be causing this?
The only difference between yours is I am using Postgres driver.
Thanks!
does this implementation works with connecting to frontend angular ?
mega tutorial man, THANKS !
This video is the best spring security video ❤
thank you very much, I stucked at OAuth2ResourceServiceConfigurer :: jwt it already depricated, how to solve could someone answer please
Most of the security chain changes have moved them to similar styles with lamba functions. In this case I was able to solve it by using
.oauth2ResourceServer((oauth2 -> oauth2
.jwt(Customizer.withDefaults())))
hmm how strange when i send a username and password like 1:10:40, the json response that i got said "authorities: null" eventhough i checked with my database and everything was correct
nevermind i fixed it, turns out i left my getAuthorities method to return null.
Thanks for the vid, the deprecated APIs were a pain in the ass!
Do we really need to return user credentials (even if it's wrapped into some DTO without any sort of sensitive information)? I mean is it so-called "best practice" or we can just return simple status code? Is it mandatory to return anything or we can just use void methods in such cases?
Its not mandatory, however some applications may use some of the users information in the frontend of the application. This is why I send back basic info in the tutorial.
From your implementation, how will it be possible to add permission to a users roles? from what I can see, there can only be one authority/permission. I am not too clear on that part.
Also previous videos I have seen usually have a secret in the application.properties file that the jwt encoder uses. why dont we have that? is it because we are using the RSA encryption thing? if you have links that explain this in springboot context, I will appreciate if you can share it.
I also did notice one downside in that if the application restarts, users have to login again. Can you explain why this is so?
And for some reasons, when I try to log the currently logged in user using @AuthenticationPrincipal, I get an error
One Question. When the token will be sent back to the user in JSONObject, how do i solve it in the FrontEnd actually? User has to insert the Token in order to log in and access the Website. Email it to the user is bullshit, isnt it? Or am i missing something?
Great video, really helpful!
I'm trying to do this with MongoDb as the database, and I lose myself when i end up trying to create the roles. Since MongoDb isnt a relational db, its a little confusing when im trying to make "join tables"
Hey, I get the following error trying to login following your tutorial:
java.lang.IllegalArgumentException - There is no PasswordEncoder mapped for the id "null".
Could you help me?
You missed setting up a bean somewhere inside of the configuration would be the first place to look.
@@unknownkoder Ty for the reply. I fixed it by changing the PasswordEncoder bean to:
@Bean
public PasswordEncoder passwordEncoder() {
String idForEncode = "bcrypt";
Map encoderMap = new HashMap();
encoderMap.put(idForEncode, new BCryptPasswordEncoder());
return new DelegatingPasswordEncoder(idForEncode, encoderMap);
}
This adds the {bcrypt} prefix to passwords stored in the DB and fixes the problem.
@@thomasvs2911 What you needed to do was
@Bean
public AuthenticationManager authenticationManager(UserDetailsService userDetailsService) {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return new ProviderManager(daoAuthenticationProvider);
}
You forgot to set the password encoder here. Change your password encoder back to Bcrypt
I also encountered the same problem, your solution helped me out, thank you)
you need to add daoProvider.setPasswordEncoder(passwordEncoder()); to your authManager() method
Hello, good tutorial. Can you please tell me how to deal with CORS? Simply adnotating the controller wont work
Theres a CORS configuration you must setup inside the Configuration class and inside the config bean
Thank you for your content!
Thank you so much bro, you are a life saver
I have a little confuse. Are u using Authorization Code or Resource Owner Password Credentials. Can u help me to clear my mind
Wow. Thank you for this. Brilliant
Brother, you are a lifesaver!
Great Video!
Thank you for the video!
sick hoodie man
Whats the tool being used to create the architectural diagram in your video?
Nice tutorial but can you tell me how do I follow these steps from spring security documentation?
Very nice video! Can you tell me how to log out with a jwt token? Should I store it in tokenRepo and disable it on logout? Thanks!
Yes, there should be something along the lines of an invalidate method for your token object.