Skip to content

Instantly share code, notes, and snippets.

@lpgauth
Created September 26, 2012 16:53
Show Gist options
  • Save lpgauth/3789152 to your computer and use it in GitHub Desktop.
Save lpgauth/3789152 to your computer and use it in GitHub Desktop.
basic auth with Cowboy
-module(auth_handler).
-compile({parse_transform, seqbind}).
-export([init/3, handle/2, terminate/2]).
-define(USERNAME, <<"admin">>).
-define(PASSWORD, <<"password">>).
%% public
init(_Transport, Req, []) ->
{ok, Req, undefined}.
handle(Req@, State) ->
{Username, Password, Req@} = credentials(Req@),
{ok, Req@} =
case {Username, Password} of
{?USERNAME, ?PASSWORD} ->
cowboy_http_req:reply(200, [{'Content-Type', <<"text/html">>}], <<"hello world!">>, Req@);
_ ->
unauthorized(Req@)
end,
{ok, Req@, State}.
terminate(_Req, _State) ->
ok.
%% private
credentials(Req@) ->
{AuthorizationHeader, Req@} = cowboy_http_req:header('Authorization', Req@),
case AuthorizationHeader of
undefined ->
{undefined, undefined, Req@};
_ ->
{Username, Password} = credentials_from_header(AuthorizationHeader),
{Username, Password, Req@}
end.
credentials_from_header(AuthorizationHeader) ->
case binary:split(AuthorizationHeader, <<$ >>) of
[<<"Basic">>, EncodedCredentials] ->
decoded_credentials(EncodedCredentials);
_ ->
{undefined, undefined}
end.
decoded_credentials(EncodedCredentials) ->
DecodedCredentials = base64:decode(EncodedCredentials),
case binary:split(DecodedCredentials, <<$:>>) of
[Username, Password] ->
{Username, Password};
_ ->
{undefined, undefined}
end.
unauthorized(Req@) ->
{ok, Req@} = cowboy_http_req:set_resp_header(<<"Www-Authenticate">>, <<"Basic realm=\"Secure Area\"">>, Req@),
{ok, Req@} = cowboy_http_req:set_resp_body(unauthorized_body(), Req@),
cowboy_http_req:reply(401, Req@).
unauthorized_body() ->
<<"
<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"
\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dt\">
<HTML>
<HEAD>
<TITLE>Error</TITLE>
<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=ISO-8859-1\">
</HEAD>
<BODY><H1>401 Unauthorized.</H1></BODY>
</HTML>
">>.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment