Authorization

Authorizing a client connection to a server can be achieved at two levels:

  1. Http request validation
  2. Websocket message challenge

Http request validation

A user may pass a function with one parameter to the Server Options authfunction.

The parameter is of type RequestDetails and the function must return Bool.

SimpleWebsockets.RequestDetailsType
(headers, queries, basicauth)

Provides:

  • headers::NamedTuple All request headers
  • queries::NamedTuple All request query parameters
  • basicauth::Function returns NamedTuple(username, password) if found, or nothing

basicauth will first look for basicauth details in the headers, then the parameters, returning the first one found or nothing

Optionally, basicauth can be passed two parameters:

basicauth([usernamekey::String, passwordkey::String])

which define which query parameters to look up. Defaults to ("username","password").

Example:

function authfunction(details::RequestDetails)
    headers = details.headers
    queries = details.queries
    auth = details.basicauth()

    auth !== nothing && return auth.username === username && auth.password === password
    return false 
end
source

Websocket message challenge

A user may allow all clients to connect, and then allow challenge verification over websocket.

To this end, the Websocket Connection has a validation key, which contains Dict{String, Any}.

By default, validation is:

(
    "valid" => true
)

Setting validation["valid"] = false will deny the connection participation in emit and broadcast methods, but allow the server to send and receive messages to it.

Example

using SimpleWebsockets
server = WebsocketServer()
supersecret = "supersecret"

listen(server, :client) do client::WebsocketConnection
    client.validation["valid"] = false
    send(client, "Awaiting supersecret")
    listen(client, :message) do message
        if(!client.validation["valid"])
            message === supersecret && (client.validation["valid"] = true)
            !client.validation["valid"] && close(client, 1000, "Not authorized")
        end
    end
end

serve(server)