Login against ActiveDirectory, Boss Filter for authentification/authorization

Login against ActiveDirectory, Boss Filter for authentification/authorization.

earlier this year, i had to connect and authenticate an user against Active Directory from erlang,
erlang/OTP have ldap client include since R15,
i tryed to connect to an Active Directory but without success :(, MS, MS, again MS ...
back to my favorite search engine, after googling some time,
i find out that ejabberd from preocess-one,
can connect and authenticate user against ActiveDirectory, WOW :), and it is open-source,
i decided to extract the code and package it here.

in this tutorial, you will find out how to use ChicagoBoss with an external dep,
boss filter for authentification and authorization.

Get started.

i assume you have an Active Directory Server ready somewhere in your network,
and installed ChicagoBoss, mostly you can copy paste to your shell when you see shell code,
this tuto was made against last version of CB, 17 september 2015

cd ChicagoBoss
make
make app PROJECT=ad
cd ../ad

edit your rebar.config file and add eldap repo in the deps section.

{deps, [
  {boss, ".*", {git, "git://github.com/ChicagoBoss/ChicagoBoss.git", {tag, "v0.8.15"}}},
  {eldap, ".*", {git, "git://github.com/mihawk/ldap.git", {tag, "master"}}}
]}.
{deps_dir, ["./deps"]}.
{plugin_dir, ["priv/rebar"]}.
{plugins, [boss_plugin]}.
{eunit_compile_opts, [{src_dirs, ["src/test"]}]}.
{lib_dirs, ["../ChicagoBoss/deps/elixir/lib"]}.
  • fetch and compile our new deps.
cd ad
make all

i had this error during compilation process.

==> lager (compile)
ERROR: /home/mihawk/workspace/ad/deps/lager/.rebar/erlcinfo file version is incompatible. expected: 1 got: 2
ERROR: compile failed while processing /home/mihawk/workspace/ad/deps/lager: rebar_abort

i do this:

find . -name .rebar -type d | xargs rm -fr
make compile

Let's try to connect to ActiveDirectory

./init-dev.sh

oups forget to configure our eldap.
edit boss.config and add the config for eldap.
just like follow, update your config according to your env.

