Skip to main content

Using LDAP for Authentication and Authorization within APEX

One of my current customers would like to use their LDAP (Microsoft Active Directory) server for authentication and authorization of APEX applications. Of course we tried to set up a standard LDAP Authenication that's available within APEX. But we couldn't get that to work. Maybe it has to do with the fact that the client stored their Users within Groups within Groups within .... . Or maybe it doesn't do a full tree walk in the directory. Or maybe it is just because it is Microsoft - and not Oracle Internet Directory (OID). So we moved to a custom Authentication using the DBMS_LDAP functions (and some examples from the Pro Oracle Application Express book and Tim Hall - a.k.a. Oracle Base).

One of the issues we encountered that we wanted to use the user's login name, like "jdoe" and not his full name ("John Doe"). And the login name is stored in the "sAMAccountName" attribute. But authenticating using just "jdoe" didn't work. I don't whether it is particular for this set up, but we had to prefix the username with the domain, like "USERS\jdoe". See the code snippet below:

-- Authenicate the user -- raises an exception on failure
retval := dbms_ldap.simple_bind_s
          ( ld     => l_session 
          , dn     => l_dn_prefix || p_username
          , passwd => p_password ); 

Once authenticated we needed to check whether the user was a member of a particular group. Authorization was done by defining a group in AD containing the string APEX_<APP_ID>, so for instance "Users for APEX_101". So we had to read the AD tree and scan it for the "memberOf" attribute. This attribute contains a string with the complete group information.  Therefore we used the dbms_ldap_search_s function defining a specific filter using the "sAMAccountName" attribute.

-- Get all "memberOf" attributes    
l_attrs(1) := 'memberOf';
-- Searching for the user info using his windows loginname
retval := dbms_ldap.search_s
          ( ld       => l_session 
          , base     => ldap_base 
          , scope    => dbms_ldap.scope_subtree
          , filter   => '(&(objectClass=*)(sAMAccountName='|| p_username || '))'
          , attrs    => l_attrs
          , attronly => 0
          , res      => l_message );

Then  we could scan the results on the existence of the "APEX_101" string.

One additional request was to show the user why his login failed - if it did. By default APEX just returns "Invalid login credentials", but in the case where he is just not authorized (because he is not in the correct "application group"), another message should appear. And there the APEX builtin function apex_util.set_custom_auth_status came to the rescue! Although it has been there for ages - at least since version 3.1 - I had never used it and wasn't aware of it's existence. With this function you can override the standard message on the login screen. So pretty useful stuff.

The next step will be to implement a more fine grained authorization (for read / write) using the same technique. This will be implemented using a (real) Authorization scheme, based on the same code.

So for the interested - and for my own documentation ;-) - the full code is below:

create or replace  
function ldap_auth( p_username in varchar2
                  , p_password in varchar2 )
