Mapeamento de papéis externos

Edge para nuvem privada v4.18.01

Com o mapeamento de papéis externos, é possível mapear seus próprios grupos ou papéis para papéis de controle de acesso baseado em papéis (RBAC, na sigla em inglês) e grupos criados no Apigee Edge. Este recurso está disponível apenas com a nuvem privada de borda.

O que há de novo

O serviço de mapeamento de papéis externos do Edge para versões de nuvem privada anteriores à 4.18.01 foi descontinuado. A versão 4.18.01 do mapeamento de papéis externos é uma versão atualizada com bugs corrigidos e novos recursos adicionados:

  • Foi corrigido o problema em que você recebia respostas proibidas de autenticação 403 ao autenticar com usuários que deveriam ter acesso.
  • Agora, o cabeçalho X-Apigee-Current-User é compatível com o mapeamento de papéis externos. Usuários com acesso adequado (sysadmin) agora podem ver os papéis atribuídos a outro usuário.

Pré-requisitos

  • Você precisa ser um administrador do sistema de nuvem privada da Apigee com credenciais de administrador de sistema global para executar essa configuração.
  • Você precisa saber o diretório raiz da instalação da nuvem privada do Apigee Edge. O diretório raiz padrão é /opt.

Exemplo de configuração detalhada

Consulte este artigo nos fóruns da comunidade da Apigee para conferir um exemplo detalhado da configuração do mapeamento de papéis externos.

Configuração padrão

O mapeamento de papéis externos está desativado por padrão.

