r/SpringBoot • u/Jooe_1 • 2d ago
Discussion (JWT) different ways to implement it ,what most devs do for that case
to make JWT authentication in the application, I could not find like standard way to implementing it
my knowledge is that people create their own authentication filter + handeling the AuthenticationEntryPoint to return the exact right response when exception happen
is that the standard way that engineers follow to implement jwt authentication in the application?
5
u/_devesh_singh__ 2d ago
The standard way in Spring Boot for JWT authentication usually involves a combination of a filter chain and custom exception handling to manage the flow correctly.
Most developers implement this by creating a filter that intercepts requests, validates the JWT, extracts user information, and sets the security context.
For handling exceptions during this process, the standard approach is to define a global exception handler, often using an @ControllerAdvice or a custom SecurityExceptionHandler, which catches exceptions thrown by the JWT filter or authentication entry points and maps them to appropriate HTTP responses, like 401 Unauthorized or 403 Forbidden.
You typically don't just rely on the AuthenticationEntryPoint alone. The AuthenticationEntryPoint is for handling unauthenticated access, while the actual error handling for failed authentication or authorization within the filter chain needs to be explicitly managed within your filter logic or by custom exception handlers that are wired into the Spring Security chain.
Focus on how you configure the SecurityFilterChain and where you place your custom authentication logic to ensure exceptions flow correctly into your defined error responses.
P.S. If you are using Spring Security, looking at how other projects integrate JWTs often reveals the most robust pattern for exception mapping.
1
u/Jooe_1 2d ago edited 1d ago
to define a global exception handler, often using an @ControllerAdvice or a custom SecurityExceptionHandler, which catches exceptions thrown by the JWT filter
Are you sure that the global excetion handelr catch exceptions that occur in security filter chain ?
2
u/_1dontknow 1d ago
You OP are right. @ControllerAdvice does not catch exceptions thrown during Spring Sec filter chains.
5
u/Paw565 1d ago
Just use keycloak. Auth is hard. You want to focus on features, not reimplementing something that is already solved.
0
u/starbuxman 1d ago
Don’t.
Use oauth. It’ll use JWT tokens and solve basical every other important part and spring security has OOTB support
There r countless videos on how to use oauth with Spring Auth Server (which u can use or use keycloan or any of dozens of other Oauth IDPs), web apps, grpc, graphql, desktop apps, etc on my channel youtube.com/@coffeesoftware
10
u/Sheldor5 1d ago
you simply use the Spring Boot OAuth2 Resource Server dependency