return boolean
  retval        PLS_INTEGER;
  l_session     dbms_ldap.session;
  l_attrs       dbms_ldap.string_collection;
  l_message     dbms_ldap.message;
  l_entry       dbms_ldap.message;
  l_attr_name   varchar2(256 );
  l_vals        dbms_ldap.string_collection;
  l_ber_element dbms_ldap.ber_element;
  ldap_host     varchar2(256) := '<your LDAP server>';
  ldap_port     varchar2(256) := '389'; -- default port
  ldap_base     varchar2(256) := 'OU=<base OU>,DC=<dc1>,DC=<dc2>,DC=<dc3>';
  l_dn_prefix   varchar2(100) := '<prefix>\'; -- domain, like 'USERS\'
  l_not_authenticated varchar2(100) := 'Incorrect username and/or password';
  l_not_authorized    varchar2(100) := 'Not authorized for this application';
  l_authed      boolean;
  l_memberof    dbms_ldap.string_collection;
  -- Raise exceptions on failure
  dbms_ldap.use_exception := true;
  -- Connect to the LDAP server
  l_session := dbms_ldap.init( hostname =>ldap_host 
                             , portnum  => ldap_port );
  -- Authenicate the user -- raises an exception on failure
  retval := dbms_ldap.SIMPLE_BIND_S( ld     => l_session 
                                   , dn     => l_dn_prefix || p_username
                                   , passwd => p_password ); 
  -- Once you are here you are authenticated
  -- Get all "memberOf" attributes    
  l_attrs(1) := 'memberOf';
  -- Searching for the user info using his samaccount (windows login )
  retval := dbms_ldap.search_s( ld       => l_session 
                              , base     => ldap_base 
                              , scope    => dbms_ldap.SCOPE_SUBTREE
                              , filter   => '(&(objectClass=*)(sAMAccountName=' || p_username || '))'
                              , attrs    => l_attrs
                              , attronly => 0
                              , res      => l_message );
  -- There is only one entry but still have to access that
  l_entry := dbms_ldap.first_entry( ld  => l_session 
                                  , msg => l_message );
  -- Get the first Attribute for the entry
  l_attr_name := dbms_ldap.first_attribute( ld        => l_session
                                          , ldapentry => l_entry       
                                          , ber_elem  => l_ber_element );

  -- Loop through all "memberOf" attributes  
  while l_attr_name is not null loop

    -- Get the values of the attribute
    l_vals := dbms_ldap.get_values( ld        => l_session
                                  , ldapentry => l_entry 
                                  , attr      => l_attr_name );
    -- Check the contents of the value
    for i in l_vals.first..l_vals.last loop
      -- A user gets access to APP 101 when he is assigned to a group where the name contains "APEX_101" 
      l_authed := instr(upper(l_vals(i)), 'APEX_'||v('APP_ID')) > 0 ;
      exit when l_authed;
    end loop;
    exit when l_authed;    

    l_attr_name := dbms_ldap.next_attribute( ld        => l_session
                                           , ldapentry => l_entry       
                                           , ber_elem  => l_ber_element );
  end loop;

  retval := dbms_ldap.unbind_s( ld => l_session );
  if not l_authed
  then -- Although username / password was correct, user isn't authorized for this application
    apex_util.set_custom_auth_status ( p_status => l_not_authorized );
  end if;  

  -- Return Authenticated  
  return l_authed;
  when others then
  retval := dbms_ldap.unbind_s( ld => l_session );
  -- Return NOT Authenticated  
  apex_util.set_custom_auth_status ( p_status => l_not_authenticated );
  return false;    
Post a Comment

Popular posts from this blog

A review of APEX World 2017 - Day 1

Last week the SS Rotterdam was the beautiful location of the largest gathering of APEX Developers worldwide. With around 380 (!) attendees a new high was set. And they came from all over the world : I spotted people from The Netherlands, Belgium, Switzerland, Austria, Croatia, Germany, Denmark, Norway, UK, Ireland and the USA. And I even might have missed one or two ….

The event started with a presentation by the “father of APEX”, Mike Hichwa, talking about "Oracle APEX Past, Present and Future”. Of course everyone is curious what the APEX future might bring: Friendly URL’s, automated testing, more JSON, concurrent APEX versions, third party Oauth 2 authentication (think Facebook, Google), APEX app diff and more, a lot more, REST capabilities. And now we have to wait for APEX 5.2 … and that might take a while! 
After this keynote, the conference split up in three tracks. After the coffee break I returned to to big theatre where Geertjan Wielenga talked about "Finally Javas…

Push changed rows to an Interactive Grid

For pushing changes from the database to the end user, the regular solution is using websockets. A change in a record is detected - using a trigger or using the CQN (Change Query Notification) feature - and a notification is send to a websocket server. That websocket server broadcasts the notification over a channel to all browsers that are tuned in to that websocket channel. Then the browser reacts to that notification, usually showing an alert or refreshing a report. This trick is described on multiple sites, just Google for "oracle apex websockets" or similar.

So back in the old days, we used that notification in the browser to refresh the (interactive) report. But along comes the Interactive Grid (IG). While he full-refresh mechanism still works for IG, an IG has also the option to refresh just one row.  So wouldn't it be awesome that just the changed row(s) get refreshed upon a change in the database, instead of the whole report? Can we do it ... yes we can!
First i…

Dockerize your APEX development environment

Nowadays Docker is everywhere. It is one of the main components of Continuous Integration / Continuous Development environments. That alone indicates Docker has to be seen more as a Software Delivery Platform than as a replacement of a virtual machine.

However ...

If you are running an Oracle database using Docker on your local machine to develop some APEX application, you will probably not move that container is a whole to test and production environments. Because in that case you would not only deliver a new APEX application to the production environment - which is a good thing - but also overwrite the data in production with the data from your development environment. And that won't make your users very excited.
So in this set up you will be using Docker as a replacement of a Virtual Machine and not as a Delivery Platform.
And that's exactly the way Martin is using it as he described in this recent blog post. It is an ideal way to get up and running with an Oracle database …