Como ativar o mapeamento de papéis externos

  1. Antes de concluir a configuração a seguir, crie uma classe Java que implemente a interface do ExternalRoleMapperServiceV2 e inclua a implementação no caminho de classe do gerenciamento do servidor:

    /opt/apigee/edge-management-server/lib/thirdparty/

    Para mais detalhes sobre a implementação, consulte a seção Sobre a implementação de amostra do ExternalRoleMapperImpl mais adiante neste documento.
  2. Faça login no servidor de gerenciamento do Apigee Edge e interrompa o processo do servidor de gerenciamento:
    > /opt/apigee/apigee-service/bin/apigee-service stop-management-server stop
  3. Abra /opt/apigee/customer/application/management-server.properties em um editor de texto. Se o arquivo não existir, crie-o.
  4. Edite o arquivo de propriedades para fazer as seguintes configurações:
    # O armazenamento do usuário a ser usado para autenticação.
    # Use "externalized.authentication" para o armazenamento do usuário LDAP.
    # Para autorização, continuamos usando o LDAP.
    # Consulte Como ativar a autenticação externa para saber mais sobre como ativar a autenticação externa.
    conf_security_authentication.user.store=externalized.authentication

    #Ative o mapeador do papel de autorizações externas.
    conf_security_externalized.authentication.role.mapper.enabled=true conf_security_externalized.authentication.role.mapper.implementation.class=
    com.customer.authorization.impl.ExternalRoleMapperImpl

    Importante:
    a classe de implementação e o nome do pacote na configuração acima (ExternalRole, ou seja, a classe que você quer implementar e a classe que você quer implementar, é apenas um exemplo que você quer implementar e a classe que você quiser implementar. Para detalhes sobre como implementar essa classe, consulte Sobre a classe de implementação de amostra do ExternalRoleMapperImpl abaixo. Essa é uma classe que você precisa implementar para refletir seus próprios grupos.
  5. Salve o arquivo management-server.properties.
  6. Verifique se management-server.properties é de propriedade do usuário da Apigee:?
    > chown apigee:apigee /opt/apigee/customer/application/management-server.properties
  7. Inicie o servidor de gerenciamento:
    > /opt/apigee/apigee-service/bin/apigee-service edge-management-server start

Como desativar a autorização externa

Para desativar a autorização externa:

  1. Abra /opt/apigee/customer/application/management-server.properties em um editor de texto. Se o arquivo não existir, crie-o.
  2. Mude o repositório do usuário de autenticação para ldap:
    conf_security_authentication.user.store=ldap
  3. Defina esta propriedade como falsa:
    conf_security_externalized.authentication.role.mapper.enabled=false
  4. Reinicie o servidor de gerenciamento:
    > /opt/apigee/apigee-service/bin/apigee-service edge-management-server start

Sobre a implementação de amostra do ExternalRoleMapperImpl

No arquivo de configuração security.properties descrito anteriormente em Como ativar o mapeamento de funções externas, observe esta linha:

externalized.authentication.role.mapper.implementation.class=com.customer.authorization.impl.ExternalRoleMapperImpl

Esta classe implementa a interface ExternalRoleMapperServiceV2 e é obrigatória. Você precisa criar sua própria implementação dessa classe que reflita seus respectivos grupos. Quando terminar, coloque a classe compilada em um JAR e coloque esse JAR no caminho de classe do servidor de gerenciamento em:

/opt/apigee/edge-management-server/lib/thirdparty/

Você pode nomear a classe e o pacote como quiser, desde que ela implemente ExternalRoleMapperServiceV2, seja acessível no caminho de classe e seja referenciada corretamente no arquivo de configuração management-server.properties.

Abaixo, apresentamos um exemplo bem comentado de implementação de uma classe ExternalRoleMapperImpl.

package com.customer.authorization.impl;

import com.apigee.authentication.*;
import com.apigee.authorization.namespace.OrganizationNamespace;
import com.apigee.authorization.namespace.SystemNamespace;
import java.util.Collection;
import java.util.HashSet;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

/** *
* Sample Implementation constructed with dummy roles with expected namespaces.
*/

public class ExternalRoleMapperImpl
       implements ExternalRoleMapperServiceV2 {

   InitialDirContext dirContext = null;

   @Override
   public void start(ConfigBean arg0) throws ConnectionException {

       try {
           // Customer Specific Implementation will override the
           // ImplementDirContextCreationLogicForSysAdmin method implementation.
           // Create InitialDirContext based on the system admin user credentials.
           dirContext = ImplementDirContextCreationLogicForSysAdmin();
       } catch (NamingException e) {
           // TODO Auto-generated catch block
           throw new ConnectionException(e);
       }
   }

   @Override
   public void stop() throws Exception {
   }

   /**
    * This method should be replaced with customer's implementation
    * For given roleName under expectedNamespace, return all users that belongs to this role
    * @param roleName
    * @param expectedNamespace
    * @return All users that belongs to this role. For each user, please return the username/email that is stored in Apigee LDAP
    * @throws ExternalRoleMappingException
    */
   @Override
   public Collection<String> getUsersForRole(String roleName, NameSpace expectedNamespace) throws ExternalRoleMappingException {
       Collection<String> users = new HashSet<>();
       if (expectedNamespace instanceof SystemNamespace) {
           // If requesting all users with sysadmin role
           if (roleName.equalsIgnoreCase("sysadmin")) {
               // Add sysadmin's email to results
               users.add("sysadmin@wacapps.net");
           }
       } else {
           String orgName = ((OrganizationNamespace) expectedNamespace).getOrganization();
           // If requesting all users of engRole in Apigee LDAP
           if (roleName.equalsIgnoreCase("engRole")) {
               // Get all users in corresponding groups in customer's LDAP. In this case looking for 'engGroup';
               SearchControls controls = new SearchControls();
               controls.setSearchScope(1);
               try {
                   NamingEnumeration<SearchResult> res = dirContext.search("ou=groups,dc=corp,dc=wacapps,dc=net",
                           "cn=engGroup", new Object[]{"",""}, controls);
                   while (res.hasMoreElements()) {
                       SearchResult sr = res.nextElement();
                       // Add all users into return
                       users.addAll(sr.getAttributes().get("users").getAll());
                   }
               } catch (NamingException e) {
                   // Customer needs to handle the exception here
               }
           }
       }
       return users;
   }

   /**
    *
    * This method would be implemented by the customer and would be invoked
    * while including using X-Apigee-Current-User header in request.
    *
    * X-Apigee-Current-User allows the customer to login as another user
    *
    * Below is the basic example.
    *
    * If User has sysadmin role then it's expected to set SystemNameSpace
    * along with the expected NameSpace. Otherwise role's expectedNameSpace
    * to be set for the NameSpacedRole.
    *
    * Collection<NameSpacedRole> results = new HashSet<NameSpacedRole>();
    *
    * NameSpacedRole sysNameSpace = new NameSpacedRole("sysadmin",
    * SystemNamespace.get());
    *
    * String orgName =
    * ((OrganizationNamespace) expectedNameSpace).getOrganization();
    *
    * NameSpacedRole orgNameSpace = new NameSpacedRole ("orgadmin",
    * expectedNameSpace);
    *
    * results.add(sysNameSpace);
    *
    * results.add(orgNameSpace);
    *
    *
    * @param username UserA's username
    * @param password UserA's password
    * @param requestedUsername UserB's username. Allow UserA to request UserB's userroles with
    *                          UserA's credentials when requesting UserB as X-Apigee-Current-User
    * @param expectedNamespace
    * @return
    * @throws ExternalRoleMappingException
    */
   @Override
   public Collection<NameSpacedRole> getUserRoles(String username, String password, String requestedUsername, NameSpace expectedNamespace) throws ExternalRoleMappingException {
       /************************************************************/
       /******************** Authenticate UserA ********************/
       /************************************************************/

       // Customer Specific Implementation will override the
       // ImplementDnameLookupLogic method implementation.

       // obtain dnName for given username.
       String dnName = ImplementDnNameLookupLogic(username);
       // Obtain dnName for given requestedUsername.
       String requestedDnName = ImplementDnNameLookupLogic(requestedUsername);

       if (dnName == null || requestedDnName == null) {
           System.out.println("Error ");
       }

       DirContext dirContext = null;
       try {

           // Customer Specific Implementation will override the
           // ImplementDirectoryContextCreationLogic method implementation

           // Create a directory context with dnName or requestedDnName and password
           dirContext = ImplementDirectoryContextCreationLogic();

           /************************************************/
           /*** Map internal groups to apigee-edge roles ***/
           /************************************************/
           return apigeeEdgeRoleMapper(dirContext, requestedDnName, expectedNamespace);

       } catch (Exception ex) {
           ex.printStackTrace();
           System.out.println("Error in authenticating User: {}" + new Object[] { username });

       } finally {
           // Customer implementation to close
           // ActiveDirectory/LDAP context.
       }

       return null;

   }

   /**
    *
    * This method would be implemented by the customer and would be invoked
    * wihle using username and password for authentication and without the
    * X-Apigee-Current-User header
    *
    * The customer can reuse implementations in
    *      getUserRoles(String username, String password, String requestedUsername, NameSpace expectedNamespace)
    * by
    *      return getUserRoles(username, password, username, expectedNamespace)
    * in implementations.
    *
    * or the customer can provide new implementations as shown below.
    */

   @Override
   public Collection<NameSpacedRole> getUserRoles(String username, String password, NameSpace expectedNamespace) throws ExternalRoleMappingException {
       /*************************************************************/
       /****************** Authenticate Given User ******************/
       /*************************************************************/

       // Customer Specific Implementation will override the
       // ImplementDnameLookupLogic implementation.

       // Obtain dnName for given username or email address.
       String dnName = ImplementDnNameLookupLogic(username);

       if (dnName == null) {
           System.out.println("Error ");
       }

       DirContext dirContext = null;
       try {
           // Create a directory context with username or dnName and password
           dirContext = ImplementDirectoryContextCreationLogic();

           /************************************************/
           /*** Map internal groups to apigee-edge roles ***/
           /************************************************/
           return apigeeEdgeRoleMapper(dirContext, dnName, expectedNamespace);

       } catch (Exception ex) {
           ex.printStackTrace();
           System.out.println("Error in authenticating User: {}" + new Object[] { username });

       } finally {
           // Customer implementation to close
           // ActiveDirectory/LDAP context.
       }

       return null;
   }

   /**
    *
    * This method would be implemented by the customer and would be invoked
    * while using security token or access token as authentication credentials.
    *
    */
   @Override
   public Collection<NameSpacedRole> getUserRoles(String username, NameSpace expectedNamespace) throws ExternalRoleMappingException {

       /*************************************************************/
       /****************** Authenticate Given User ******************/
       /*************************************************************/

       // Customer Specific Implementation will override the
       // ImplementDnameLookupLogic implementation.

       // Obtain dnName for given username or email address.
       String dnName = ImplementDnNameLookupLogic(username);

       if (dnName == null) {
           System.out.println("Error ");
       }

       DirContext dirContext = null;
       try {
           // Create a directory context with username or dnName and password
           dirContext = ImplementDirectoryContextCreationLogic();

           /************************************************/
           /*** Map internal groups to apigee-edge roles ***/
           /************************************************/
           return apigeeEdgeRoleMapper(dirContext, dnName, expectedNamespace);

       } catch (Exception ex) {
           ex.printStackTrace();
           System.out.println("Error in authenticating User: {}" + new Object[] { username });

       } finally {
           // Customer implementation to close
           // ActiveDirectory/LDAP context.
       }

       return null;
   }

   /**
    *  This method should be replaced with Customer Specific Implementations
    *
    *  Provided as a sample Implementation of mapping user groups to apigee-edge roles
    */
   private Collection<NameSpacedRole> apigeeEdgeRoleMapper(DirContext dirContext, String dnName, NameSpace expectedNamespace) throws Exception {

       Collection<NameSpacedRole> results = new HashSet<NameSpacedRole>();

       /****************************************************/
       /************ Fetch internal groups *****************/
       /****************************************************/

       String groupDN = "OU=Groups,DC=corp,DC=wacapps,DC=net";
       String userFilter = "(user=userDnName)";
       SearchControls controls = new SearchControls();
       controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);

       // Looking for all groups the user belongs to in customer's LDAP
       NamingEnumeration<SearchResult> groups = dirContext.search(groupDN,userFilter.replace("userDnName", dnName), new Object[] { "", "" }, controls);

       if (groups.hasMoreElements()) {
           while (groups.hasMoreElements()) {
               SearchResult searchResult = groups.nextElement();
               Attributes attributes = searchResult.getAttributes();
               String groupName = attributes.get("name").get().toString();

               /************************************************/
               /*** Map internal groups to apigee-edge roles ***/
               /************************************************/

               if (groupName.equals("BusDev")) {
                   results.add(new NameSpacedRole("businessAdmin",SystemNamespace.get()));

               } else if (groupName.equals("Engineering")) {
                   if (expectedNamespace instanceof OrganizationNamespace) {
                       String orgName = ((OrganizationNamespace) expectedNamespace).getOrganization();
                       results.add(new NameSpacedRole("orgadmin", new OrganizationNamespace(orgName)));
                   }

               } else if (groupName.equals("Marketing")) {
                   results.add(new NameSpacedRole("marketAdmin",SystemNamespace.get()));

               } else {
                   results.add(new NameSpacedRole("readOnly",SystemNamespace.get()));
               }
           }

       } else {
           // In case of no group found or exception found we throw empty roles.
           System.out.println(" !!!!! NO  GROUPS FOUND !!!!!");
       }
       return results;
   }

   /**
    * The customer need to replace with own implementations for getting dnName for given user
    */
   private String ImplementDnNameLookupLogic(String username) {
       // Connect to the customer's own LDAP to fetch user dnName
       return customerLDAP.getDnName(username);
   }

   /**
    * The customer need to replace with own implementations for creating DirContext
    */
   private DirContext ImplementDirectoryContextCreationLogic() {
       // Connect to the customer's own LDAP to create DirContext for given user
       return customerLDAP.createLdapContextUsingCredentials();
   }

}