I've made a complete playlist about how to write unit tests with JUnit 5 and Mockito. Still, this is only the backend part. Never worked on unit tests for the frontend. ru-vid.com/group/PLab_if3UBk99yq2g9ewtJaKsHn9IwZ90p
At the start of the tutorial, after the CORS configuration, spring security force me to login, even if my html request is only for /messages, my program is obliged to get to /login...I have exactly the same code
If you have no Spring Security configuration, but you added the Spring Security dependency, it makes that all the endpoints are protected, and it redirects to a default login page. Continue adding the Spring Security configuration and it should work
when I do the line request(method: string, url: string, data: any): Promise { return axios({ method: method, url: url, data: data }); there is the following error: No overload matches this call. Overload 1 of 2, '(config: AxiosRequestConfig): AxiosPromise', gave the following error. Type 'string' is not assignable to type 'Method | undefined'. Overload 2 of 2, '(url: string, config?: AxiosRequestConfig | undefined): AxiosPromise', gave the following error. Argument of type '{ method: string; url: string; data: any; }' is not assignable to parameter of type 'string'.ts(2769) index.d.ts(52, 3): The expected type comes from property 'method' which is declared here on type 'AxiosRequestConfig' How to fix this problem?
The method request() is a method i've created on my own. it's not imported from a library. For more details, check the source code at: github.com/serlesen/fullstack-jwt/tree/chapter_2/frontend
How did you learn it, it's a black box, everyone uses it but no one knows about it. I'm a self learner and I don't have a company behind me, I'm unemployed, and I want to bring a product to the market, but I have to get my users securely registered or the procedure, and I'm scared because that can fall on my feet. My stack: -Angular, -Spring boot, wants the Angula app to authenticate then the user registers or logs in
This video is comprehensive and well presented. However, there are some serious problems with this instruction if you're following the video and making sure you completely understand each step. If you're simply downloading the repo and going with that, it may work fine. The repo needs to have snapshots of the code as tested; e.g., at 35:13. I find all of the praises a bit biased.
Thank you. What I'm trying is to explain the concepts and give a repository with the same code. I can't give you a repository prepared for everything with all the data (everyone will need a different use case)
Really loved your video just curious how we can implement jwt refresh token in angular. means how will automatically call from angular to spring boot refereshtoken api call after it's expired?
Both are represented as String, but the password is the most critical field in the application, so i convert it in char array to avoid having the characters in the same variable. I could have done the same for the login.
that's brilliant, please keep it up sir! I'm just wondering how one's supposed to learn all of that without guys like you?? It appears to me that there are not that many resources that go in-depth on spring security
Thank you so much for those kind words! In my case, I've learned from guys "like me" but while working. I had the chance to work with great people, great managers and great teachers. Now It's my turn to teach
I can tell you are a backend developer at heat. Love the video, the only question is, what if i want to send to the frontend the first name and the last name of the logged in user, so that the message will welcome them after logging in ? it should show "welcome Sergio Lema !" for example. What do i need to change ? Looking forward for your guidance :)
Thanks!! You can already do it with the code I've shown in the video. The response of the login endpoint is the user's information, where you can find the first name and the last name.
16:05 anybody else got stuck there as the front end didn't display the messages ? commenting spring-boot-starter-security dependency seems to fix the issue apparently but I'm not sure it's supposed to be like that.
Hi Sir, the applicaiton back and front end are running now but.. not really sure why i am getting backend point not found.. where as I am able to hit the endpoint via Postman..nt_app_login_form_3_Template_app_login_form_onSubmitLoginEvent_0_listener @ content.component.html:8 onSubmitLogin @ login-form.component.ts:29 LoginFormComponent_Template_form_ngSubmit_11_listener @ login-form.component.html:17 Zone - HTMLFormElement.addEventListener:submit (async) LoginFormComponent_Template @ login-form.component.html:15 ContentComponent_Template
Nice Tutorial! But beware at Minute 11:29 in Code Line 18, the request param for data should be "{}" and not "()" :) had quite an issue with that typo until i checked the git repo
Hello, first of all, thx for this great tutorial. I was just wondering if this can be used in production and if so, jwt is enought or do we need anything else ? i mean if we use jwt token and not cookies auth we don't need to enable the csrf no ?
Thanks! Yes, you can use the same configuration in production. A JWT is strong enough. The only thing you have to change is the way the database is initialized. Don't use create-drop on production
Love this video, very straight forward and informative. Just a question: Can you use the angular http package to connect to the backend instead of importing Axios?
@@TheDevWorldbySergioLema Sorry, just saw the other comments where you stated this, but you really did well using it for the 1st time. Also wanted to ask, how would I go about securing other endpoints after login in as a user? Say I wanna perform CRUD operations after login, how would I secure those endpoints using the token?
Thank you! In fact, if you take a look at the current SecurityConfig, you can see that the only open endpoints are the one about the login and register. The rest must be authenticated. So, adding more endpoints for CRUD operation will be by default protected with the JWT authentication.
Good tutorial but I have one thing to improve. It is: password is sent from frontend to the backend without any encryption. In my opinion it is easy to stole such password by this. It would be better to encrypt it on the frontend side and send to the backend side already not readable (at least for human).
That's a good point. But if you're application uses HTTPS communication, all the data sent in a POST payload will be automatically encrypted. So, you won't need to add this additional complexity.
Hi Sir.. I am getting the below error while running the Spring Boot Applicaiton /Users/Srikar/Desktop/Angular/AngularSecurity/backend/src/main/java/com/srikar/jwt/backend/mappers/UserMapper.java:14: error: Unknown property "password" in result type User. Did you mean "null"? @Mapping(target = "password", ignore = true) ^
What's the order of the dependencies in your pom.xml? You must have Lombok first, then Mapstruct. Otherwise, Lombok won't create the getters and setters and Mapstruct won't see the fields
I get Exception: The Token has expired on 2023-10-06T22:08:57Z while registering. Do I understand it correctly, if I do not have refresh token after 1 hour (validity of access token) I will not be able to access restricted endpoints?
This comes from the value you put in the field withExpiresAt. And yes, if you don't refresh the token before that date, you can't access the application anymore.
Hey, has anybody implemented response message when validation of JWT fails? If JWT is expired, or format is not good, we get Internal Error 500 in postman, but it would be good to have response message with more details
In the video I've just handled the main case: the JWT is always correct. If you want a more specific error message, you have to throw a custom exception in the catch clause.
Nice work! But one thing that looks odd to me : you do not delegate the user/password check against the data using User Details Service. Is this a choice? Again, on the Jwt filter, is there a way to delegate this to spring security, to avoid handling all by ourself?
I was not able to do it with UserDetailsService because I use custom JWT generation. I may investigate some more if there is a way to do it all by configuring Spring Security correctly.
Hello superb video ! I have a problem with the UserService, my ide (eclipse) tell me to initialise the 3 final variable. Do you have an idea to fix this ? thanks for you video it's really hepfull
Thanks a lot for this tutorial, It was very useful for me. Could you explain please if it is possible to refresh the expired token in this project or not? I found out that after the token expires I can't obviously login with the same username and password but also I'm not able to register a new user. There is always the same exception: 'com.auth0.jwt.exceptions.TokenExpiredException: The Token has expired on'. is it should be like this or I did something wrong?
The project was not developed enough to handle all the cases. Let me update the source code in Github to almost handle the basic situations. And I'm preparing another video about the token refresh 😉
very efficient and to the point,thanks for this tutorial, i just wanted to ask how can make the front end into one login component, since i want to add it to my project
Thank you! I'm not sure to understand you what do you mean with one component. If you want the code I've used, check the Github repository, you can find the link in the description of the video.
The CORS problem can only be solved in the backend, configuring the accepted frontend. Check the CORS chapter of the video available in the description
Excellent! I just happen to get a problem with the injection of the UserMapper in the UserService. Spring tells me it could not find the bean... Btw, I don't use lombok. Thanks !
Thanks. For the mapper, you must tell MapStruct to use the mapper as a componentModel = "spring". Then, you can inject the Mapper inside a service as always.
@@TheDevWorldbySergioLema Thanks for your quick answer but I already annotated the UserMapper class with these params and it still refuses to wire it...
@@TheDevWorldbySergioLema When I run the app. I really don't get what's happening, I properly annotated the mapper interface and it seems - indeed - that it's not in the app context (I logged the result of the search of the bean at startup -> applicationContext.getBeansOfType(UserMapper.class) and it returns nothing). I even added the @Autowired annotation to the constructor of the UserService... Also, for the sake of being complete, I must precise that I use the last version of spring boot (3.2) and Java 21.
I am getting this error message back when i try to run in Intellij at 33 minute mark: Service\UserService.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type 'com.scaweb.customerPortal.Repositories.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
Does your repository extends JpaRepository? Is it an interface? Do you have a correct injection method in the service (by constructor or using the Autowired annotation)?
thank you for this video. But i have a question if you don't mind: I want to reuse the same code for another front (client side and admin side, they share the same database), and I was wondering if its possible to include something else alongside the User here ?
@@TheDevWorldbySergioLema I meant the same JWT for 2 different angular fronts. I wanted to re-use the same code since I need the same backend code, but It's all good now I found a solution. Thank you !
The backend is a Spring Boot server running in a Tomcat web server on the port 8080. And the frontend is a separated application, a Single Page Application (SPA) running in a node server on port 4200.
On 44:19 I'm getting error 403 and 200. The Java console says "ERROR: relation "app_user" does not exist". I've been trying for hours to fix the issue but so far I'm out of luck.
How do you create the database? In the example I show, I use the property spring.jpa.hibernate.ddl-auto: create, which creates the schema on the database from the entities description. If you use another value (validates or none), you must create the tables and columns by your own.
Once you get the user authenticated, you can add a flag in the root component (like userAuthenticated), and use this flag to display different content with the syntax *ngIf="userAuthenticated == true". You can also have this similar logic in the router. But creating a video about the router may be interesting, let me add this idea to my TODO list 😉
What would you need to do to make 'authenticated content' that shows after the login not disappear after refreshing the site or loading some other components in it's place?
@@TheDevWorldbySergioLema If you refresh the page after the login in your GitHub project, the authenticated content disappears even when the auth_token is stored in local storage. Should it function in that way?
@WorldbySergioLema I'm using google chrome 122.0.6261.94. The auth_token persists between refreshes but the component (auth-content-component) that displays backend response 'first, second' disappears between refreshes and the welcome-component is displayed instead of the auth-content-component one . This also happens on edge. In my understanding when you login and refresh the page unless you logout you should have the access to the auth-conent-component but you don't.
Excelente video!! Tengo una pregunta. Es válido esta arquitectura para un ambiente en producción ? ... He visto otros video tutoriales, y en el Front Angular, se debe configurar un clientId y clientSecret... No es necesario ? o cuál es la diferencia ?
Gracias! Claro, esta configuracion es válida para producción. El uso de un clientId y clientSecret implica una autenticación OAuth2, que es diferente al JWT utilizado en este video. Si quieres más detalles sobre ese tipo de autenticacion, tengo varios vídeos, bit.ly/3KUd6fM
@@TheDevWorldbySergioLema i'm using material design for bootstrap, and it has a basic example modal in it's documentation, where you need to just press a button to open a modal. Here it won't open it just copying it and pasting, as the tutorial says. I downloaded the starter package that comes with Angular 16, and installed just the dependencied that come with it. What can i be doing wrong?
Check the button click is correctly handled (add logs or breakpoints). Then, try to display the modal by default (without any action). This way, you ensure the modal has no error when rendering. If you see any error in the console, it can guide you to the solution.
@@TheDevWorldbySergioLema it shows no errors in the console, and i pasted the code as it is :/ it doesn't use js for back, it's appearance is handled by the library
Hi, I was looking for this, this is great for learning, thank you. I saw in the comments that you were knew to Angular (so am I ~ 3 months in), I would suggest you look into Observables and the RxJS library. Those are great to handle http requests over Promises. (And much more all in all) Moreover, I'm looking to use OAuth2 authentification with JWT. If by any chance you could do a video on it, that would be great. Thank you (+1 sub)
Thank you! Yes, I'm still learning new libraries in Angular, thanks for the sharing. About the OAuth2 authentication, I've made a playlist with some ways to do it with Spring Security: ru-vid.com/group/PLab_if3UBk9-AArufc8CryyhSDVqkNT-U
The CRUD operations are mainly backend. And the routing is mainly a frontend topic. Time ago, i've created two playlists, where I build a complete backend with Spring Boot and a complete frontend with React separatly. Check the backend playlist (ru-vid.com/group/PLab_if3UBk9-TuyqwMy3JvNHeCh7Ll9Wz) and the frontend playlist (ru-vid.com/group/PLab_if3UBk9-O8mjF8JyuK6_4j8G2UxUq). You can find how to create CRUD operations and create a routing strategy in React (sorry, I did nothing yet with Angular).
No, the DTO is the Data Transfer Object, the object which will be converted in JSON and sent to the frontend. The entity is the object mapped to a database table.
With Angular it's better to use HttpClient. This was the first time I've used Angular, so I've used the first library I know. Now that I've worked more with Angular, I prefer HttpClient
Thank you. Now it works. But my UserService in backend giving me error that "Could not autowire. No beans of 'UserMapper' type found." How can I fix this problem?
He hecho un video hace algun tiemo sobre los roles, deberías encontrar todo lo necesario, ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-ZBeyy4Q3nIw.html