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. 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
Make sure to add some dependencies to your project. I used 2.5.0.RELEASE for the parent.
- spring-boot-starter-security
- spring-boot-starter-webflux
- jjwt (from io.jsonwebtoken)
- lombok
if you use maven, see code below…
2. Model
First, create an enum
that contains the role that will be used.
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
Next, create your custom password encoder (for user’s password simulation), don’t forget to add some properties for your secret salt on application.properties
.
springbootwebfluxjjwt.password.encoder.secret=mysecret
springbootwebfluxjjwt.password.encoder.iteration=33
springbootwebfluxjjwt.password.encoder.keylength=256
4. User Service
Next, create UserService
, this is just an example, you can load the user from the database (from repository).
5. JWT Util
Next, create JWTUtil
, don’t forget to add some properties for your JWT secret salt and JWT expiration time on application.properties
springbootwebfluxjjwt.jjwt.secret=ThisIsSecretForJWTHS512SignatureAlgorithmThatMUSTHave64ByteLength
springbootwebfluxjjwt.jjwt.expiration=28800
6. Security Configuration
Create AuthenticationManager
that implementing ReactiveAuthenticationManager
for validate token and role.
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
Next, create endpoint for login (create token). You can change the url to /auth
or whatever you want.
and example secured endpoint.
Done 👍, next you can test your http API (e.g. using Postman).
Full source code is available on my Github page.
Are you looking for any 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.