Authentication and Authorization Using JWT on Quarkus

Ardiansyah
3 min readApr 14, 2020

--

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.

  1. RESTEasy JSON-B
  2. SmallRye JWT

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 resources 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 a token.

TokenUtils.java

5. Model

Next, create a User POJO and some DTOs.

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

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.

--

--