Secure Your Fullstack Angular – Spring Boot Application With the JWT Authentication
In today’s digital world, application security is of utmost importance. As developers, we want to make sure that our application and user data are protected from unauthorized access. One popular approach to secure a full-stack application built with Angular and Spring Boot is by implementing JWT (JSON Web Token) authentication.
What is JWT Authentication?
JSON Web Token (JWT) is an open standard for securely transmitting information between parties as a JSON object. In the context of user authentication, JWT provides a way to generate and validate tokens that can be used to manage user sessions and secure API endpoints.
How does JWT Authentication work?
When a user logs in to your Angular-Spring Boot application, their credentials are verified on the server-side. If the credentials are valid, the server generates a JWT token and sends it back to the client. The client then stores this token and includes it in every subsequent request to the server.
The server validates the token on each request by checking its authenticity and expiration. If the token is valid, the server allows access to the requested resource. If the token is invalid or expired, the server denies access.
Implementation Steps
- Create an Angular login page where users can enter their credentials.
- Send the user’s credentials to the server-side API endpoint.
- On the server-side, authenticate the user’s credentials using Spring Security.
- If the credentials are valid, generate a JWT token using a library like
io.jsonwebtoken
in Spring Boot. - Send the JWT token back to the client.
- On the client-side, store the token securely (e.g., in local storage or session storage).
- For every subsequent request, include the JWT token in the request header.
- On the server-side, validate the token on each request and grant access only to authorized resources.
Benefits of JWT Authentication
Implementing JWT authentication provides several benefits:
- Statelessness: JWT tokens are self-contained and store user authentication information. This eliminates the need for server-side session management, making your application stateless and scalable.
- Secure transmission: JWT tokens are compact and can be easily transmitted over the network. They can also be encrypted for additional security.
- Simple integration: JWT authentication can be seamlessly integrated into your Angular and Spring Boot application without depending on external libraries or services.
- Flexibility: JWT tokens can carry additional user information, such as roles or permissions, which can be used for authorization purposes.
Conclusion
By implementing JWT authentication in your full-stack Angular – Spring Boot application, you can ensure secure communication between the client and server, protecting sensitive user data from unauthorized access. Follow the above-mentioned steps to add an extra layer of security to your application, giving peace of mind to your users.
My Guy you're so underrated. Making a Full User Backend with a GUI in 1h is just insane. I'm gonna recommend you to my friends for sure!
Absolute quantity content❤ lots of love from India❤❤❤
thanks a lot men : )
thnak u for this amazing video , can u make us an other video explaning how to get from the form(login page ) to other pages(home) in our application
So good ! , Brazilian country peoples send to you, Thank's So Much !!!
11:50 ne doit-on pas ajouter <div class="app"> <app-auth-content></app-auth-content></div> dans notre app.component.html pour que ça s'affiche ?
16:00 malgré la connexion de mon frontend a mon backend, la liste contenant "first, second" ne s'affiche pas .. j'ai pourtant suivit le tuto à la lettre
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
first of all extremely nice and informativ video bro! just insane 🔥
but I have a question… (maybe its to late in the evening and my brain is stuck xD)
but when I enable the validateTokenStrongly() for all requests except get-request. I cant register a new user, when there is no auth token in the localstorage, because I get an exception, that the token format is wrong. The exception: com.auth0.jwt.exceptions.JWTDecodeException: The token was expected to have 3 parts, but got 0.
my solution-idea is that I change the register to @PutMapping and only use the validatorToken() method by Put-Mapping requests, but I think thats not the best solution..
have you an idea for that problem? 🤔 (I have researched in the git repo, but I think you must had the same problem…)
Man, exactly what i needed to start my graduation project. Thank you so much!
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?
Excellent tutorial!
Only one note, I was kind of confused when it came to binding form controls with ngModel, because I was used to instantiating a FormGroup in the component and then bind controls using FormControlName. inside the template Found out that the way you show in the video is mainly used when updating legacy Angular projects, and the recommended way for new projects is through Reactive Forms. Hope this made sense! Nice tutorial once again!
Hello Sergio. I am having the following error in my spring boot backend:
"Could not resolve view with name 'api/v1/auth/signup' in servlet with name 'dispatcherServlet'"
This happens when I try to hit my signup endpoint. It works fine for login, but it doesn't for this one. In one of the log lines, I see that it points to my JWT Filter while it does the doFilter method.
In my SecurityConfig, I set all auth endpoints to permitAll():
request.requestMatchers(HttpMethod.POST,AUTH_PATH+"/**").permitAll();
Do you have any idea why it happens? Thanks in advance.
Great tutorial! 👍
Thanks a lot for the video. 👏
Please do a follow up video for this with the role based authorisation with JWT. 🙏
can you please help?
com.project.jwt.exceptions.AppException: Unknown User
at com.project.jwt.services.UserService.lambda$login$0(UserService.java:25) ~[classes/:na]
at java.base/java.util.Optional.orElseThrow(Optional.java:403) ~[na:na]
at com.project.jwt.services.UserService.login(UserService.java:25) ~[classes/:na]
I get this error when i hit /login path using Postman. At this stage , i didn't start on regsiter function. But spring is throwing this error
Hi Sergio,
I just discovered you by seeing your cookie based authentication video. I was wondering something about authentication/authorization. Some resources are warning us about to sending JWT to client side. They say that's not a secure way. One advice they given about this instead of using jwt about authentication, use cookies and session tokens. However, i cannot find a good resource cookie based authentication. There is really good resource that recorded by you. I want to do a simple project for my personal site but I want to pay attention to best practices. Jwt is not secure enough, if the token is captured by a malicious person, we are considered at risk until it is expired. I don't know what to do, there is only JWT content everywhere. Topics like FormLogin, HttpBasic are always related to Spring MVC. I would be very happy if you share your views with me, best wishes.
CORS issue brought me here…. you are awsome! Keep doing
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.
Instead of downloading bootstrap packages u could have added bootstrap cdn right?
why is the url of the backend and frontend different?
The constructor CorsFilter(UrlBasedCorsConfigurationSource) is undefined…. I see this error when i config WebConfig