Skip to main content

Authorization and Session Management

In this example we will create a simple authorization app with login/sign up scenarios and session management.

ActiveJ doesn't include built-in authorization modules or solutions, as this process may significantly vary depending on the project's business logic. This example represents a simple "best practice" which you can extend and modify depending on your needs. You can find full example sources on GitHub

In the example we will consider only the server which was created using ActiveJ HttpServerLauncher and AsyncServlet. This approach allows to create an embedded application server in about 100 lines of code with no additional XML configurations or third-party dependencies.

Creating Launcher

Let's create an AuthLauncher, which is the main part of the application as it manages the application lifecycle, routing and authorization processes. We will use ActiveJ HttpServerLauncher and extend it:

public final class AuthLauncher extends HttpServerLauncher {
public static final String SESSION_ID = "SESSION_ID";

@Provides
AuthService loginService() {
return new AuthServiceImpl();
}

@Provides
Executor executor() {
return newSingleThreadExecutor();
}

@Provides
IStaticLoader staticLoader(Reactor reactor, Executor executor) {
return IStaticLoader.ofClassPath(reactor, executor, "site/");
}

@Provides
ISessionStore<String> sessionStore(Reactor reactor) {
return InMemorySessionStore.<String>builder(reactor)
.withLifetime(Duration.ofDays(30))
.build();
}

@Provides
AsyncServlet servlet(Reactor reactor, ISessionStore<String> sessionStore,
@Named("public") AsyncServlet publicServlet, @Named("private") AsyncServlet privateServlet) {

return SessionServlet.create(reactor, sessionStore, SESSION_ID, publicServlet, privateServlet);
}

Let's explore the provided objects in more detail:

  • AuthService - authorization and register logic

  • Executor - needed for StaticLoader

  • StaticLoader - loads static content from /site directory

  • SessionStore - handy storage for information about sessions

  • AsyncServlet servlet - the main servlet that combines public and private servlets (for authorized and unauthorized sessions). As you can see, due to DI, this servlet only requires two servlets without their own dependencies

Now let's provide the public and private servlets.

  • AsyncServlet publicServlet - manages unauthorized sessions:
@Provides
@Named("public")
AsyncServlet publicServlet(Reactor reactor, AuthService authService, ISessionStore<String> store, IStaticLoader staticLoader) {
StaticServlet staticServlet = StaticServlet.create(reactor, staticLoader, "errorPage.html");
return RoutingServlet.builder(reactor)
//[START REGION_3]
.with("/", request -> HttpResponse.redirect302("/login").toPromise())
//[END REGION_3]
.with(GET, "/signup", StaticServlet.create(reactor, staticLoader, "signup.html"))
.with(GET, "/login", StaticServlet.create(reactor, staticLoader, "login.html"))
//[START REGION_4]
.with(POST, "/login", request -> request.loadBody()
.then(() -> {
Map<String, String> params = request.getPostParameters();
String username = params.get("username");
String password = params.get("password");
if (authService.authorize(username, password)) {
String sessionId = UUID.randomUUID().toString();

return store.save(sessionId, "My object saved in session")
.then($ -> HttpResponse.redirect302("/members")
.withCookie(HttpCookie.of(SESSION_ID, sessionId))
.toPromise());
}
return staticServlet.serve(request);
}))
//[END REGION_4]
.with(POST, "/signup", request -> request.loadBody()
.then($ -> {
Map<String, String> params = request.getPostParameters();
String username = params.get("username");
String password = params.get("password");

if (username != null && password != null) {
authService.register(username, password);
}
return HttpResponse.redirect302("/login").toPromise();
}))
.build();
}

Let's take a closer look at how we set up routing for servlets. ActiveJ approach resembles Express. For example, here's the request to the homepage for unauthorized users:

.with("/", request -> HttpResponse.redirect302("/login").toPromise())

Method with(@Nullable HttpMethod method, String path, AsyncServlet servlet) of RoutingServlet's builderadds the route to the RoutingServlet

