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
is
  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;
  
BEGIN
  -- 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;
    
EXCEPTION
  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;    
END;​

Comments

Popular posts from this blog

How to create neatly formatted Excel documents using PL/SQL?

If there is a requirement to produce output from an application into Excel, you would probably create a CSV (Comma Separated File) with the data and start Excel to show the data - at least that's what I did...until now. The drawback of this solution is that you could only produce data and no nice layout. But Excel is also capable of opening HTML-files and using this you could create Excel files with data and magnificent layout! Let me give an example: 1. Create a procedure to show the data in formatted in an HTML table. CREATE OR REPLACE PROCEDURE display_emp_list IS v_emp_count NUMBER(5); v_empno NUMBER(8); v_ename VARCHAR2(50); v_job emp.job%TYPE; v_sal emp.sal%TYPE; v_bg_color VARCHAR2(10) := ''; CURSOR c_emp IS SELECT empno, initcap(ename), job, sal FROM emp ORDER BY ename; BEGIN SELECT COUNT(*) INTO v_emp_count FROM emp; owa_util.mime_header('application/ms-excel', FALSE); htp.p('Content...

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 wors...

APEX ReadOnly Pages - The easy way

If your Oracle APEX Application requires different types of access - full access or readonly - for different types of users, you can specify a Read Only Condition on Page level (or Region, Item, Button, etc.).  You can set an Authorization Scheme on Application level, so it'll be applied to all pages. So if you have an Authorization Scheme named 'User Can Access Page' defined by a PL/SQL function like this: return apex_authorization.user_can_access_page ( p_app_id  => :APP_ID , p_page_id => :APP_PAGE_ID , p_user    => :APP_USER );  then you can code all the logic in the database using the APEX Repository, your own tables or a combination to define whether a user has access to that page or not. But alas it is not possible to define something similar Application wide for a Read Only condition. You can specify an Authorization Scheme 'User has Read Only Access' using a similar signature as the one above and use that on each and e...