segunda-feira, 30 de dezembro de 2019

Microblog application using Quarkus and template (Qute)



Quarkus 1.1 was released and in the announcement surprisingly a new template extension was mentioned: Qute. Qute was made for Quarkus: it works in dev mode and you can compile to native image using Graal. In this post I will share the application I created to test the template engine.


How Qute works with Quarkus?


Qute works like very other Quarkus extension: convention over configuration and simple setup. It has support for custom tags and the template language is very simple.
You can place templates in resource/templates and then inject them in your code. So if you have:

src/main/resources/templates/productTemplate.html

You can inject it using:

@Inject
io.quarkus.qute.Template productTemplate;

Later you can create instances from this template passing variables and return them in JAX-RS methods. Yes, you can use JAX-RS as controller:
 
    @GET
    @Produces(MediaType.TEXT_HTML)
    public TemplateInstance getProductsHtml() {
        return postsTemplate.data("products", products);
    }

And it is not only about HTML, take a look at Qute guide for more information.


The microblog example


We want to create a page where you can make quick posts, for this a single entity Micropost which will be handled by MicropostResource and rendered by postsTemplate.html. 

Micropost is a Panache entity, which makes very easier to access databases;
MicropostResource is a JAX-RS resource and makes use of Qute templates
postsTemplate.html is a simple HTML file that prints a list of posts

Everything is put together by index.html. See the sources below:

Next steps


The application can evolve to add more quarkus extension and learn more (validation, security, more CRUD operations and so on), but for me it was enough to see Qute in action. For it was a great step towards making microfrontends easier to implement using Quarkus.

The code is on my github.





sexta-feira, 27 de dezembro de 2019

Quarkus Application with Form Authentication using Database



Let's create a simple Quarkus application that uses databases table for authorization and authentication. This tutorial uses MariaDB and Quarkus 1.1.0.Final.

Database configuration


Remember to NEVER store plain text in the database. Elytron has the tools to use bcrypt for password encryption as described in the Quarkus JDBC security guide.


We need to configure the database tables where the user, password and roles will be stored. Let's create the tables in the database:

* User table keeps the username and password;
* Roles is where you can find all the system roles;
* User_role is user mapping to their roles

Which translated to the following SQL:

create table user(id int primary key, 
                            username varchar(100) unique, 
                            password varchar(1000));

create table role(id int primary key, name varchar(100));

create table user_role(user_id int references user(id), 
                                    role_id int references role(id), 
                                    primary key (user_id, role_id));


Create a database with the tables above and it will allow us to retrieve user information from the database.

Create Quarkus application

Generating an application

Go to code.quarkus.io, fill groupId, artifactId and version, then select the extension JDBC Driver - MariaDB* and Elytron Security JDBC Realm. Download the application, unzip it and import in the IDE you want. I will use VSCode with Quarkus extension and Java tooling.

* Change the JDBC driver according to the database you are using.


Application configuration


We need to configure at least 3 things:

* Datasource that connects to the database;
* Specific security JBDC configuration;
* Permissions

It translates to the following in application.properties:

### 1 - DATASOURCE CONFIGURATION ###
quarkus.datasource.url=jdbc:mysql://localhost:3306/quarkus_form_example
quarkus.datasource.driver=org.mariadb.jdbc.Driver
quarkus.datasource.username=root

### 2 - SECURITY CONFIGURATION ###
quarkus.http.auth.form.enabled=true
quarkus.security.jdbc.enabled=true
quarkus.security.jdbc.principal-query.sql=select... see below
quarkus.security.jdbc.principal-query.clear-password-mapper.enabled=true
quarkus.security.jdbc.principal-query.clear-password-mapper.password-index=1
quarkus.security.jdbc.principal-query.attribute-mappings.0.index=2
quarkus.security.jdbc.principal-query.attribute-mappings.0.to=groups

