[erlang-questions] HTTPS and Basic Authentication with Erlang

Vance Shipley vances@REDACTED
Thu Feb 16 05:47:54 CET 2017

On Wed, Feb 15, 2017 at 12:41 PM, Kenneth Lakin <kennethlakin@REDACTED> wrote:
> On 02/14/2017 09:00 PM, David Wright wrote:
>> I am after an Erlang only example or is using a framework (http server)
>> like cowboy the only way?
> You can serve HTTP over SSL/TLS with erlang's httpd module:
> Erlang/OTP 19 [erts-8.2] [source] [smp:2:2] [ds:2:2:10]
> [async-threads:10] [hipe] [kernel-poll:true]
> Eshell V8.2  (abort with ^G)
> 1> application:ensure_all_started(inets).
>  {ok,[inets]}
> 2> inets:start(httpd, [{port, 8443}, {server_root, "."}, {server_name,
> "localhost"}, {document_root, "."}, {socket_type, {essl, [{certfile,
> "server.pem"}]}}]).
> {ok,<0.77.0>}

Building on that here's how to use mnesia with mod_auth for Basic

$ erl -mnesia dir db
1> mnesia:create_schema([node()]).
2> mnesia:start().
3> rr(code:lib_dir(inets, src) ++ "/http_server/mod_auth.hrl").
4> mnesia:create_table(httpd_user, [{type, bag}, {disc_copies,
[node()]}, {attributes, record_info(fields, httpd_user)}]).
5> mnesia:create_table(httpd_group, [{type, bag}, {disc_copies,
[node()]}, {attributes, record_info(fields, httpd_group)}]).
6> inets:start().
7> Mandatory = [{port, 8080}, {server_root, "/Users/vances"},
{server_name, "rest"}, {document_root, "/Users/vances"}].
8> Auth = [{directory, {"/", [{auth_type, mnesia}, {require_group, ["api"]}]}}].
9> inets:start(httpd, Mandatory ++ Auth).
11> mod_auth:add_user("client", "secret", [], 8080, "/").
12> mod_auth:add_group_member("api", "client", 8080, "/").

$ curl -u client:secret --head http://localhost:8080/index.html
HTTP/1.1 200 OK
Date: Thu, 16 Feb 2017 04:37:58 GMT
Server: inets/6.3.4
Content-Type: text/html
Content-Length: 471

Writing your own callback module for use with inets is simple enough.
You must include it in the list of modules to be used by httpd with
the {modules, Modules]} property. The basic idea is that each module
will be called in sequence to process the request. Your module may do
nothing with some requests or it may return a response. In either
event you return {proceed, NewData} so that the rest of the modules
may do their part. For a REST application you might add a mod_rest
callback module to the list which handles the API resources but let
the mod_get module handle file resources, mod_auth handle
authentication, mod_alias handle rewriting paths, etc..


More information about the erlang-questions mailing list