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;    


Popular posts from this blog

apex_application.g_f0x array processing in Oracle 12

If you created your own "updatable reports" or your custom version of tabular forms in Oracle Application Express, you'll end up with a query that looks similar to this one:
then you disable the "Escape special characters" property and the result is an updatable multirecord form.
That was easy, right? But now we need to process the changes in the Ename column when the form is submitted, but only if the checkbox is checked. All the columns are submitted as separated arrays, named apex_application.g_f0x - where the "x" is the value of the "p_idx" parameter you specified in the apex_item calls. So we have apex_application.g_f01, g_f02 and g_f03. But then you discover APEX has the oddity that the "checkbox" array only contains values for the checked rows. Thus if you just check "Jones", the length of g_f02 is 1 and it contains only the empno of Jones - while the other two arrays will contain all (14) rows. So for processing y…

Adding items to your Interactive Grid Toolbar

The APEX Interactive Grid uses the Toolbar widget to create the default Toolbar showing the Search box, Actions menu, Save button etc. And since quite a while there is a nice Plugin "Extend IG Toolbar" by Marko Goricki that makes it very easy to add additional buttons to the Toolbar.

But what if you need more than a button? 
Inspecting the contents of widget.toolbar.js, you can easily spot there can be added more to the Toolbar than just a button: The type of control, available values:
The first example will show a way to easily switch from one filter to another. Of course we could use the standard functionality and create two different Report views, but using a Radio Group on the Toolbar gives a more "Tab" like user experience.

So how can we create a Radio Group that looks like a switch in the Toolbar?
In the Javascript Code …

Refresh selected row(s) in an Interactive Grid

In my previous post I blogged about pushing changed rows from the dabatase into an Interactive Grid. The use case I'll cover right here is probably more common - and therefore more useful!

Until we had the IG, we showed the data in a report (Interactive or Classic). Changes to the data where made by popping up a form page, making changes, saving and refreshing the report upon closing the dialog. Or by clicking an icon / button / link in your report that makes some changes to the data (like changing a status) and ... refresh the report.  That all works fine, but the downsides are: The whole dataset is returned from the server to the client - again and again. And if your pagination size is large, that does lead to more and more network traffic, more interpretation by the browser and more waiting time for the end user.The "current record" might be out of focus after the refresh, especially by larger pagination sizes, as the first rows will be shown. Or (even worse) while you…