I just want to come back here and let everyone know how awesome your content is. I will be attentive to all of your new video uploads. Easily the best tutorial I've seen on Spring Boot JWT Authentication.
I'm new to auth and springboot so this video is perfect, a bit beyond my capabilities at the moment but hopefully I'll get the hang of it soon (I can't believe you're using class components for react 😅)
This is a great video. But it would be wonderful if you could include features like handling expired tokens and also features to refresh expired token. Role is also important. I hope you will include those features in other videos and prepare play list. Thank you
Really great video, clear and quick explanation, thanks! Couple of questions though: how do you "hide" the password on the dev tools inspector payload of the request (we can see it at 1:06.11) - is this something SSL takes care of in production? I also wonder why you don't use @Autowired.
Thank you! About the password, it's hidden in the input element by using type=password, but it's clear when using the dev tools inspector. And about the Autowired annotation, I use the injection by controller (recommended) with Lombok instead of the injection by reflection with the Autowired annotation.
It was a good video. I've seen a few with Jwt, but this one had a little bit of another approach. I guess you should add roles to the User entity because you often have different options and front-end should render different components/pages for ROLE_USER and ROLE_ADMIN as well as functionality will vary depending on the role.
Thanks. I didn't want to add the roles, because it's already a long video. If you want more about the roles, check this one, th-cam.com/video/ZBeyy4Q3nIw/w-d-xo.html
Great demo. Thanks, Sergio. I do have a question. For the backend Spring Boot, I read in a book that if you didn't provide a UserDetailsService, that means the default InMemoryUserDetailsService gets used. Is that the case here?
Thanks. Maybe, but if you manage your AuthentationBean by your own, you don't care about the UserDetailsService. It will save a username and password in-memory, but it will never be used.
Sergio such a great content. I am trying to develop a full stack application & saw your work on Keycloak. I am doing more research but what is your experience, is Keycloak more secure than this method ?
The best advantage on using a technologie like Keycloak is that the credentials are stored outside your application. Your application won't need to care about the user's account, the user's credentials, the database encryption... And the same user account can be used for multiple applications (say you use Facebook Connect or Google Suite instead of Keycloak). Still, this need to maintain a second application in a separate network. The alternative, using simple login form with a JWT, is easy to implement and secure enough. Still, the users need to create a new account on your application. But you need to create the strategy to only accept strong passwords, passwords rotation, password encryption at storage... It's up to you to choose.
This is awesome! Can you make a video building a full stack app using React and Spring and use msal Java to obtain Azure Credentials to call Microsoft Graph? I feel like a lot of people do OAuth stuff on the Frodo tend side and don’t realize that it should be done on the backend side
Make a video on Login Registration using React function based component, Spring security , mysql database with jwt authentication 🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉
Changing from Postgres or Mysql is not very hard. And if you take a look to the github repository, half of the components are function based. It should be easy to find what you're looking for
Nice video bro , but i have a question like if in backened i have a url that should be accessible to an authenticated user by spring security then how will we call that from frontened , as here we have permitall() but if restrictions for specific roles was then how to do it
@@TheDevWorldbySergioLema my doubt is , how to access the controller method (in backend )that are accessible to particular user (by spring security configuration user role) from frontend (I want to hit controller api from react js frontend)
Ok, I see. You need to use the PreAuthorize annotations to filter the requests per roles. I have a video pending about this topic. Meanwhile, you can watch an old one: th-cam.com/video/ZBeyy4Q3nIw/w-d-xo.html
Hey Awesome video!! And quick doubt : Why are we checking the user by login method? Shouldn't we check with the user email or both? And also can you do a video on login using google or fb or any other? oauth2?
Some websites use a login or username, and some other use an email. It's up to you to choose which uniq identifier to use. About the OAuth2 protocol, I've done a video using Github: th-cam.com/video/7gWcPWh5WVY/w-d-xo.html And there is another playlist where I use an authorization server created by Spring or Keycloak: th-cam.com/play/PLab_if3UBk9-AArufc8CryyhSDVqkNT-U.html
In this video I use a standard login, username and password. And the login form is managed in React. For more advanced login types, like OAuth2, check the video and playlist I've shared with you. About using OAuth2 with Google, I'm preparing a video about that. I will be ready soon, stay tunned.
Excellent content helps me a lot in my work. However, I have a question. How do we validate the token expiry? Suppose the token saved in local storage expires, then what happens? how to request a new token and use it. Could you please help?
There are many alternatives: * you can request the user to log in again; * or you can have a renew token to obtain a new fresh token Check this blog article where the alternatives are explained: sergiolema.dev/2023/03/13/how-to-renew-a-jwt-without-requesting-to-login/
Axios is a frontend library to make requests from the frontend to the backend (or to somewhere else). As I'm in a stateless application, the token is saved nowhere in the backend; if I don't store it in the frontend, it will be lost.
Bonjour Sergio, j'ai une question à propos de la sécurité d'une application. Est ce que l'utilisation des JWT suffit à protéger entièrement l'application contre les attaques du type CSRF ou alors suis je également obligé d'utiliser des token CSRF ?
Salut. Non, le JWT va juste te permettre d'ajouter une couche d'authentification pour toutes les requêtes. Si tu veux te protéger contre les CSRF, tu dois implémenter les token CSRF. Tu peux voir un exemple ici, th-cam.com/video/bwnycqGosoA/w-d-xo.html
@@TheDevWorldbySergioLema Bonjour, En faite j'ai réfléchi à la question et le fait d'utiliser les JWT nous protège effectivement contre les attaques CSRF à la condition de ne pas conserver le JWT dans les cookies. La raison est simple, les navigateurs vont automatiquement ajouter les cookies à chacune des requêtes. Ainsi, si le JWT est conservé parmi les cookies alors il sera automatiquement ajouter aux requêtes et par conséquent l'application devient vulnérable aux attaques CSRF. Il faut également penser à s'occuper des attaques XSS.
Hello, thank you so much for the video, but I encounter on bug I am really confused about, in UserMapper, it awalys give me error java: Unknown property "password" in result type UserEntity. Did you mean "null"? while I have everything the same as to the video, so may I ask what could be issue?
Thanks! It works well with my version of the project. Maybe it's the version of Mapstruct which changed the way it handles unknown properties. You can solve it by ignoring the password property.
Hi ! thank you so much for the video I love it, but in the config the Security config exceptionHandling() and() csrf() sessionManagement() are all deprecated and marked for removal , is there any update video for those, thank you so much!
Thanks. I've made this other video with the latest version of Spring Security. The frontend is made with Angular, but the backend remains similar. th-cam.com/video/YUqi1IjLX8I/w-d-xo.html
Very good job bro, nice work. But please for the next videos just take it slower and take your time to explain a bit more the code and the implementation flow. Also, maybe structure a bit the video, because i feel that you just wrote from a prompt, maybe take it step by step next time. Thank you tho
How are you sure that value -102 will provide you the lowest position to be used before any Spring Security filter ? And why didn't you use "Ordered.HIGHEST_PRECEDENCE" ?
No, I didn't made yet videos about the logout, but I've written this article about how to invalidate a JWT token: sergiolema.dev/2023/04/03/3-ways-to-invalidate-a-jwt-token-in-the-backend-side/
I'm thinking of doing it with tokenEntity, tokenRepo and validate/invalidate the token in the backend and reset the token in the frontend@@TheDevWorldbySergioLema
In fact, you can't invalidate a token from the backend, as it's stored in the frontend. What you can do, is have a table with all the tokens per user, and when invalidating a session, remove all the tokens for a user. And when validating a token, check against this table too. But you loose a little bit of Stateless. In my blog article I describe it more in details.
bro you're storing jwt token in localStorage which is vulnerable to xss attacks, storing in client storages will make it easier to get tokens for any scripts to access, I've read that its better to use cookie and that too httpOnly cookies to store jwt, can you show us that with example how to?
Using the cookie to store the JWT is an alternative, yes. Both have their advantages and disadvantages. What if the user or the website doesn't allow the usage of cookies? If you use a HTTPS communication, in both cases you reduce the risks. I will try to implement it using the cookies to better see the impact.
@@TheDevWorldbySergioLema yes pleases make a video on storing jwt token with httpOnly cookies from server side so that javascript cannot access it from client side
What if in my case the "secured data" is actually whole html webpage that i have in my frontend project running on different webserver then backend restapi? Should this secured html file be blank by default and instead let rest api serve whole html file content after being logged in? Or would i auto ri-direct from the secured webpage if user is not logged in? If the second aproach how would i implement it? In frontend? Is it safe to do implement it in frontend when user can just change the client side and somehow bypass this check? Thanks for any answers but only ones i found were in php.
If your "secured data" is an entire HTML page, it must be returned by the backend. Let me explain this. If you're using a frontend SPA like React or Angular, the entire HTML will always be in the browser, accessible to the user. If the HTML contains sensitive data, this is not good. The HTML must contain only the display logic. Then, request the backend for the sensitive data. This way, a hacker may display the HTML but without the sensitive data, it will be half blank. The frontend should have the logic to redirect to some login page if no token is available. Because this is a display logic. This is my opinion and a general behaviour. But it can be adapted to specific cases. Is it more clear to you now?
Thank you for the video! At the point, directly after putting AuthContent into the AppContent file, the information from the controller is still not displaying. I have double checked everything. I don't know what to do!:(
I figured it out! One, I wasn't even running the localhost server, and two, it was requiring login. I made spring security not require login just for now and ran the server and it worked!
Hi, I've made some time ago another video about connecting a Spring Boot application with MongoDb. Check it here: th-cam.com/video/2jykIvIKMeg/w-d-xo.html
Hey, do you know why after my first token expired, when i try to login through frontend i'm always getting the error that the token expired? I tried logging through different accounts and registering new ones. When i login through simple postman request everything works
after debugging i see that there is a problem with userAuthenticationProvider.validateToken(authElements[1])); being called in JwtAuthFilter, i guess we shouldn't validate the token when we are just logging in to obtain one? or am i wrong : [
ok i also found that clearing cookies helped, but now after logging in and after refreshing the page i need to login again to see the response - any direction i can head to always show the correct view based on login state?
Hi! Sergio! I got an error after created AuthContent. the error is " Uncaught TypeError: this.state.data.map is not a function ". I try to solve this issue, searched google and stackoverflow. and I copy and past from your github code also have same error. could you fix it?
I think that the returned value from the backend is not a list. So, React can't apply the map function to a not-list element. Check what you receive from the backend. Check if there is an error received in the backend. Check the content-type, if it's JSON and if it's a list. Hope this will help you!
@@TheDevWorldbySergioLema Thank you a lot for your reply! I fixed it. The problem was because of SecurityAutoConfiguration in main method. I got a hint from you. Really Appreciate!! Have a good day!
Even after adding webconfig as you explained, still seeing cors policy error. Followed your instruction as it is line by line. Any clue how to confirm if webconfig is applied as expected. One more doubt : Though you have added web security, without username and password you are able to retrieve the name list? Is it because of Corsfilter?
If you still see the CORS error, it's sure the WebConfig isn't applied correctly. Maybe the URL of the frontend isn't set correctly, maybe it's the filter which doesn't include your endpoints... Did you tried from a terminal or Postman? Add a breakpoint in the WebConfig to be sure it's loaded. Maybe it's the scan which isn't well performed on your bean. I'm not sure to understand your doubt. Which name list are you talking about?
@@TheDevWorldbySergioLema Thank you so much for your response. :) 1. I put breakpoints and confirmed that corsFilter is hit and FilterRegistrationBean bean is returned. 2. In post man I am getting following error. Status: 401 Unauthorized 3. I am using Spring Tool suite 4 with Java 8. 4. The name list is "first" and "second" in your example. Some more doubts 1. when i refer git hub you have added credentials as "backend". Is it required here? I am trying out without application.yml. Is this correct or my understanding is wrong? Sorry to ask very simple questions. I am new to this area. Thanks again for your help.
If it fails from Postman, it's not a CORS problem. The CORS problem appears from the browser only. This means that the problem is that you try to access a protected route without any credential. Have you first log in your user? Do you send the JWT in the header? If you have any other HTTP filter, add a breakpoint. there too, to be sure it reaches and goes out correctly. The credentials in the application.yaml are for the database. You can create the same database as I did with the Docker command available in the README.
I can't get past the CORS policy error, I also added the method on your newer CORS video, but it still gives me the same error. Not sure what I am doing wrong
Do you have the correct URL of your frontend? Do you have the correct annotations in the class? Maybe create a StackOverflow question with the code and link it here, I will try to answer it.
@@TheDevWorldbySergioLema Hi Sergio, it seems like the issue was with Lombok, and how I was handling dependency injections. I had to use @Autowired on some of the injections and annotate some of the classes with @Component. On top of that, the way I had to set up the securityconfig classes. I had to remove the Lombok annotations since I am using Spring Tool Suite, I wasn't sure why I couldn't use Lombok. I just went with creating the constructors myself for now. I watched your entire video twice lol, and couldn't figure it out. As of right now, I'm good. I configured the database to use MySQL instead of Postgress, as I don't know how to use Postgress/set it up. Do you know how to set the login buttons, and logout buttons to only display at the proper times? For example, if the user is not logged in, then show the login button, and if the user is logged in then only show the logout button. I searched online and it says to use the *ngIf but I'm not sure where I would need to put that 😅github.com/gustavo94manga/fullstack That is where you will find the slight modifications I used, which are all thanks to you🙌🏽 Also, I love your channel. When I grow up I want to be like you haha.
For the login/logout buttons, you already use the "componentToShow" variable. Just find the logic to display one or the other depending on the value of the variable "componentToShow". And update the value after the login/logout is successful.
i had the similar issue, all i did was create a new java file called "SecurityConfig" with the following code: @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .csrf(csrf -> csrf.disable()) .authorizeHttpRequests(auth -> auth .requestMatchers("/messages").permitAll() .anyRequest().authenticated() ) .httpBasic(httpBasic -> {}); return http.build(); } } basically the problem u are running into is that backend wont allow requests from "/messages" unless you are authenticated, this code permits requests from "/messages" without needing to login or anything
In the JWT filter, you parse the JWT, then, you can do whatever you want with the decoded content. In my case, I wanted to fetch the user entity from its ID.
Hey!! great video but, I tried to put the App.js, App.css and etc on a components file but desnt work :( could you help me with that? shows this error: ERROR in ./src/index.js 7:0-35 Module not found: Error: Can't resolve './components/App' in 'C:\Users\LENOVO\Desktop\climatec\frontend\src'
thank you sir!!@@TheDevWorldbySergioLema but now i have a problem, when i tried running the code in the minute 20:33 it appears this message: Uncaught runtime errors: × ERROR Network Error AxiosError: Network Error at XMLHttpRequest.handleError (localhost:3000/static/js/bundle.js:42250:14)
How would you hide? The token is shared to the frontend. There are many ways the frontend can store the JWT, but none are 100% secure. That's why the JWT must not contain sensitive data and has a validity date as short as possible
I try to separate the videos. This video is focus on the authentication. If you want to see how a todo project is built, check this other: th-cam.com/video/WTAjAo4v9qM/w-d-xo.html
@@TheDevWorldbySergioLema hello Sergio , yep i watched the video and but this is built with angular 😕if possible can you teach us todo using react and spring boot with auth . Thank you
I try to explain the main functionality of the code without entering too much into the details. This is an introductory video. If I explain in details all the code, it wouldn't be easy to follow.
This would break the restful mantra. But sometimes, it's necessary. Check this video where I persist the user's session in Redis, th-cam.com/video/YWVjnJsJRG0/w-d-xo.html Or do you mean storing the JWT in the database?
I do not understand, why all spring boot jwt authentication tutorials do not use refresh token? like c'mon bro You are not gonna set expiration date of a access token for a long time (3 months) cause it's not secure, also you are not gonna set it for a short time (24hrs) either cause i do not want my users to relog-in every 24hrs, so here refresh token goes, Can anyone explain me why don't they use refresh token, by them i mean all the spring boot jwt authentication tutorial authors
A refresh token is another logic, more complicated. In this video, I just introduce the Http Filters and how to generate a JWT. If you want to know more about the refresh token, I share you an article where I describe it clearly: sergiolema.dev/2023/03/13/how-to-renew-a-jwt-without-requesting-to-login/
El título, descripción y subtítulos están en Español si tienes TH-cam configurado para el Español. El sonido está en inglés (para llegar a mayor audiencia). Pero siempre añado los subtítulos en Español para que toda la comunidad hispana pueda entenderlos facilmente.
Maybe 6 years ago. But I've never worked professionally with React. I've only been working as Java or Python developer, backend developer or DevOps/Cloud.
At this moment (th-cam.com/video/bqFjrhRrvy8/w-d-xo.html), I am getting error in SecurityConfig class. The errors are: 1. 'exceptionHandling()' is deprecated and marked for removal 2. 'csrf()' is deprecated and marked for removal Can you please help me how to resolve these errors?
I see, this happens on the version of Spring Boot 3.1.0, but not on the one I'm using in the video, 3.0.2. The quick answer: use a previous version of Spring Boot. The hardest answer: I have to investigate the alternatives.
@@TheDevWorldbySergioLema Okay, so it would be good if you can suggest me a fix with the newer version. Because generally when we create a new project we won't use some older version. I am okay to wait for a few days for your help, say 5 or 6 days maybe?
Here is the same configuration with the new version of Spring Boot / Spring Security: http .exceptionHandling(customizer -> customizer.authenticationEntryPoint(userAuthenticationEntryPoint)) .addFilterBefore(new JwtAuthFilter(userAuthenticationProvider), BasicAuthenticationFilter.class) .csrf(AbstractHttpConfigurer::disable) .sessionManagement(customizer -> customizer.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests((requests) -> requests .requestMatchers(HttpMethod.POST, "/login", "/register").permitAll() .anyRequest().authenticated()) ; return http.build();
Hey, is there any way to return the JWT in postman? Basically I need this same in a mobile application where I won't be able to use window.localStorage
This is not secure way to do authentication... localstorage is not secure... do not save JWT, the best way is with cookie, as you did in the other video
Why??!! Which part is dirty??? 😅 The Java part is perfect, I've been using the code style for at least 15 years, the one recommended by the Java standards. I agree that the JS part is not so clean, IntelliJ is unable to apply a clean code style. Maybe I'm missing a plugin.
Great video! But when i'm trying to login from another pc in local network, i'm getting "POST localhost:8080/login net::ERR_CONNECTION_REFUSED". When i'm logining from localhost browser all work fine. Please help.
Localhost is only for the current PC. If you want to connect from a PC in the same network, instead of localhost you must use the IP address of the PC where is the application running
I used ip address of my application server(192….:3000) to connect to frontend from another pc, backend is hosted on the same server(app port :3000, back 8080). I see welcome screen , but after authorisation I have an error in Google chrome from localhost:8080. Or it will not work while the application and the backend are hosted on the same pc?
I just want to come back here and let everyone know how awesome your content is. I will be attentive to all of your new video uploads. Easily the best tutorial I've seen on Spring Boot JWT Authentication.
Thank you so much Angel 😅
You're a magician bro! Hope you get more subscribers because you deserve it.
Thank you so much! Keep watching the full videos and sharing them, i feel the subscribers coming 😅
I've been fighting cors issues, I've tried various examples I've seen and none of them worked, yours did. Thanks for that, I'd say you saved me! 😅
I'm happy for you. I also have another video which explains in details the CORS error and its solution, th-cam.com/video/uMJnAxapF7E/w-d-xo.html
Merci beaucoup Sergio! I found your video clear and concise. Demonstrating React, Spring Security and JWT in just one hour is impressive.
Merci à toi !
너무 너무 멋진 강의입니다. 저는 영어를 잘 못해서 자동 번역 자막으로 봤습니다. 아마 제가 모든 내용을 정확히 이해하지는 못했을거 같아요. 하지만 한국에 있는 어떤 자료보다 이 자료가 가장 잘 이해가 잘됐습니다. 무료로 볼 수 있어서 너무 좋았어요. 감사합니다.
Thanks. Hopefully Google translate me your message 😅. So glad my content reach this far!
I'm new to auth and springboot so this video is perfect, a bit beyond my capabilities at the moment but hopefully I'll get the hang of it soon (I can't believe you're using class components for react 😅)
Watch again, and try it on your own. You will quickly get it. (I'm not a React developer, I do what I can/know 😅)
Thanks so much Sergio,
Finally I got to understand the concept and the application of JWT in fulllstack app with your tutorial!, ¡Regards/Saludos!
😀
I'm so glad David!
Sergio, you are a great teacher. thank you
Thank you Pratham!
Than you very much!
It is working with my backend as well!
Huge upp!
I'm happy for you!
Good job
Thank you so much, bro!!!! I will continue to follow you!
So glad to hear that Minh!
Very nice one Sergio
Merci Arnaud !
This is a great video. But it would be wonderful if you could include features like handling expired tokens and also features to refresh expired token. Role is also important. I hope you will include those features in other videos and prepare play list.
Thank you
I'm on it. The roles will be my next video.
Then another one to handle the token renew and the logout.
@@TheDevWorldbySergioLema thank you sir!
Really great video, clear and quick explanation, thanks! Couple of questions though: how do you "hide" the password on the dev tools inspector payload of the request (we can see it at 1:06.11) - is this something SSL takes care of in production? I also wonder why you don't use @Autowired.
Thank you!
About the password, it's hidden in the input element by using type=password, but it's clear when using the dev tools inspector.
And about the Autowired annotation, I use the injection by controller (recommended) with Lombok instead of the injection by reflection with the Autowired annotation.
It was a good video. I've seen a few with Jwt, but this one had a little bit of another approach. I guess you should add roles to the User entity because you often have different options and front-end should render different components/pages for ROLE_USER and ROLE_ADMIN as well as functionality will vary depending on the role.
Thanks. I didn't want to add the roles, because it's already a long video. If you want more about the roles, check this one, th-cam.com/video/ZBeyy4Q3nIw/w-d-xo.html
You are saving me so much time! 😁
I'm so glad for you!
Great demo. Thanks, Sergio. I do have a question. For the backend Spring Boot, I read in a book that if you didn't provide a UserDetailsService, that means the default InMemoryUserDetailsService gets used. Is that the case here?
Thanks. Maybe, but if you manage your AuthentationBean by your own, you don't care about the UserDetailsService. It will save a username and password in-memory, but it will never be used.
Great content, keep them coming. The class based React components are horrible though - thank God they've changed their mind on this.
Thanks! Yes, this video has 1 yo. Now I use only the new method
awsome video, a graet quide thank Sergio.
Thank you Farzad!
Would it possible for you to post an updated video? Running into issues where the new spring security depreciated since version 6.1
I've made another video with a recent version of Spring Security but using Angular, check it, th-cam.com/video/YUqi1IjLX8I/w-d-xo.html
Sergio such a great content. I am trying to develop a full stack application & saw your work on Keycloak. I am doing more research but what is your experience, is Keycloak more secure than this method ?
The best advantage on using a technologie like Keycloak is that the credentials are stored outside your application. Your application won't need to care about the user's account, the user's credentials, the database encryption... And the same user account can be used for multiple applications (say you use Facebook Connect or Google Suite instead of Keycloak). Still, this need to maintain a second application in a separate network.
The alternative, using simple login form with a JWT, is easy to implement and secure enough. Still, the users need to create a new account on your application. But you need to create the strategy to only accept strong passwords, passwords rotation, password encryption at storage...
It's up to you to choose.
@@TheDevWorldbySergioLema thank you sir. Doing god's work :) I ll support your channel moving forward!
Thank you so much Nurlan!
This is awesome! Can you make a video building a full stack app using React and Spring and use msal Java to obtain Azure Credentials to call Microsoft Graph? I feel like a lot of people do OAuth stuff on the Frodo tend side and don’t realize that it should be done on the backend side
Thank you. But my knowledge on Azure is very limited. I will try to read something about this.
@@TheDevWorldbySergioLema It is definitely a niche topic but can be quite interesting for companies working with Azure and Graph API.
Maybe something about Azure can be interesting (and challenging as i've never used Azure)
Make a video on Login Registration using React function based component, Spring security , mysql database with jwt authentication 🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉
Changing from Postgres or Mysql is not very hard. And if you take a look to the github repository, half of the components are function based. It should be easy to find what you're looking for
Nice video bro , but i have a question like if in backened i have a url that should be accessible to an authenticated user by spring security then how will we call that from frontened , as here we have permitall() but if restrictions for specific roles was then how to do it
I'm not sure to understand your question. Can you reformulate?
@@TheDevWorldbySergioLema my doubt is , how to access the controller method (in backend )that are accessible to particular user (by spring security configuration user role) from frontend (I want to hit controller api from react js frontend)
Ok, I see.
You need to use the PreAuthorize annotations to filter the requests per roles.
I have a video pending about this topic. Meanwhile, you can watch an old one: th-cam.com/video/ZBeyy4Q3nIw/w-d-xo.html
Hey Awesome video!!
And quick doubt : Why are we checking the user by login method? Shouldn't we check with the user email or both?
And also can you do a video on login using google or fb or any other? oauth2?
Some websites use a login or username, and some other use an email. It's up to you to choose which uniq identifier to use.
About the OAuth2 protocol, I've done a video using Github: th-cam.com/video/7gWcPWh5WVY/w-d-xo.html
And there is another playlist where I use an authorization server created by Spring or Keycloak: th-cam.com/play/PLab_if3UBk9-AArufc8CryyhSDVqkNT-U.html
@@TheDevWorldbySergioLema oh ok. I thought login is the login type. Like Google, fb etc.
Thank you!
In this video I use a standard login, username and password. And the login form is managed in React.
For more advanced login types, like OAuth2, check the video and playlist I've shared with you.
About using OAuth2 with Google, I'm preparing a video about that. I will be ready soon, stay tunned.
@@TheDevWorldbySergioLema hey sure.. thanks a lot!!
thanks bro love u form Bharat
Thank you!
Excellent content helps me a lot in my work. However, I have a question. How do we validate the token expiry?
Suppose the token saved in local storage expires, then what happens? how to request a new token and use it. Could you please help?
There are many alternatives:
* you can request the user to log in again;
* or you can have a renew token to obtain a new fresh token
Check this blog article where the alternatives are explained: sergiolema.dev/2023/03/13/how-to-renew-a-jwt-without-requesting-to-login/
It was a good class 🧡
Thanks Jose!
Is axios always needed when communicating with a backend? Also does your browser ever persist the token to disk?
Axios is a frontend library to make requests from the frontend to the backend (or to somewhere else).
As I'm in a stateless application, the token is saved nowhere in the backend; if I don't store it in the frontend, it will be lost.
Bonjour Sergio, j'ai une question à propos de la sécurité d'une application. Est ce que l'utilisation des JWT suffit à protéger entièrement l'application contre les attaques du type CSRF ou alors suis je également obligé d'utiliser des token CSRF ?
Salut. Non, le JWT va juste te permettre d'ajouter une couche d'authentification pour toutes les requêtes. Si tu veux te protéger contre les CSRF, tu dois implémenter les token CSRF. Tu peux voir un exemple ici, th-cam.com/video/bwnycqGosoA/w-d-xo.html
@@TheDevWorldbySergioLema OK merci beaucoup, ça confirme mes doutes.
Au passage, merci pour tes vidéos, elles sont très intéressantes.
Merci à toi pour ce retour
N'hésite pas à les partager dans ton réseau, ça pourrait aider des autres gens
@@TheDevWorldbySergioLema Bonjour,
En faite j'ai réfléchi à la question et le fait d'utiliser les JWT nous protège effectivement contre les attaques CSRF à la condition de ne pas conserver le JWT dans les cookies.
La raison est simple, les navigateurs vont automatiquement ajouter les cookies à chacune des requêtes. Ainsi, si le JWT est conservé parmi les cookies alors il sera automatiquement ajouter aux requêtes et par conséquent l'application devient vulnérable aux attaques CSRF.
Il faut également penser à s'occuper des attaques XSS.
Bien vu. Merci pour ce partage!
Hello, thank you so much for the video, but I encounter on bug I am really confused about, in UserMapper, it awalys give me error java: Unknown property "password" in result type UserEntity. Did you mean "null"? while I have everything the same as to the video, so may I ask what could be issue?
Thanks!
It works well with my version of the project.
Maybe it's the version of Mapstruct which changed the way it handles unknown properties.
You can solve it by ignoring the password property.
Wow really helpful, Thanks a lot for sharing..
Thanks again for pushing your code to Github : - )
Thanks to you Mohammad for watching!
Hi ! thank you so much for the video I love it, but in the config the Security config exceptionHandling() and() csrf() sessionManagement() are all deprecated and marked for removal , is there any update video for those, thank you so much!
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(HttpMethod.POST, "/login", "/register").permitAll()
.anyRequest().authenticated()
)
.exceptionHandling(exceptionHandling -> exceptionHandling
.authenticationEntryPoint(userAuthenticationEntryPoint)
)
.addFilterBefore(new JwtAuthFilter(userAuthenticationProvider), BasicAuthenticationFilter.class)
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
} i updated to this one and it works
Thanks. I've made this other video with the latest version of Spring Security.
The frontend is made with Angular, but the backend remains similar.
th-cam.com/video/YUqi1IjLX8I/w-d-xo.html
Thanks - keep up the magic
I try my best 😅
Thank you so much for your guide!
Would u kindly to give a hint how to use it with standart spring form without FE ? ^_^
You mean with a server side frontend, like Thymeleaf? I've done a video about that here: th-cam.com/video/ig8k_5nEov4/w-d-xo.html
Very good job bro, nice work. But please for the next videos just take it slower and take your time to explain a bit more the code and the implementation flow. Also, maybe structure a bit the video, because i feel that you just wrote from a prompt, maybe take it step by step next time. Thank you tho
Thanks for your feedback!
That's something I've tried to solve on my new videos.
Tell me if it's good now!
you are a genius
Thank you Rudy 😅
How are you sure that value -102 will provide you the lowest position to be used before any Spring Security filter ? And why didn't you use "Ordered.HIGHEST_PRECEDENCE" ?
I don't know, I just put a high number.
You're right, I have used Ordered.HIGHEST_PRECEDENCE which is a better solution
Hi, this video is very good, but do you have another where you logout and clear or remove the JWT token?
No, I didn't made yet videos about the logout, but I've written this article about how to invalidate a JWT token: sergiolema.dev/2023/04/03/3-ways-to-invalidate-a-jwt-token-in-the-backend-side/
I'm thinking of doing it with tokenEntity, tokenRepo and validate/invalidate the token in the backend and reset the token in the frontend@@TheDevWorldbySergioLema
In fact, you can't invalidate a token from the backend, as it's stored in the frontend. What you can do, is have a table with all the tokens per user, and when invalidating a session, remove all the tokens for a user. And when validating a token, check against this table too. But you loose a little bit of Stateless. In my blog article I describe it more in details.
Love you bro❤
Thanks Rachit!
bro you're storing jwt token in localStorage which is vulnerable to xss attacks, storing in client storages will make it easier to get tokens for any scripts to access, I've read that its better to use cookie and that too httpOnly cookies to store jwt, can you show us that with example how to?
Using the cookie to store the JWT is an alternative, yes. Both have their advantages and disadvantages. What if the user or the website doesn't allow the usage of cookies?
If you use a HTTPS communication, in both cases you reduce the risks.
I will try to implement it using the cookies to better see the impact.
@@TheDevWorldbySergioLema yes pleases make a video on storing jwt token with httpOnly cookies from server side so that javascript cannot access it from client side
Ok, I add it to my TODO list
Thanks bro!! ❤️
Gracias por seguirme Eduardo!
What if in my case the "secured data" is actually whole html webpage that i have in my frontend project running on different webserver then backend restapi? Should this secured html file be blank by default and instead let rest api serve whole html file content after being logged in? Or would i auto ri-direct from the secured webpage if user is not logged in? If the second aproach how would i implement it? In frontend? Is it safe to do implement it in frontend when user can just change the client side and somehow bypass this check? Thanks for any answers but only ones i found were in php.
If your "secured data" is an entire HTML page, it must be returned by the backend.
Let me explain this.
If you're using a frontend SPA like React or Angular, the entire HTML will always be in the browser, accessible to the user. If the HTML contains sensitive data, this is not good.
The HTML must contain only the display logic. Then, request the backend for the sensitive data.
This way, a hacker may display the HTML but without the sensitive data, it will be half blank.
The frontend should have the logic to redirect to some login page if no token is available. Because this is a display logic.
This is my opinion and a general behaviour. But it can be adapted to specific cases.
Is it more clear to you now?
@@TheDevWorldbySergioLema Yes, thank you.
Thank you for the video! At the point, directly after putting AuthContent into the AppContent file, the information from the controller is still not displaying. I have double checked everything. I don't know what to do!:(
Is the request correctly performed? Is there any CORS error? Any JS error in the Inspect Tool of the browser?
I figured it out! One, I wasn't even running the localhost server, and two, it was requiring login. I made spring security not require login just for now and ran the server and it worked!
@@yourratking Exactly my error, thanks for that
Glad it works now
Hey. Could you please tell me what changes need to be done if we wanna use MongoDB as a database? Thanks
Hi, I've made some time ago another video about connecting a Spring Boot application with MongoDb. Check it here: th-cam.com/video/2jykIvIKMeg/w-d-xo.html
Hey, do you know why after my first token expired, when i try to login through frontend i'm always getting the error that the token expired? I tried logging through different accounts and registering new ones. When i login through simple postman request everything works
after debugging i see that there is a problem with userAuthenticationProvider.validateToken(authElements[1])); being called in JwtAuthFilter, i guess we shouldn't validate the token when we are just logging in to obtain one? or am i wrong : [
ok i also found that clearing cookies helped, but now after logging in and after refreshing the page i need to login again to see the response - any direction i can head to always show the correct view based on login state?
You're right. I should skip the token validation if the URL is the login URL. This way, you can renew a token without checking it again.
Hi! Sergio! I got an error after created AuthContent. the error is " Uncaught TypeError: this.state.data.map is not a function ". I try to solve this issue, searched google and stackoverflow. and I copy and past from your github code also have same error. could you fix it?
I think that the returned value from the backend is not a list. So, React can't apply the map function to a not-list element. Check what you receive from the backend. Check if there is an error received in the backend. Check the content-type, if it's JSON and if it's a list. Hope this will help you!
@@TheDevWorldbySergioLema Thank you a lot for your reply! I fixed it. The problem was because of SecurityAutoConfiguration in main method. I got a hint from you. Really Appreciate!! Have a good day!
Nice!
@@프레데릭말 Can you share how you solve it
I am facing this same error, I see the note about SecurityAutoConfiguration but not sure how to implement this, thank you!
do you have any references or samples of how to implement logout and invalidate the token?
Yes, check this article, sergiolema.dev/2023/04/03/3-ways-to-invalidate-a-jwt-token-in-the-backend-side/
@@TheDevWorldbySergioLema thank you
Even after adding webconfig as you explained, still seeing cors policy error. Followed your instruction as it is line by line. Any clue how to confirm if webconfig is applied as expected. One more doubt : Though you have added web security, without username and password you are able to retrieve the name list? Is it because of Corsfilter?
If you still see the CORS error, it's sure the WebConfig isn't applied correctly. Maybe the URL of the frontend isn't set correctly, maybe it's the filter which doesn't include your endpoints...
Did you tried from a terminal or Postman?
Add a breakpoint in the WebConfig to be sure it's loaded. Maybe it's the scan which isn't well performed on your bean.
I'm not sure to understand your doubt. Which name list are you talking about?
@@TheDevWorldbySergioLema Thank you so much for your response. :)
1. I put breakpoints and confirmed that corsFilter is hit and FilterRegistrationBean bean is returned.
2. In post man I am getting following error.
Status: 401 Unauthorized
3. I am using Spring Tool suite 4 with Java 8.
4. The name list is "first" and "second" in your example.
Some more doubts
1. when i refer git hub you have added credentials as "backend". Is it required here? I am trying out without application.yml. Is this correct or my understanding is wrong?
Sorry to ask very simple questions. I am new to this area. Thanks again for your help.
If it fails from Postman, it's not a CORS problem. The CORS problem appears from the browser only.
This means that the problem is that you try to access a protected route without any credential. Have you first log in your user? Do you send the JWT in the header?
If you have any other HTTP filter, add a breakpoint. there too, to be sure it reaches and goes out correctly.
The credentials in the application.yaml are for the database. You can create the same database as I did with the Docker command available in the README.
@@TheDevWorldbySergioLema I'm having the same issue, and idk how to solve it, algo when I go to the link in the browser it requires me to log in
Did you try with other browsers? Chrome, Firefox, IE...
Could you explain how to render and redirect the required components with react router?
I've done something similar in an old video, with an older version of React, th-cam.com/video/1IOX_B7sWXY/w-d-xo.html
How come when you were doing your yaml it didn’t seem to autocomplete any of your properties?
I have Intellij CE, maybe the autocompletion is only available for the paying version. Or I'm missing a plugin.
I can't get past the CORS policy error, I also added the method on your newer CORS video, but it still gives me the same error. Not sure what I am doing wrong
Do you have the correct URL of your frontend? Do you have the correct annotations in the class? Maybe create a StackOverflow question with the code and link it here, I will try to answer it.
@@TheDevWorldbySergioLema Hi Sergio, it seems like the issue was with Lombok, and how I was handling dependency injections. I had to use @Autowired on some of the injections and annotate some of the classes with @Component. On top of that, the way I had to set up the securityconfig classes. I had to remove the Lombok annotations since I am using Spring Tool Suite, I wasn't sure why I couldn't use Lombok. I just went with creating the constructors myself for now. I watched your entire video twice lol, and couldn't figure it out. As of right now, I'm good. I configured the database to use MySQL instead of Postgress, as I don't know how to use Postgress/set it up.
Do you know how to set the login buttons, and logout buttons to only display at the proper times? For example, if the user is not logged in, then show the login button, and if the user is logged in then only show the logout button. I searched online and it says to use the *ngIf but I'm not sure where I would need to put that 😅github.com/gustavo94manga/fullstack That is where you will find the slight modifications I used, which are all thanks to you🙌🏽
Also, I love your channel. When I grow up I want to be like you haha.
To let Lombok work on your IDE, you must enable the annotation processor. I don't know how to do it in STS
For Postgres, I always use a Docker image. you can find the command to run a Docker image with Postgres in my Repository's README
For the login/logout buttons, you already use the "componentToShow" variable. Just find the logic to display one or the other depending on the value of the variable "componentToShow". And update the value after the login/logout is successful.
About 20 minutes into the video I'm getting the value of login html of security, not first, second. Do you know why and how to fix this?
I'm not sure to understand your problem
i had the similar issue, all i did was create a new java file called "SecurityConfig" with the following code:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/messages").permitAll()
.anyRequest().authenticated()
)
.httpBasic(httpBasic -> {});
return http.build();
}
}
basically the problem u are running into is that backend wont allow requests from "/messages" unless you are authenticated, this code permits requests from "/messages" without needing to login or anything
In jwt auth filter, can i get jwt body to auth instead of get user info from database?
In the JWT filter, you parse the JWT, then, you can do whatever you want with the decoded content. In my case, I wanted to fetch the user entity from its ID.
Hey!! great video but, I tried to put the App.js, App.css and etc on a components file but desnt work :(
could you help me with that? shows this error: ERROR in ./src/index.js 7:0-35
Module not found: Error: Can't resolve './components/App' in 'C:\Users\LENOVO\Desktop\climatec\frontend\src'
Thanks!
You can check the complete code in my Github profile: github.com/serlesen/fullstack-jwt/tree/chapter_1
thank you sir!!@@TheDevWorldbySergioLema
but now i have a problem, when i tried running the code in the minute 20:33 it appears this message: Uncaught runtime errors:
×
ERROR
Network Error
AxiosError: Network Error
at XMLHttpRequest.handleError (localhost:3000/static/js/bundle.js:42250:14)
I don't know from where comes this bundle JS file.
Can you make a video with OAuth2 and Session token pls?
Does this video answer your questions: th-cam.com/video/yp28g5AJczM/w-d-xo.html
Which theme and font ur using?
In my IDE? The dark theme and default font of IntelliJ
In order to make the app secure, wouldn’t we want to hide the jwt token?
How would you hide?
The token is shared to the frontend. There are many ways the frontend can store the JWT, but none are 100% secure. That's why the JWT must not contain sensitive data and has a validity date as short as possible
Do you have a spring boot course in udemy? excelents videos
Thank you. No, I don't have any course en Udemy.
A todo project with auth would have been more helpful. But thanks 👍
I try to separate the videos. This video is focus on the authentication. If you want to see how a todo project is built, check this other: th-cam.com/video/WTAjAo4v9qM/w-d-xo.html
@@TheDevWorldbySergioLema hello Sergio , yep i watched the video and but this is built with angular 😕if possible can you teach us todo using react and spring boot with auth .
Thank you
I'm already working on it 😉
Hey Sergio
When can we except todo with auth video .
Thank you
It would be interesting if you explained the code more and didn't just write code without almost explaining its functionality.
I try to explain the main functionality of the code without entering too much into the details. This is an introductory video. If I explain in details all the code, it wouldn't be easy to follow.
Considering one where you use an identity service and oauth2
LIke this one, th-cam.com/video/hfeOqvHxHO8/w-d-xo.html ?
And here was me thinking you were only doing shorts.
🤣
what if we want to persist user login state ?
This would break the restful mantra. But sometimes, it's necessary.
Check this video where I persist the user's session in Redis, th-cam.com/video/YWVjnJsJRG0/w-d-xo.html
Or do you mean storing the JWT in the database?
The thing is, when we click refresh, we are thrown back to login screen, and I don't want that
But tbh your explanation is very good, sir !
You can store the token in the localstorage. It will be persisted when you refresh the page.
I do not understand, why all spring boot jwt authentication tutorials do not use refresh token? like c'mon bro
You are not gonna set expiration date of a access token for a long time (3 months) cause it's not secure, also you are not gonna set it for a short time (24hrs) either cause i do not want my users to relog-in every 24hrs, so here refresh token goes, Can anyone explain me why don't they use refresh token, by them i mean all the spring boot jwt authentication tutorial authors
A refresh token is another logic, more complicated. In this video, I just introduce the Http Filters and how to generate a JWT. If you want to know more about the refresh token, I share you an article where I describe it clearly: sergiolema.dev/2023/03/13/how-to-renew-a-jwt-without-requesting-to-login/
Hi Sergio
Please share react js with Spring boot code
You have it in the description of the video.
Here is the link: github.com/serlesen/fullstack-jwt/tree/chapter_1
How can i fix CORS error policy?
You have a chapter called CORS at minute 18 where I describe the solution.
And now I have this video dedicated to solve the CORS error, th-cam.com/video/uMJnAxapF7E/w-d-xo.html
¿POR QUÉ EL TUTORIAL ESTA EN INGLÉS Y EL TITULO EN ESPAÑOL?
El título, descripción y subtítulos están en Español si tienes TH-cam configurado para el Español.
El sonido está en inglés (para llegar a mayor audiencia). Pero siempre añado los subtítulos en Español para que toda la comunidad hispana pueda entenderlos facilmente.
Who uses class components?
It was long time ago 😅
I don't use it anymore
@@TheDevWorldbySergioLema thought so. I could not recognise that it was react at first.
🤣🤣🤣
can u do it with agular
Oh God! this will be really challenging! I've never worked with Angular 😅
@@TheDevWorldbySergioLema waiting for your magic
😂 I will give a try!
When did you start to learn React?
Maybe 6 years ago. But I've never worked professionally with React. I've only been working as Java or Python developer, backend developer or DevOps/Cloud.
At this moment (th-cam.com/video/bqFjrhRrvy8/w-d-xo.html), I am getting error in SecurityConfig class.
The errors are:
1. 'exceptionHandling()' is deprecated and marked for removal
2. 'csrf()' is deprecated and marked for removal
Can you please help me how to resolve these errors?
I see, this happens on the version of Spring Boot 3.1.0, but not on the one I'm using in the video, 3.0.2.
The quick answer: use a previous version of Spring Boot.
The hardest answer: I have to investigate the alternatives.
@@TheDevWorldbySergioLema Okay, so it would be good if you can suggest me a fix with the newer version. Because generally when we create a new project we won't use some older version. I am okay to wait for a few days for your help, say 5 or 6 days maybe?
Here is the same configuration with the new version of Spring Boot / Spring Security:
http
.exceptionHandling(customizer -> customizer.authenticationEntryPoint(userAuthenticationEntryPoint))
.addFilterBefore(new JwtAuthFilter(userAuthenticationProvider), BasicAuthenticationFilter.class)
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(customizer -> customizer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests((requests) -> requests
.requestMatchers(HttpMethod.POST, "/login", "/register").permitAll()
.anyRequest().authenticated())
;
return http.build();
@@TheDevWorldbySergioLema Thanks a lot, it's working now
Hey, is there any way to return the JWT in postman? Basically I need this same in a mobile application where I won't be able to use window.localStorage
Nice tutorial but I was expecting functional components for react js
I've created half of the React components as functional components, to both alternatives
Check the Github repository of the description.
Any class components he created are very simple to convert to functional.
no explicas casi nada del código
Explico los conceptos que utilizo. No explico cada línea de código, sino sería demasiado difícil seguir el hilo del video para principiantes.
Si hay alguna parte que necesitas mas explicación, dimelo e intentaré mejorar para el próximo vídeo.
i tried everything but cant fix 401 unauthorised error .
Does it come from the authentication entry point configuration? Do you have a response body with error?
El fondo blanco me arruina
😂 Puesto que trabajo muchas horas al dia, utilizar el fondo negro me cansa muchisimo mas la vista
This is not secure way to do authentication... localstorage is not secure... do not save JWT, the best way is with cookie, as you did in the other video
I know localstorage is not fully secure. But it's an easy way.
good tutorial, but very dirty code style((
Why??!! Which part is dirty??? 😅 The Java part is perfect, I've been using the code style for at least 15 years, the one recommended by the Java standards. I agree that the JS part is not so clean, IntelliJ is unable to apply a clean code style. Maybe I'm missing a plugin.
Great video! But when i'm trying to login from another pc in local network, i'm getting "POST localhost:8080/login net::ERR_CONNECTION_REFUSED". When i'm logining from localhost browser all work fine. Please help.
Localhost is only for the current PC. If you want to connect from a PC in the same network, instead of localhost you must use the IP address of the PC where is the application running
I used ip address of my application server(192….:3000) to connect to frontend from another pc, backend is hosted on the same server(app port :3000, back 8080). I see welcome screen , but after authorisation I have an error in Google chrome from localhost:8080. Or it will not work while the application and the backend are hosted on the same pc?
You must also adapt the CORS, as the frontend is not anymore at localhost
Thank you!
Hope it works