,

Securing Your Fullstack Angular-Spring Boot Application with JWT Authentication

Posted by





Secure Your Fullstack Angular – Spring Boot Application With the JWT Authentication

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

  1. Create an Angular login page where users can enter their credentials.
  2. Send the user’s credentials to the server-side API endpoint.
  3. On the server-side, authenticate the user’s credentials using Spring Security.
  4. If the credentials are valid, generate a JWT token using a library like io.jsonwebtoken in Spring Boot.
  5. Send the JWT token back to the client.
  6. On the client-side, store the token securely (e.g., in local storage or session storage).
  7. For every subsequent request, include the JWT token in the request header.
  8. 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.

0 0 votes
Article Rating
21 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
sionex
1 year ago

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!

Avishek Das
1 year ago

Absolute quantity content❤ lots of love from India❤❤❤

Łukasz Kiepas
1 year ago

thanks a lot men : )

Hanine zayani
1 year ago

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

B1010 Code
1 year ago

So good ! , Brazilian country peoples send to you, Thank's So Much !!!

Conor Macdonald
1 year ago

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

William
1 year ago

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

CrafterXD
1 year ago

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…)

Kamil Musiałowski
1 year ago

Man, exactly what i needed to start my graduation project. Thank you so much!

Maciej Demucha
1 year ago

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?

Dimosthenis Karampinas
1 year ago

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!

Missael Espinoza
1 year ago

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.

Ruwan Chathuranga
1 year ago

Great tutorial! 👍
Thanks a lot for the video. 👏
Please do a follow up video for this with the role based authorisation with JWT. 🙏

Ali
Ali
1 year ago

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

Ahmet Talha Köylü
1 year ago

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.

HelloWorld
1 year ago

CORS issue brought me here…. you are awsome! Keep doing

Deadweight
1 year ago

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.

ジャサ자사
1 year ago

Instead of downloading bootstrap packages u could have added bootstrap cdn right?

Elian Holguín
1 year ago

why is the url of the backend and frontend different?

Chia Sẻ Lập Trình
1 year ago

The constructor CorsFilter(UrlBasedCorsConfigurationSource) is undefined…. I see this error when i config WebConfig