[
{eldap, [
         {default, [         
                    {ldap_servers, ["ldap.MyDomain.com"]},
                    {ldap_encrypt, none},
                    {ldap_port, 389},
                    {ldap_uids, [{"sAMAccountName", "%u"}]},
                    {ldap_base, "CN=Users,DC=MyDomain,DC=com"},
                    {ldap_rootdn, "CN=Administrator,CN=Users,DC=MyDomain,DC=com"},
                    {ldap_password, "MyPassword"},
                    {ldap_filter, "(memberOf=*)"}
                   ]
         }
        ]
 },
{boss, [
    {path, "./deps/boss"},
    {applications, [ad]},
    {assume_locale, "en"},
...

let's try again

./init-dev.sh
(ad@xyz)1> 
(ad@xyz)1>application:start(eldap).
ok
(ad@xyz)2>eldap_api:start().
00:55:36.645 [info] LDAP connection on xxx.xx.xx.xx:389
00:55:36.646 [info] LDAP connection on xxx.xx.xx.xx:389
{ok,<0.86.0>}

test user credential:

(ad@xyz)4> eldap_api:check_password(default, <<"administrator">>, <<"mypass1">>).
true
(ad@xyz)5> eldap_api:check_password(default, <<"administrator">>, <<"mypass2">>).
false

Start eldap at boot.

in CB, we have init folder where you can perform some task at the boot time of your CB app.
let's write what we did previously in the shell into a module.

cat <<EOF > priv/init/ad_02_eldap.erl
-module(ad_02_eldap).
-compile(export_all).

init() ->
    {ok, Pid} = case application:start(eldap) of
                    ok -> 
                        lager:info("starting eldap interface..."),
                        eldap_api:start();
                    Err -> 
                        lager:error("starting eldap interface fail ~p", [Err])
                end,
    {ok, []}.

stop(_) ->
  application:stop(eldap),
  ok.
EOF
./init-dev.sh

if you lunch your app, you application crash miserably, what happen here,
the culprit is lager :(, it's a parse transform,
a parse transform is a hook into the compilation chaine
where the code is transformed before compilation.
the easiest way to fix this, is to add this magic line:

-compile({parse_transform, lager_transform}).

-compile({parse_transform, lager_transform}).
-module(ad_02_eldap).
-compile(export_all).
...

now your app should start properly.

./init-dev.sh
...
13:14:19.947 [info] starting eldap interface...
13:14:19.978 [info] LDAP connection on xxx.xx.xxx.xx:389
13:14:19.978 [info] LDAP connection on xxx.xx.xxx.xx:389
(ad@xyz)1> eldap_api:check_password(default, <<"administrator">>, <<"mypass1">>). 
true
(ad@xyz)2>

cool we can call eldap_api:check_password/3 from our controller :)

Boss filter for authentification/authorization.

i assume you have read the README_FILTERS.md from the boss repo.
from the doc we have:

    -module(my_before_filter).
    -export([before_filter/2]).

    before_filter(_Config, RequestContext) ->
        IsAdmin = is_admin(RequestContext),
        {ok, [{is_admin, IsAdmin}|RequestContext]}.

let's write our own module, which does nothing but just log some information.

cat <<EOF > src/lib/ad_filter.erl
-compile({parse_transform, lager_transform}).
-module(ad_filter).
-export([before_filter/2]).

before_filter(Cfg, ReqCtx) ->
  lager:info("Cfg:~p",[Cfg]),
  lager:info("ReqCtx:~p",[ReqCtx]),
  {ok, ReqCtx}.

EOF

we need a basic page

basic controller:

cat <<EOF > src/controller/ad_index_controller.erl
-module(ad_index_controller,[Req,Sid]).
-export([index/3]).
-default_action(index).

index('GET', [], _ReqCtx) ->
  {ok, [{msg, "Hello World!!"}]}.
EOF

basic view:

mkdir -p src/view/index
cat <<EOF > src/view/index/index.html
<html>
<head></head>
<body>
  {{msg}}
</body>
</html>
EOF

activate your filter, edit your boss.config like below:

%% controller_filter_config - Specify defaults for controller filters
%%   Sub-key 'lang' can be set to the atom 'auto' to autodetermine language
%%     universally, or can be set to a specific language by setting a string (e.g.
%%     "en" or "de")

{controller_filter_modules, [ad_filter]},

%    {controller_filter_config, [
%        {lang, auto}
%    ]},

open an other shell an fetch the page with curl:

curl -XGET http://localhost:8001/index
...

here the corresponding log from the REPL.

13:45:16.444 [info] Cfg:undefined
13:45:16.444 [info] ReqCtx:[{controller_module,ad_index_controller},{request,....},{session_id,"219ec9e933d968b595c2c85e6721a6dab98699ec"},{method,'GET'},{action,"index"},{tokens,[]}]
13:45:16.462 [warning] GET /index [ad] 404 49ms

we see that ReqCtx contain:

  • controller_module
  • request
  • session_id
  • method
  • action
  • token

let's add a login page, and redirect all user who want to access /index/index to the login page.

auth controller:

cat <<EOF > src/controller/ad_auth_controller.erl
-module(ad_auth_controller,[Req,Sid]).
-export([login/3]).
-default_action(login).

login('GET', [], _ReqCtx) ->
  {ok, []};

login('POST', [], _ReqCtx) ->  
  {ok, []}.

EOF

login view:

mkdir -p src/view/auth
cat <<EOF > src/view/auth/login.html
<html>
<head>
<style> center{padding-top:100px;} </style>
</head>
<body>
  <center>
  <form method="post" action="/auth/login">
  <table>
  <tr>
  <td>login:</td>
  <td><input type=text name="login"></td>
  </tr>
  <tr>
  <td>password:</td>
  <td><input type=password name="password"></td>  
  </tr>
  <tr>
  <td>  
   <input type="submit" value="OK">
  </td><td></td>  
  </tr>
  </table>
  </form>
  </center>
</body>
</html>
EOF

let s try our new login page.
open your webrowser an go to the url http://localhost:8001/auth/login,
you should see our login form
or you can get the page using curl like below:

curl -X GET http://localhost:8001/auth/login
<html>
<head>
<style> center{padding-top:100px;} </style>
</head>
<body>
  <center>
  <form method="post" action="/auth/login">
  <table>
  <tr>
  <td>login:</td>
  <td><input type=text name="login"></td>
  </tr>
  <tr>
  <td>password:</td>
  <td><input type=password name="password"></td>  
  </tr>
  <tr>
  <td>  
   <input type="submit" value="OK"> 
  </td><td></td>  
  </tr>
  </table>
  </form>
  </center>
</body>
</html>

we got the page. nice
now let's authenticate our user against Active Directory,
edit the auth controller like follow:


login('POST', [], _ReqCtx) ->

  %% extract value returned by the login form
  Params = Req:post_params(),

  %% extract login and password convert them into binary
  Login = list_to_binary(proplists:get_value("login", Params)),
  Password = list_to_binary(proplists:get_value("login", Params)),

  %% check against active directory
  case eldap_api:check_password(default, Login, Password) of
       true -> 
               %%if user is authentified, link is current session
               boss_session:set_session_data(Sid, user, Login);
               {ok, [{success_msg, "You are authentified"}]};
       false ->
               {ok, [{error_msg, "Not Authorized"}]}
  end.

edit your view and add the error message.

<html>
<head>
<style> center{padding-top:100px;} </style>
</head>
<body>
  <center>
  {% if success_msg %}<p><span style="color:green;">{{success_msg}}</span></p>{% endif %}  
  {% if error_msg %}<p><span style="color:red;">{{error_msg}}</span></p>{% endif %}  
  <form method="post" action="/auth/login">
  <table>
  <tr>
...

let's test with curl

curl -X POST -d "login=admin&password=123123" http://localhost:8001/auth/login
<html>
<head>
<style> center{padding-top:100px;} </style>
</head>
<body>
  <center>  
   
 <p><span style="color:red;">Not Authorized</span></p>  
  <form method="post" action="/auth/login">
  <table>
  <tr>
  <td>login:</td>
  <td><input type="text" name="login"></td>
  </tr>
  <tr>
  <td>password:</td>
  <td><input type="password" name="password"></td>  
  </tr>
  <tr>
  <td>  
   <input type="submit" value="OK">
  </td> 
  </tr>
  </table>
  </form>
  </center>
</body>
</html>

we got the error message "Not Autorized".
let s try with a correct user.

curl -X POST -d "login=administrator&password=mypass1" http://localhost:8001/auth/login
<html>
<head>
<style> center{padding-top:100px;} </style>
</head>
<body>
  <center>  
 <p><span style="color:green;">You are authetified</span></p>  
   
  <form method="post" action="/auth/login">
  <table>
  <tr>
  <td>login:</td>
  <td><input type="text" name="login"></td>
  </tr>
  <tr>
  <td>password:</td>
  <td><input type="password" name="password"></td>  
  </tr>
  <tr>
  <td>  
   <input type="submit" value="OK">
  </td> 
  </tr>
  </table>
  </form>
  </center>
</body>
</html>

we got the success message "You are authentified".
let s go back to our ad_filter module and add the logic
if the user want to see the page index/index he need to be authentified

-compile({parse_transform, lager_transform}).
-module(ad_filter).
-export([before_filter/2]).

before_filter(Cfg, ReqCtx) ->
  %% get the current SessionId
  Sid = proplists:get_value(session_id, ReqCtx),

  %% get the linked user
  User = boss_session:get_session_data(Sid, user),

  %% get the http request method
  Method = proplists:get_value(method, ReqCtx),

  %% get the current controller
  Ctrl = proplists:get_value(controller_module, ReqCtx),

  %% get the current action
  Action = proplists:get_value(action, ReqCtx),

  check_access(ReqCtx, User, Sid, Method, Ctrl, Action).


%% we use pattern matching for access page.

%% if user is not authentified and want to access the index page, we redirect to the login page
check_access(_, undefined, Sid, 'GET', ad_index_controller, "index") -> {redirect, "/auth/login"};

%% if user is identified and want to access index page, the user can acces it.
check_access(ReqCtx, User, Sid, 'GET', ad_index_controller, "index") -> {ok, [{user, User}|ReqCtx]};

%% anonymous user or identified user can access other page
check_access(ReqCtx, undefined, Sid, _Method, _Ctrl, _Action) -> {ok, [{user, "anonymous"}|ReqCtx]};
check_access(ReqCtx,      User, Sid, _Method, _Ctrl, _Action) -> {ok, [{user, User}|ReqCtx]}.

let's edit our index/index page to see which type of user.

-module(ad_index_controller,[Req,Sid]).
-export([index/3]).
-default_action(index).

index('GET', [], ReqCtx) ->
  User = proplists:get_value(user, ReqCtx, "anonymous"),
  {ok, [{msg, "Hello World!!" ++ User}]}.

there is a small glitch here, how to redirect the user after the login page.
i let you image what to do, you have all the information.

thank for reading this long post,
hope you find it interesting.
you can find the code for this post here

mihawk.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容