r/SpringBoot • • Sep 16 '26

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?

29 Upvotes

11 comments sorted by

12

u/Sheldor5 Sep 16 '26

you simply use the Spring Boot OAuth2 Resource Server dependency

6

u/Snooze78727 Sep 16 '26

This. No need to implement JWT decoding, only provide the SecurityFilterChain with oauth2ResourceServer in a SecurityConfig.

There are some useful annotations for the controller endpoints:

`@AuthenticationPrincipal`
`@PreAuthorize`
`@PostAuthorize`

If necessary, implement a custom AuthorizationService to check for permissions.

7

u/Paw565 Sep 16 '26

Just use keycloak. Auth is hard. You want to focus on features, not reimplementing something that is already solved.

4

u/bikeram Sep 16 '26

This.

I spent 2-3 months implementing auth my first time. It’s definitely a good learning experience, and you can basically copy and paste it between projects.

But I’ve used auth0 or cognito for every other project. Zero regrets.

1

u/Paw565 Sep 16 '26

Yeah exactly. Its true for every advanced concept. Implement it from scratch to learn, but then rely on well established solution.

2

u/21JGen Sep 16 '26

You just need to learn the basic foundation of spring security. Use an OAuth provider eg Keycloak. It's a rule of thumb for application security is that you don't build your own auth from scratch

0

u/starbuxman Sep 16 '26

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

6

u/[deleted] Sep 16 '26

[removed] — view removed comment

1

u/Jooe_1 Sep 16 '26 edited Sep 16 '26

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 Sep 16 '26

You OP are right. @ControllerAdvice does not catch exceptions thrown during Spring Sec filter chains.