How does Authentication work in Vert.x?

Java Conceptuel Diagram

About

This page is about authentication in Vertx

How does it work?

In Vertx Web, you add a handler (called an authentication handler) that will add a user to the routing context upon successful authentication.

User user = routingContext.user();
if(user !=null ){
  // authenticated
} else {
  // non-authenticated
}

Handler

An auth handler sets or not the user in the routing context.

They requires a SessionHandler to be on the routing chain before it.

The whole implementation is in the handle function.

If you want to create your handler, just extend it.

What does does it do? It checks:

  • that the user is null (ie not yet authenticated)
User user = ctx.user();
  • if this is the case, it calls the AuthenticationHandlerImpl#parseCredentials to extract the credentials
JsonObject authInfo = new JsonObject()
  .put("username", "tim")
  .put("password", "mypassword");
  • and call the authenticationProvider
authenticationProvider.authenticate(authInfo)
  .onSuccess(user -> {
    System.out.println("User " + user.principal() + " is now authenticated");
  })
  .onFailure(Throwable::printStackTrace);

Method

Oauth

See multi-tenant with google and github

Form

Redirect and FormLoginHandlerImpl

PropertyFileAuthorization

Simple auth service which uses a properties file to gets user/password/role information

Known also under the old name:

Java example:

// import io.vertx.ext.auth.properties.PropertyFileAuthentication;
PropertyFileAuthorization authorizationProvider = PropertyFileAuthorization.create(vertx, "vertx-users.properties");

Syntax of the properties file:

user.{username}={password},{roleName1},{roleName2},…​,{roleNameN}
role.{roleName}={permissionName1},{permissionName2},…​,{permissionNameN}

Example:

user.tim = mypassword,administrator,developer
user.bob = hispassword,developer
user.joe = anotherpassword,manager
role.administrator=*
role.manager=play_golf,say_buzzwords
role.developer=do_actual_work

Example

Snippets

// The authenticated user, or null if the current user is not authenticated.
User user = routingContext.user();

// Set
routingContext.setUser(user)

// Create a user
// https://vertx.io/docs/apidocs/io/vertx/ext/auth/User.html#create-io.vertx.core.json.JsonObject-
User.create(principalJsonObject)

// Delete
routingContext.clearUser()

// Snippet
cerdential = new UsernamePasswordCredentials(username, password)

Documentation







Share this page:
Follow us:
Task Runner