### 3 - SECURITY URIS MAPPING ###
quarkus.http.auth.permission.permit1.paths=/secured/*
quarkus.http.auth.permission.permit1.policy=authenticated


The value for property quarkus.security.jdbc.principal-query.sql is:

select u.password, r.name from user u, user_role ur,role r where u.id = ur.user_id AND r.id = ur.role_id and u.username = ? group by u.password;

In section one we configure how to connect to a database where all credentials are stored. In 2 the security specific properties for JDBC and we also make sure that it will use form authentication by telling how to retrieve the principal, password and roles from the database (notice the question mark, which is where quarkus will add the username) and finally we may map security policies to URIs. In the example above we just say that content under /secured will only be accessible by logged users. We will add more authorization in the application HTTP endpoints.

Authorization


Let's create a resource specific for manager and user and another one only for manager. In the index page some content will only show  if you are logged as admin or user.

Finally we can focus on the user interface. Let's create very simple pages to show the authorization and authentication in action.

Create pages


See the most import parts of the pages used in our application:

error.html: User is redirected to this page when login fails
login.html: The login page should send the credentials to the authentication endpoint passing the username and the password
secured/index.html: very simple page to show access to a secured static resource
index.html: This is where we show content according to the logged user which makes it a little more complex

Notice the content_public, content_user and content_manager headers in index.html, they are filled by Javascript and for this we use JQuery, see the script tags at the end of index.html.
An interesting method is logout. What we do is simply cancel the session cookie! The other logic in script is to try to retrieve content from the server and change the DOM accordingly.

Finally we are done! Now our index page content changes according to the logged user, see the result:


The source code can be found on my github.

terça-feira, 22 de outubro de 2019

What is the final solution to reuse code in JAX-RS resources?

Back in 2008 I was in college and had to finish my graduation thesis, which was about mashing Web applications. At that time that great news was REST and it was in WAR with SOAP! I came across Roy Fielding famous dissertation, read RESTful Web Services, the book that speed up truly REST APIs (we had data update with GET back then!) in the WEB and then I stated calling myself a RESTAFarian.

Figure 5-3: The client-stateless-server style
"Stateless architectures will never work" - said some SOAP lover 10 years ago 
And I was also a Java programmer! However, back then create REST services for Java was not easy. We had to use servlets and JAX-RS was still in its early days and we already had Restlet! However, JAX-RS was the best solution: annotation based, truly REST language and more. I decided to use Jersey and Spring for my thesis. (the only time I used it, after I felt in love with RESTEasy and have been using it since then).

I liked JAX-RS since 10 years ago I have to repeat code, like check nullable entities and return 404, create entities and build the URI, check if parent resources are found before getting the list of child resources and so on... The basic solution is distribute WebApplicationException throws, then create an exception mapper to create a suitable response when such exception is caught... That's not elegant nor easy to maintain.

Well, at this point, if you came here looking for a solution, well, I don't have it. I mean, I try different approaches, see all these bad ideas I had:


The list would go on, but I want to quickly introduce the new approach I am working one, see this GIST:




The methods from RESTUtils classes allow us to verify a given object and then run some code that will verify a given entity and do other action to build the response. For example, the method checkEntityAndUpdate is useful when you are updating an object, but first you must verify if it is not null (more specifically because PanacheEntity.findById returns null), if it is null 404 is returned, otherwise the consumer propsUpdate can be used to update some of attached object, and this is very important. This is easy to read and helpful, but still we need to repeat some code. With Quarkus and Panache I started an abstract class which was supposed to transform entities operations into suitable HTTP responses, letting us focus on HTTP mapping to our resource methods, but I faced a bug and gave up for now.

The question on this post title remains: What is the final solution to reuse code in JAX-RS resources? What do you use to avoid repeating code? An utility class? A magical framework? Please let me know!




quinta-feira, 19 de setembro de 2019

Hello World, Kogito!

Kogito is what you need to bring business automation to the cloud!

Kogito Quarkus extension allows you to build applications on top of quarkus, bringing native business applications, developer joy and multiple useful extensions that can be used along with Kogito.

Here are some interesting links for you to get started with Kogito:


Kogito Get Started Guide


Kogito Quarkus Extension Guide


Kogito Examples


Kogito Tooling Installation


Kogito + Quarkus on VS Code Tutorial


If you are a video person there's also this:




Wondering about where Kogito came from? Read this blog from Kris.

Happy Coding!