Authentication and Authorization Using JWT on Spring Webflux

Security of the application is very important, especially for your http API. JWT is one of the ways for securing (i.e. do authentication and authorization) your http API.

JSON Web Token (JWT) is a JSON-based open standard (RFC 7519) for creating access tokens that assert some number of claims. [source]

This time, I want to share my experience on how to secure your http API in Spring Webflux using JWT, at least as far as I learned until today, for Spring Webmvc you can see my repo here.

1. Setup Project

  • spring-boot-starter-security
  • spring-boot-starter-webflux
  • jjwt (from io.jsonwebtoken)
  • lombok

if you use maven, see code below…


2. Model

If you use hasRole at @PreAuthorize (at section 7. http API in this article), by default you have to add ROLE_ prefix, see this spring doc for more info.

Next, create User POJO that implementing UserDetails

AuthRequest and AuthResponse for login endpoint

and Message for example on resource.

3. Password Encoder


4. User Service

5. JWT Util


6. Security Configuration

Next, create SecurityContextRepository that implementing ServerSecurityContextRepository for get the token and forward to AuthenticationManager.

Next, create WebSecurityConfig and add EnableWebFluxSecurity and EnableReactiveMethodSecurty annotation, in this component you can configure all your security needs, like authentication manager, security context repository, which url is in permit (in this case /login), etc.

and an optional class for CORS.

7. http API

and example secured endpoint.

Done 👍, next you can test your http API (e.g. using Postman).

Access secured API without token
Login and get Token
Access secured API with token (Key: Authorization, Value: Bearer token)
Access secured API with token, but not allowed roles

Full source code is available on my Github page.

Thanks for reading (Sorry For My Bad English 😅) and feel free to comment.

Are you looking for information about remote work?
or have a cool resource about remote work?
remotework.FYI is all you need to know about remote work, find and share cool resources right now.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store