User Login Flow #38
Dynavy
started this conversation in
Show and tell
Replies: 3 comments
|
WOW I like AuthenticationManager layer. Thanks for the info @Dynavy ! 🤙 |
0 replies
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Authentication Flow and JWT Generation in an API
In an authentication application, the flow to authenticate a user and generate a JWT for future requests follows these steps:
Request from the Frontend:
The frontend makes a POST request to the
AuthControllersending theusernameandpasswordas part of the request body. This information is received in the backend as a DTO calledUserLoginRequest.Initial Validation (DTO and BindingResult):
The controller uses the
@Validannotation along withBindingResultto validate theUserLoginRequest. If there are validation errors (e.g., empty fields), a response with a 400 error and an appropriate message is returned. If there are no errors, the flow continues with the user authentication.Authentication in the AuthenticationService:
The
AuthenticationServicehandles the authentication:It creates a
UsernamePasswordAuthenticationTokenusing the providedusernameandpassword.This token is passed to the
AuthenticationManager.The
AuthenticationManageris typically defined as a@Beanin theSecurityConfigor similar configuration class. It already has built-in methods to handle authentication automatically. It uses theUserDetailsServiceImplto query theUserRepositoryand validate the user credentials.If the user is found, the
AuthenticationManagervalidates the password using thepasswordEncoder. If the validation is successful, authentication is considered successful.JWT Generation:
Once authentication is successful, the
JwtServiceis responsible for generating the JWT. It is important to note that tokens should be generated in the respective services and not in the controllers.The
JwtServicecreates the token, signs it with a secret key, and sets an expiration date.This JWT is wrapped in a DTO called
JwtResponse, which organizes the response and contains relevant information such as the token and its validity duration.Response from the Endpoint (AuthController):
Finally, the
AuthControllerreturns theJwtResponseto the frontend. The frontend can store this token (e.g., inlocalStorageor as a cookie) and use it to authenticate future requests to the backend. It is important to mention that backend responses, such as theJwtResponsein this case, should always be returned as JSON to maintain an organized and easy-to-consume structure.Mermaid Diagram:
All reactions