  • method (optional) is one of the HTTP methods (GET, POST, etc.)
  • path is the path on the server
  • servlet defines the logic of request processing. If you need to get some data from the request while processing you can use:
    • request.getPathParameter(String key)/request.getQueryParameter(String key) (see example of query parameter usage) to provide the key of the needed parameter and receive back a corresponding String
    • request.getPostParameters() to get a Map of all request parameters

GET requests with paths "/login" and "/signup" upload the needed HTML pages. POST requests with paths "/login" and "/signup" take care of log in and sign up logic respectively:

.with(POST, "/login", request -> request.loadBody()
.then(() -> {
Map<String, String> params = request.getPostParameters();
String username = params.get("username");
String password = params.get("password");
if (authService.authorize(username, password)) {
String sessionId = UUID.randomUUID().toString();

return store.save(sessionId, "My object saved in session")
.then($ -> HttpResponse.redirect302("/members")
.withCookie(HttpCookie.of(SESSION_ID, sessionId))
.toPromise());
}
return staticServlet.serve(request);
}))

Pay attention at POST "/login" route. serveFirstSuccessful() takes two servlets and waits until one of them finishes processing successfully. So if authorization fails, a Promise of null will be returned (AsyncServlet.NEXT), which means fail. In this case, a simple StaticServlet will be created to load the errorPage. Successful log in will generate a session id for the user and will save string "My saved object in session" to session store. Also it will redirect user to "/members".

Now, let's get to the next servlet that handles authorized sessions.

  • AsyncServlet privateServlet - manages authorized sessions:
@Provides
@Named("private")
AsyncServlet privateServlet(Reactor reactor, IStaticLoader staticLoader) {
return RoutingServlet.builder(reactor)
//[START REGION_6]
.with("/", request -> HttpResponse.redirect302("/members").toPromise())
//[END REGION_6]
//[START REGION_7]
.with("/members/*", RoutingServlet.builder(reactor)
.with(GET, "/", StaticServlet.create(reactor, staticLoader, "index.html"))
//[START REGION_8]
.with(GET, "/cookie", request ->
HttpResponse.ok200()
.withBody(wrapUtf8(request.getAttachment(String.class)))
.toPromise())
//[END REGION_8]
.with(POST, "/logout", request ->
HttpResponse.redirect302("/")
.withCookie(HttpCookie.builder(SESSION_ID)
.withPath("/")
.withMaxAge(Duration.ZERO)
.build())
.toPromise())
.build())
.build();
//[END REGION_7]
}

First, it redirects requests from homepage to "/members":

.with("/", request -> HttpResponse.redirect302("/members").toPromise())

Next, it takes care of all of the requests that go after "/members" path:

.with("/members/*", RoutingServlet.builder(reactor)
.with(GET, "/", StaticServlet.create(reactor, staticLoader, "index.html"))
//[START REGION_8]
.with(GET, "/cookie", request ->
HttpResponse.ok200()
.withBody(wrapUtf8(request.getAttachment(String.class)))
.toPromise())
//[END REGION_8]
.with(POST, "/logout", request ->
HttpResponse.redirect302("/")
.withCookie(HttpCookie.builder(SESSION_ID)
.withPath("/")
.withMaxAge(Duration.ZERO)
.build())
.toPromise())
.build())
.build();

Pay attention to the path "/members/*". * is a variable for the next part of the path. It states that this servlet will process any path segment that goes after "/members/". For example, this route:

.with(GET, "/cookie", request ->
HttpResponse.ok200()
.withBody(wrapUtf8(request.getAttachment(String.class)))
.toPromise())

is a GET request for "/members/cookie" path. This request shows all cookies stored in the session.

caution

A request can have an attachment map where any content can be mapped to some type, i.e. String. By default, requests have no attachments. In this case, the request contains 'cookies' as an attachment that's mapped to the String type.

"/members/logout" logs the user out, deletes all cookies related to this session and redirects the user to the homepage.

After public and private servlets are set up, we define main() method, which will start our launcher:

public static void main(String[] args) throws Exception {
AuthLauncher launcher = new AuthLauncher();
launcher.launch(args);
}

Running the application

If you want to run the example, clone ActiveJ and import it as a Maven project. Check out branch v6.0-beta2. Before running the example, build the project (Ctrl + F9 for IntelliJ IDEA).

Open AuthLauncher class and run its main() method. Then open your favorite browser and go to localhost:8080. Try to sign up and then log in. When logged in, check out your saved cookies for session. You will see the following content: My saved object in session. Finally, try to log out. You can also try to log in with an invalid login or password.