Authorization
Authorizing a client connection to a server can be achieved at two levels:
- Http request validation
- 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.RequestDetails — Type(headers, queries, basicauth)Provides:
headers::NamedTupleAll request headersqueries::NamedTupleAll request query parametersbasicauth::Functionreturns NamedTuple(username, password) if found, ornothing
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
endWebsocket 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)