In the previous article on how to Create Tokens with Microprofile JWT and JDBC Realm, we managed to have a project that provides us with tokens for our users and roles in our database.
It was pending to create a client that uses these tokens and allows them to make use of the APIs that this client exposes.
Source Code: https://github.com/joedayz/fps-ws-ecommerce
Client Project
This is a typical JakartaEE project with Microprofile 3.2. This time, the project will use DeltaSpike, which in the Spring world would be like your Spring Data, Nimbus Jose JWT to work with JSON Web Tokens (JWT), Microprofile Extension for Open API, finally Jakarta XML Binding.
DeltaSpike
This is a module used to simplify the implementation of the repository pattern. It is very similar to Spring Data. To query a database, we need to define a method declaration without implementation with @Query. The implementation will be done for us by the CDI extension.
The module requires an EntityManager to be injected by CDI. To achieve this we use a CDI producer.
There are 4 strategies:
- BeanManagedUserTransactionStrategy
- ResourceLocalTransactionStrategy
- ContainerManagedTransactionStrategy
- EnvironmentAwareTransactionStrategy
They all implement org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy. Since I am going to use JTA I have to enable a strategy like BeanManagedUserTransactionStrategy in the beans.xml file according to the information in https://deltaspike.apache.org/documentation/jpa.html.
There is also the apache-deltaspike.properties where we will also establish the same strategy:
The end result is:
Implementing Repository
With the above, we can now implement the repository pattern. Does this implementation seem familiar to you?
Cors Filter
As our Rest APIs will be consumed by a SPA application made with angular or mobile made with Flutter, we are going to define a cors filter.
Controllers
Now is the time to define our controllers.
How can you see so that we can execute the login method, you need to be authenticated and have either the USER role or the ADMIN role.
@POST
@RolesAllowed({ RolesEnum.Constants.ADMIN_VALUE,
RolesEnum.Constants.USUARIO_VALUE})
Microprofile JWT
Microprofile allows us to do the previous validation in a very simple way. For that we need 2 things:
1. In the payara-mp-jwt.properties file place the accepted.issuer:
2. Place the public key that will allow validating the JWT tokens generated by the microprofile-jwt-provider project that we saw in the previous article.
Postman
In order to test our API, we first have to obtain a token with the JWT token provider project seen in the first article.
We declare that token in the section Authorization - Type: Bearer Token:
With that configuration we can test the API - Login without problems:
And in this way, we have demonstrated the use of Microprofile JWT with JakartaEE to have our APIs in a minimalist way.
Enjoy!
Joe
0 comentarios:
Publicar un comentario