Respeto a la vida

 Todos tenemos distintos puntos de vista, creemos, no creemos, pero, incluso si fuese ateo, para mi la vida se respeta. Un niño es una historia, un pueblo detrás de él, una salvación para el mundo.

Comparto con ustedes amigos lectores, estas 2 bellas oraciones dadas por sus autores para el Respeto a la vida:






Confío en las mujeres de este mundo. Son ellas las únicas que pueden evitar embarazos no planeados o matar al niño que llevan en sus vientres. Fuerza chicas y sigamos orando para que haya más mujeres valientes que defiendan la vida. Dios provee.


Joe

Share:

Connecting our client project using Microprofile JWT

 

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.


The above assumes we have a persistence unit named "concentrador_pu" defined in the persistence.xml file:



If you have read our previous article you will recognize the jdbc/ecommerce that was created to be able to connect to our database in PostgreSQL.

The transaction strategy to use is:

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














Share:

Conectando nuestro proyecto cliente usando Microprofile JWT

 


En el articulo anterior de como Crear Tokens con Microprofile JWT y JDBC Realm, nosotros conseguimos tener un proyecto que nos provea de tokens para nuestros usuarios y roles de nuestra BD. 

Quedo pendiente crear un cliente que utilice estos tokens y permita hacer uso de las APIS que exponga este cliente. 



Proyecto Cliente


Este es un tipico proyecto JakartaEE con Microprofile 3.2. En esta oportunidad el proyecto usará DeltaSpike que en el mundo Spring vendría a ser como tu Spring Data, Nimbus Jose JWT para trabajar con Json Web Tokens (JWT), Microprofile Extension para Open API, finalmente Jakarta XML Binding



DeltaSpike


Este es un módulo usado para simplificar la implementación del patrón repository. Es muy similar a Spring Data. Para consultar una base de datos, nosotros necesitamos definir una declaración de método sin implementación con @Query. La implementación será realizada para nosotros por la extensión CDI. 

El módulo requiere un EntityManager para ser inyectado por CDI. Para conseguir esto usamos un productor CDI. 



Lo anterior asume que tenemos una unidad de persistencia con nombre "concentrador_pu" definido en el archivo persistence.xml:



Si han leido nuestro anterior articulo reconoceran el jdbc/ecommerce que se creo para poder conectarnos a nuestra BD en PostgreSQL.

La estrategia de transacción a utilizar es: 


Existen 4 estrategias:

  • BeanManagedUserTransactionStrategy
  • ResourceLocalTransactionStrategy
  • ContainerManagedTransactionStrategy
  • EnvironmentAwareTransactionStrategy


Todas implementan org.apache.deltaspike.jpa.spi.transaction.TransactionStrategy. Como yo voy a usar JTA tengo que habilitar una estrategia como BeanManagedUserTransactionStrategy en el archivo beans.xml acorde a la información en https://deltaspike.apache.org/documentation/jpa.html.


Existe tambien el apache-deltaspike.properties donde tambien estableceremos la misma estrategia:



El resultado final es:



Implementando Repositorio


Con lo anterior ya podemos implementar el patrón repository. Les parece conocida esta implementación?





Cors Filter


Como nuestros API Rest serán consumidos por una aplicación SPA hecha con angular o móvil hecha con Flutter, vamos a definir un cors filter.





Controladoras


Ahora toca el momento de definir nuestras controladoras.



Cómo se puede apreciar para que podamos ejecutar el método login, se necesita estar autenticado

y tener o el rol USUARIO o el rol ADMIN.


@POST
@RolesAllowed({ RolesEnum.Constants.ADMIN_VALUE,
RolesEnum.Constants.USUARIO_VALUE})


Microprofile JWT


Microprofile nos permite hacer la validación anterior de una forma muy simple. Para eso necesitamos 2 cosas:

1. En el archivo payara-mp-jwt.properties colocar el accepted.issuer :



2. Colocar la llave pública que permitirá validar los tokens JWT generados por el proyecto microprofile-jwt-provider que vimos en el artículo anterior.



Postman

Para poder probar nuestra API, tenemos primero que obtener un token con el proyecto proveedor de tokens JWT visto en el primer artículo


Declaramos ese token en la sección Authorization - Type: Bearer Token:



Ya con esa configuración podemos probar el API - Login sin problemas:




Y de esta manera hemos demostrado el uso de Microprofile JWT con JakartaEE para tener nuestras APIs de una forma minimalista.

Enjoy!


Joe





Share:

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: