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…

pom.xml

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.

Role.java

Next, create User POJO that implementing UserDetails

User.java

AuthRequest and AuthResponse for login endpoint

AuthRequest.java
AuthResponse.java

and Message for example on resource.

3. Password Encoder

springbootwebfluxjjwt.password.encoder.secret=mysecret
springbootwebfluxjjwt.password.encoder.iteration=33
springbootwebfluxjjwt.password.encoder.keylength=256
PBKDF2Encoder.java

4. User Service

UserService.java

5. JWT Util

springbootwebfluxjjwt.jjwt.secret=ThisIsSecretForJWTHS512SignatureAlgorithmThatMUSTHave64ByteLength
springbootwebfluxjjwt.jjwt.expiration=28800
JWTUtil.java

6. Security Configuration

AuthenticationManager.java

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

SecurityContextRepository.java

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.

WebSecurtyConfig.java

and an optional class for CORS.

CORSFilter.java

7. http API

AuthenticationREST.java

and example secured endpoint.

ResourceREST.java

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