Authentication and Authorization Using JWT on Quarkus

A few weeks ago I interested to try Quarkus, actually 1.0 was released last November, but I didn’t have much free time to try. Right now I have pretty much free time because of the rona. I want to share my experience on how to secure your http API in Quarkus using JWT, because I think it’s important feature. For comparison with Spring Webflux, you can see my story here, for Spring Webmvc see my repo here.

JWT on Quarkus is more simple than Spring, because it’s an official feature.

1. Setup Project

Go to https://code.quarkus.io/ select at least this 2 package dependency.

2. Create Public and Private Key

For unix-like OS you can run this command on terminal, for private key

openssl req -newkey rsa:2048 -new -nodes -keyout privatekey.pem -out csr.pem

for public key

openssl rsa -in privatekey.pem -pubout > publickey.pem

then, copy privatekey.pem and publickey.pem to resource folder (src/main/resources).

3. Config Project

Add some config to application.properties.

mp.jwt.verify.publickey.location=publickey.pem
mp.jwt.verify.issuer=https://ard333.com
quarkus.smallrye-jwt.enabled=true
# for jwt expiration duration
com.ard333.quarkusjwt.jwt.duration=3600

4. TokenUtils

Next, create TokenUtils class for generating token.

TokenUtils.java

5. Model

Next, create some User POJO and some other DTO.

User.java
other DTO

6. 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.

# for user's password simulation
com.ard333.quarkusjwt.password.secret=mysecret
com.ard333.quarkusjwt.password.iteration=33
com.ard333.quarkusjwt.password.keylength=256
PBKDF2Encoder.java

7. http API

Next, create endpoint for login (generate token), don’t forget @PermitAll for login endpoint.

AuthenticationREST.java

And this is for 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