Creating Tokens with Microprofile JWT and JDBC Realm

 


In these last months of the year, I have started with my team to work with Micprofile, Payara, JakartaEE and the truth everything is more minimalist and works very well.


As I needed a project that provides me with tokens with the above mentioned, I checked the great article by Victor Orozco (@tuxtor) https://vorozco.com/blog/2019/2019-10-02-MicroProfile-JWT-Token-Provider- Servlet.html to not start from scratch and use JDBC Realm.


Source code: https://github.com/joedayz/microjwt-provider


Requirements

1. Have a Payara Server installed. I'm going to use the Payara Server that Jelastic provides us as PAAS, but, you can download and install the payara on your machine.

2. Java 8+ that you can download from https://adoptopenjdk.net/

3. Check and Follow Victor's article to create the private key and public key.



4. Add some dependencies for Logging. Very necessary if problems arise.




Steps to work with a JDBC Realm

1. Add a web.xml and configure the realm, plus the roles that we are going to use.




The location of the web.xml is in the webapp folder:



2. In the glassfish-web.xml file we also add the roles that we are going to use:



Configuring Logging to the project


1. Create a LoggerProducer to be able to later inject the Logger where we need it.



2. Where you need to Logging, you just inject the Logger:



Generating the Token

1. The project is going to look a lot like the original, I have only changed the TokenProviderResource class to use the jdbc realm in this way:


2. A BaseResponse to notify the clients of this service if there was Success or not with a personalized structure.



Creating the Realm on Payara Server

1. Before creating a Realm we have to have the connection to the DB ready. For that, we are going to create a JDBC Connection Pool for Postgres.





The 2 tables are as shown below:





2. Then we create the JDBC Resource






3. Finally, we go to Configurations -> server-config -> Security -> Realms to create the JDBC Realm:






4.  Creamos el JDBC Realm con estos datos:




Realm Name: ecommerce  (Usado en la linea 9 del web.xml)
Class Name: com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm

JAAS Context: jdbcRealm
JNDI:  jdbc/ecommerce  (JDBC Resource)
User Table: usuario
User Name Column: correo
Password Column: contrasenia
Group Table: usuario_role
Group Table User Name Column:  correo
Group Name Column: role_id
Digest Algorithm: SHA-256
Encoding: Hex
Charset: UTF-8


Testing with Postman


1. We test with Postman and voila


What happens after this?


In the next article, we will use a project that can use these generated tokens and we will have the complete figure for our backend that can be used by SPA applications made with Angular or mobile applications such as Android, IOS, Flutter, etc.


Enjoy!

Joe






Share:

0 comentarios:

Publicar un comentario