Basic Auth with Javalin

Introduction

When running anything online it is important to have DDoS protection and authentication. Cloudflare gives the former and for the latter I recently piggy backed on basic auth to avoid having to build a complete login/signup flow - the browser does the prompt itself.

Auth is a middleware

I was using Javalin to build out the http service layer and it makes adding auth as a middleware really easy. Using a before block allows us to run authentication before the actual route logic is executed. It also allows adding user details [such as premium or free user] in the header/context for downstream logic - where downstream logic can be on the same machine or multiple.

Basic auth works by sending back a specific header + status code back to indicate to the browser to show the login prompt. Following shows the header ‘WWW-Authenticate’ being set to ‘Basic realm=”User Visible Realm”, charset=”UTF-8”‘ + a 401 response code.

1
2
3
4
5
6
7
8
app.before("/protected/*") {
// it [the lambda parameter] is the routing context here
if (!it.basicAuthCredentialsExist()) {
it.header("WWW-Authenticate", "Basic realm=\"User Visible Realm\", charset=\"UTF-8\"")
throw HttpResponseException(401, "Login required")
}
// validate the credentials
}

If the credentials do exist we authenticate them and fail the request if they are invalid. Most http libraries provide methods that return the parsed username and password from the raw base64 input string.

Conclusion

If the credentials can be kept in a file all of this logic can be moved to nginx as well with its auth_basic and auth_basic_user_file directives but then can’t add any header/context details for downstream logic.