Métodos de Autenticación Apilables

Dado que muchas instituciones y organizaciones ya cuentan con sistemas de autenticación existentes, DSpace ha sido diseñado para permitir su integración sencilla dentro de una infraestructura de autenticación ya establecida. Mantiene una serie o "pila" de métodos de autenticación, de modo que cada uno puede ser probado en orden. Esto facilita la adición de nuevos métodos de autenticación o la reorganización del orden de los mismos sin necesidad de modificar el código existente. También es posible compartir código de autenticación con otros sitios.

Configuration File:

[dspace]/config/modules/authentication.cfg

Property:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod

Example Value:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod = org.dspace.authenticate.PasswordAuthentication

La propiedad de configuración plugin.sequence.org.dspace.authenticate.AuthenticationMethod define la pila de autenticación. Es una lista de nombres de clase separados por comas. Cada una de estas clases implementa un método de autenticación diferente, es decir, una forma de determinar la identidad del usuario. Se invocan en el orden especificado hasta que uno de ellos tenga éxito.

Los métodos de autenticación existentes incluyen:

Un método de autenticación es una clase que implementa la interfaz org.dspace.authenticate.AuthenticationMethod. Se encarga de autenticar a un usuario evaluando las credenciales (por ejemplo, nombre de usuario y contraseña) que este presenta y verificando su validez.

Autenticación por Contraseña

Habilitación de la Autenticación por Contraseña

De forma predeterminada, este método de autenticación está habilitado en DSpace.

Sin embargo, para habilitar la autenticación por contraseña, debe asegurarse de que la clase org.dspace.authenticate.PasswordAuthentication esté incluida como uno de los AuthenticationMethods en la siguiente configuración:

Configuration File:

[dspace]/config/modules/authentication.cfg

Property:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod

Example Value:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod = org.dspace.authenticate.PasswordAuthentication

Configuración de la Autenticación por Contraseña

El método predeterminado org.dspace.authenticate.PasswordAuthentication tiene las siguientes características:

  • Uso del inicio de sesión integrado basado en dirección de correo electrónico y contraseña. Esto se logra enviando la información de inicio de sesión al endpoint "/api/authn/login" de la API REST, con el fin de obtener un JSON Web Token. Este token debe enviarse en cada solicitud posterior que requiera autenticación.
  • Los usuarios pueden registrarse por sí mismos (es decir, agregarse como e-people sin necesidad de aprobación por parte de los administradores), y pueden establecer su propia contraseña al hacerlo.
  • Los usuarios no son miembros de ningún grupo especial de e-personas (dinámico).
  • Puede restringir los dominios desde los cuales se permite el registro de nuevos usuarios. Para habilitar esta función, descomente la siguiente línea en el archivo dspace.cfg: authentication.password.domain.valid = example.com Ejemplos de opciones pueden ser '@example.com' para restringir el registro a usuarios con direcciones que terminan en @example.com, o '@example.com, .ac.uk' para restringirlo a direcciones que terminen en @example.com o en dominios .ac.uk.

Una lista completa de todas las configuraciones disponibles para la Autenticación por Contraseña:

Configuration File:

[dspace]/config/modules/authentication-password.cfg

Property:

user.registration

Example Value:user.registration = false
Informational Note:This option allows you to disable all self-registration. When set to "false", no one will be able to register new accounts with your system. Default is "true".
Property:user.forgot-password
Example Value:user.forgot-password = false
Informational Note:

This option allows you to disable the forgot password link inside the login page. When set to "false", no one will be able to reset the password related to its account.

Default is "true".

Property:

authentication-password.domain.valid

Example Value:

authentication-password.domain.value = @mit.edu, .ac.uk

Informational Note:

This option allows you to limit self-registration to email addresses ending in a particular domain value. The above example would limit self-registration to individuals with "@mit.edu" email addresses and all ".ac.uk" email addresses. (This setting only works when user.registration=true)

Property:

authentication-password.login.specialgroup

Example Value:

authentication-password.login.specialgroup = My DSpace Group

Informational Note:

This option allows you to automatically add all password authenticated user sessions to a specific DSpace Group (the group must exist in DSpace) for the remainder of their logged in session.

Property:

authentication-password.digestAlgorithm

Example Value:

authentication-password.digestAlgorithm = SHA-512

Informational Note:

This option specifies the hashing algorithm to be used in converting plain-text passwords to more secure password digests. The example value is the default. You may select any digest algorithm available through java.security.MessageDigest on your system. At least MD2, MD5, SHA-1, SHA-256, SHA-384, and SHA-512 should be available, but you may have installed others. Most sites will not need to adjust this.

Property:

authentication-password.regex-validation.pattern

Example Value:

authentication-password.regex-validation.pattern = ^.{8\,}$

Informational Note:

This option specifies a regular expression which all new passwords MUST validate against. By default, DSpace just requires a new password to be 8 or more characters (see above example value). However, sites can modify this regex in order to require more robust passwords of all users. One example of a complex rule is:

authentication-password.regex-validation.pattern = ^(?=.*?[a-z])(?=.*?[A-Z])(?=\\S*?[0-9])(?=\\S*?[!?$@#$%^&+=]).{8\,15}$

This example requires all users to adopt a more complex password:

  • (?=.*?[a-z]) - the password must contain at least one lowercase character

  • (?=.*?[A-Z]) - the password must contain at least one uppercase character

  • (?=\\S*?[0-9]) - the password must contain at least one numeric character

  • (?=\\S*?[!?$@#$%^&+=]) - the password must contain at least one of the following special character: !?$@#$%^&+=

  • .{8\,15} - the password must be at least 8 and at most 15 characters long (NOTE: the "\," is required to escape the comma, which is a special character)

Autenticación con Open ID Connect (OIDC)

La autenticación con Open ID Connect (OIDC) está disponible únicamente en DSpace 7.2 o versiones superiores.

Habilitación de la Autenticación OIDC

Para habilitar la autenticación con OIDC, debe asegurarse de que la clase org.dspace.authenticate.OidcAuthentication esté incluida como uno de los AuthenticationMethods en la siguiente configuración:

Configuration File:

[dspace]/config/modules/authentication.cfg

Property:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod

Example Value:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod = org.dspace.authenticate.OidcAuthentication

(NOTE: This setting may be repeated to support multiple AuthenticationMethods)

(WARNING: it's easy to miss, the "camel case" for OidcAuthentication might catch you off guard. It's important to not use OIDCAuthentication in this line, because that class does not exist. Case matters.

Configuración de la Autenticación OIDC

OpenID Connect es una capa de identidad sobre el protocolo OAuth 2.0. Permite que los Clientes verifiquen la identidad del Usuario Final (End-User) basándose en la autenticación realizada por un Servidor de Autorización, así como obtener información básica del perfil del usuario final de forma interoperable y similar a REST. Existen muchas implementaciones de servidor de OpenID Connect, incluyendo Keycloak y AWS Cognito.

Configuration File:

[dspace]/config/modules/authentication-oidc.cfg

Property:

authentication-oidc.auth-server-url

Example Value:

authentication-oidc.auth-server-url = https://auth.example.com

Informational Note:

(Optional) The root URL of the OpenID Connect server. This is optional, as it's only used to fill out each of the "-endpoint" configs below (see below).
So, for some setups, it may be easier to configure the "-endpoint" configs directly INSTEAD OF the "auth-server-url" and "auth-server-realm"

Property:authentication-oidc.auth-server-realm
Example Value:authentication-oidc.auth-server-realm = dspace-realm
Informational Note:(Optional) The realm to authenticate against on the OpenID Connect server. This is optional, as it's only used to fill out each of the "-endpoint" configs below (see below).
So, for some setups, it may be easier to configure the "-endpoint" configs directly INSTEAD OF the "auth-server-url" and "auth-server-realm"
Property: authentication-oidc.token-endpoint
Example Value: authentication-oidc.token-endpoint = ${authentication-oidc.auth-server-url}/auth/realms/${authentication-oidc.auth-server-realm}/protocol/openid-connect/token
Informational Note:(Required) The URL of the OIDC Token endpoint. This defaults to using the configured "auth-server-url" and "auth-server-realm" to determine the likely OIDC path for this endpoint (see example above for the default value). However, if that default path is incorrect, you may choose to hardcode the correct URL in this field.
Property:authentication-oidc.authorize-endpoint
Example Value:authentication-oidc.authorize-endpoint = ${authentication-oidc.auth-server-url}/auth/realms/${authentication-oidc.auth-server-realm}/protocol/openid-connect/auth
Informational Note:(Required) The URL of the OIDC Authorize endpoint. This defaults to using the configured "auth-server-url" and "auth-server-realm" to determine the likely OIDC path for this endpoint (see example above for the default value). However, if that default path is incorrect, you may choose to hardcode the correct URL in this field.
Property:authentication-oidc.user-info-endpoint
Example Value:authentication-oidc.user-info-endpoint = ${authentication-oidc.auth-server-url}/auth/realms/${authentication-oidc.auth-server-realm}/protocol/openid-connect/userinfo
Informational Note:(Required) The URL of the OIDC Userinfo endpoint. This defaults to using the configured "auth-server-url" and "auth-server-realm" to determine the likely OIDC path for this endpoint (see example above for the default value). However, if that default path is incorrect, you may choose to hardcode the correct URL in this field.
Property:authentication-oidc.client-id
Example Value:authentication-oidc.client-id = our-dspace
Informational Note:(Required) The registered OIDC client id for our DSpace server's use. No default value.
Property:authentication-oidc.client-secret
Example Value:authentication-oidc.client-secret = some-sort-of-hash
Informational Note:(Required) The registered OIDC client secret for our DSpace server's use. No default value.
Property:authentication-oidc.redirect-url
Example Value:authentication-oidc.redirect-url = ${dspace.server.url}/api/authn/oid
Informational Note:The URL users will be redirected to after a successful login. The example above is the default value, and it usually does not need to be updated.
Property:authentication-oidc.scopes
Example Value:authentication-oidc.scopes = openid,email,profile
Informational Note:The scopes to request from the OIDC server. The example above is the default value
Property:authentication-oidc.can-self-register
Example Value:authentication-oidc.can-self-register = true
Informational Note:

Specify if the user can self register using OIDC (true|false). If not specified, true is assumed.

If this is set to false, then only users with an existing EPerson in DSpace will be able to authenticate through OIDC. When set to true, an EPerson will be automatically created for each person who successfully authenticates through OIDC.

Property:authentication-oidc.user-info.email
Example Value:authentication-oidc.user-info.email = email
Informational Note:Specify the attribute present in the user info json related to the user's email. The default value is "email"
Property:authentication-oidc.user-info.first-name
Example Value:authentication-oidc.user-info.first-name = given_name
Informational Note:Specify the attribute present in the user info json related to the user's first/given name. The default value is "given_name"
Property:authentication-oidc.user-info.last-name
Example Value:authentication-oidc.user-info.last-name = family_name
Informational Note:Specify the attribute present in the user info json related to the user's last/family name. The default value is "family_name"
Ejemplo/Configuración de prueba de OIDC

Una forma sencilla de probar la autenticación OIDC es utilizar el sitio de prueba PhantAuth en https://www.phantauth.net/. Este sitio permite crear un cliente OIDC aleatorio y un usuario OIDC aleatorio con el que autenticarse. Por lo tanto, puede utilizarse para verificar que la autenticación OIDC de DSpace está funcionando en su sistema, aunque evidentemente está destinado únicamente a fines de desarrollo/pruebas.

Para configurar DSpace para utilizar PhantAuth como proveedor de autenticación, solo necesita realizar las siguientes actualizaciones en su archivo local.cfg:

local.cfg updates for PhantAuth
# Enable OIDC
plugin.sequence.org.dspace.authenticate.AuthenticationMethod = org.dspace.authenticate.OidcAuthentication

# Settings for OIDC authentication
# Based on instructions at https://www.phantauth.net/doc/integration
authentication-oidc.authorize-endpoint = https://phantauth.net/auth/authorize
authentication-oidc.token-endpoint = https://phantauth.net/auth/token
authentication-oidc.user-info-endpoint = https://phantauth.net/auth/userinfo

# Obtain a random client-id and client-secret via https://phantauth.net/client
# Find the "client_id" and "client_secret" returned, and place those values in these next two configs.
authentication-oidc.client-id = 
authentication-oidc.client-secret = 

# Because PhantAuth uses random users, you MUST ensure self registration is enabled 
# (This is the default setting though, which is why it's commented out)
# authentication-oidc.can-self-register = true


Autenticación con Shibboleth

Habilitación de la Autenticación Shibboleth

Para habilitar la autenticación con Shibboleth, debe asegurarse de que la clase org.dspace.authenticate.ShibAuthentication esté incluida como uno de los AuthenticationMethods en la siguiente configuración:

Configuration File:

[dspace]/config/modules/authentication.cfg

Property:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod

Example Value:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod = org.dspace.authenticate.ShibAuthentication

(NOTE: This setting may be repeated to support multiple AuthenticationMethods)

Configuración de la Autenticación con Shibboleth

Shibboleth es un sistema de autenticación distribuido que permite autenticar usuarios de forma segura y transmitir atributos sobre el usuario desde uno o más proveedores de identidad. En la terminología de Shibboleth, DSpace actúa como un Proveedor de Servicios (Service Provider), el cual recibe la información de autenticación y, en base a ella, proporciona un servicio al usuario. Para utilizar Shibboleth, DSpace requiere que se utilice Apache instalado con el módulo mod_shib, actuando como proxy para todas las solicitudes HTTP hacia su contenedor de servlets (típicamente Tomcat). DSpace recibirá la información de autenticación desde el módulo mod_shib a través de cabeceras HTTP.

Antes de que DSpace funcione con Shibboleth, debe contar con lo siguiente:

  1. Un servidor web Apache con el módulo "mod_shib" instalado. Como se mencionó, este módulo mod_shib actúa como un proxy para todas las solicitudes HTTP dirigidas a su contenedor de servlets (típicamente Tomcat). Cualquier solicitud a DSpace que requiera autenticación mediante Shibboleth debe ser redirigida al 'shibd' (el demonio de Shibboleth) por medio de este módulo mod_shib. Los detalles para instalar y configurar mod_shib en Apache están disponibles en: https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPApacheConfig también se proporciona a continuación una configuración de ejemplo para Apache + mod_shib.
  2. Un IdP (Proveedor de Identidad) Shibboleth externo. Utilizando mod_shib, DSpace actuará únicamente como un SP (Proveedor de Servicios) de Shibboleth. La autenticación y la información de identidad reales deben ser proporcionadas por un IdP externo. Si su institución ya utiliza Shibboleth, entonces probablemente ya cuente con un IdP disponible. Puede encontrar más información sobre la diferencia entre IdPs y SPs en Shibboleth en: https://wiki.shibboleth.net/confluence/display/SHIB2/UnderstandingShibboleth

Para obtener más información sobre la instalación y configuración de un Proveedor de Servicios Shibboleth, consulte: https://wiki.shibboleth.net/confluence/display/SHIB2/Installation

Nota sobre sesiones Shibboleth activas vs. perezosas (lazy sessions):

Al configurar su Proveedor de Servicios Shibboleth, puede elegir entre dos paradigmas de sesión de Shibboleth: Sesiones activas o sesiones perezosas (lazy sessions). Sesiones activas: el módulo mod_shib está configurado para proteger un espacio completo de URLs. Nadie podrá acceder a esas URLs sin autenticarse previamente con Shibboleth. Usando este método, deberá configurar Shibboleth para proteger la URL: /shibboleth-login. Sesión perezosa (Lazy Session): no se protege ninguna URL específica. En su lugar, Apache permitirá el acceso a cualquier URL, y será la aplicación la que iniciará una sesión autenticada cuando lo necesite.

El método de sesión perezosa (Lazy Session) es preferible para la mayoría de las instalaciones de DSpace, ya que normalmente se desea proporcionar acceso público a la mayor parte del contenido de DSpace, restringiendo el acceso solo a áreas particulares (por ejemplo, interfaz de administración, herramientas administrativas, ítems privados, etc.). Cuando se habilitan las sesiones activas, todo su sitio DSpace estará restringido. En otras palabras, al usar sesiones activas, Shibboleth requerirá que todos los usuarios se autentiquen antes de poder acceder a cualquier parte del repositorio (lo que en la práctica resulta en un “archivo oscuro”, ya que no se permitirá el acceso anónimo).

Configuración de Apache con "mod_shib" (requerida)

Como se mencionó anteriormente, debe tener Apache con el módulo "mod_shib" instalado para que DSpace pueda actuar como un Proveedor de Servicios (SP) de Shibboleth. El módulo mod_shib actúa como un proxy para todas las solicitudes HTTP dirigidas a su contenedor de servlets (típicamente Tomcat). Cualquier solicitud a DSpace que requiera autenticación mediante Shibboleth debe ser redirigida al demonio 'shibd' por medio de este módulo mod_shib. Los detalles sobre la instalación y configuración de mod_shib en Apache están disponibles en: https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPApacheConfig Información general sobre la instalación y configuración de Proveedores de Servicios (SPs) de Shibboleth puede encontrarse en: https://wiki.shibboleth.net/confluence/display/SHIB2/Installation

Algunas notas y sugerencias adicionales al configurar mod_shib y Apache:

  • En entornos basados en Debian, el módulo "mod_shib" suele encontrarse en un paquete con un nombre como "libapache2-mod-shib2"
  • La configuración de Shibboleth "ShibUseHeaders" ya no necesita establecerse en "On", ya que DSpace utilizará correctamente los atributos en lugar de las cabeceras.
    • Cuando "ShibUseHeaders" está configurado en "Off" (lo cual es lo recomendado en la documentación de mod_shib), la configuración adecuada de Apache para pasar atributos a Tomcat (ya sea mediante mod_jk o mod_proxy) puede resultar algo compleja, SWITCH ofrece una excelente documentación sobre exactamente lo que se debe hacer. Eventualmente se resumirá o parafraseará dicha documentación aquí, pero por ahora deberá consultar la página de SWITCH.
  • Al configurar inicialmente Apache y mod_shib, https://samltest.id/ proporciona un excelente entorno de prueba para sus configuraciones. Este sitio ofrece un IdP Shibboleth de muestra/demostración (así como un SP de ejemplo) contra el cual puede realizar pruebas. Actúa como una especie de "sandbox" para asegurarse de que sus configuraciones funcionen correctamente antes de apuntar DSpace a su IdP Shibboleth de producción.
  • También puede ser útil revisar la configuración de Shibboleth en nuestro entorno Docker denominado "dspace-shibboleth" que el equipo de desarrollo utiliza para realizar pruebas (y que emplea https://samltest.id como IdP). Este entorno puede ofrecer buenos ejemplos o sugerencias para lograr una configuración funcional. Sin embargo, tenga en cuenta que este código no ha sido probado en entornos de Producción.

A continuación, se proporciona un ejemplo de configuración para Apache. Sin embargo, dado que cada institución tiene su propia configuración específica de Apache, es muy probable que necesite ajustar esta configuración para que funcione correctamente en su entorno. Nuevamente, consulte la documentación oficial de mod_shib para obtener más detalles sobre cada uno de estos ajustes: https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPApacheConfig Estas configuraciones están diseñadas para agregarse a un bloque <VirtualHost> de Apache que actúe como proxy hacia su instancia de Tomcat (u otro contenedor de servlets) que ejecuta DSpace. Puede encontrar más información sobre los ajustes de Apache VirtualHost en: https://httpd.apache.org/docs/2.2/vhosts/

#### SAMPLE MOD_SHIB CONFIGURATION FOR APACHE2 (it may require local modifications based on your Apache setup) ####
# While this sample VirtualHost is for HTTPS requests (recommended for Shibboleth, obviously), 
# you may also need/want to create one for HTTP (*:80)
<VirtualHost *:443>
   ...
   # PLEASE NOTE: We have omitted many Apache settings (ServerName, LogLevel, SSLCertificateFile, etc) 
   # which you may need/want to add to your VirtualHost
    
   # As long as Shibboleth module is installed, enable all Shibboleth/mod_shib related settings
   <IfModule mod_shib>
       # Shibboleth recommends turning on UseCanonicalName
       # See "Prepping Apache" in https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPApacheConfig
       UseCanonicalName On
 
       # Most DSpace instances will want to use Shibboleth "Lazy Session", which ensures that users 
       # can access DSpace without first authenticating via Shibboleth. 
       # This section turns on Shibboleth "Lazy Session". Also ensures that once they have authenticated
       # (by accessing /Shibboleth.sso/Login path), then their Shib session is kept alive
       <Location />
         AuthType shibboleth
         ShibRequireSession Off
         require shibboleth
         # If your "shibboleth2.xml" file specifies an <ApplicationOverride> setting for your 
         # DSpace Service Provider, then you may need to tell Apache which "id" to redirect Shib requests to. 
         # Just uncomment this and change the value "my-dspace-id" to the associated @id attribute value.
         #ShibRequestSetting applicationId my-dspace-id
       </Location>
 
       # If a user attempts to access the DSpace shibboleth endpoint, force them to authenticate via Shib.
       <Location "/server/api/authn/shibboleth">
         Order deny,allow
         Allow from all
         AuthType shibboleth
         ShibRequireSession On
         # Please note that setting ShibUseHeaders to "On" is a potential security risk. 
         # You may wish to set it to "Off". See the mod_shib docs for details about this setting:
         # https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPApacheConfig#NativeSPApacheConfig-AuthConfigOptions
         # Here's a good guide to configuring Apache + Tomcat when this setting is "Off": 
         # https://www.switch.ch/de/aai/support/serviceproviders/sp-access-rules.html#javaapplications
         ShibUseHeaders On
         Require shibboleth
       </Location>
 
       # If a user attempts to access the DSpace login endpoint, ensure Shibboleth is supported but other auth methods can be too.
       <Location "/server/api/authn/login">
          Order deny,allow
          Allow from all
          AuthType shibboleth
          # For DSpace, this is required to be off otherwise the available auth methods will be not visible
          ShibRequireSession Off
          # Please note that setting ShibUseHeaders to "On" is a potential security risk.
          # You may wish to set it to "Off". See the mod_shib docs for details about this setting:
          # https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPApacheConfig#NativeSPApacheConfig-AuthConfigOptions
          # Here's a good guide to configuring Apache + Tomcat when this setting is "Off":
          # https://www.switch.ch/de/aai/support/serviceproviders/sp-access-rules.html#javaapplications
          ShibUseHeaders On
       </Location>
          
       # Ensure /Shibboleth.sso path (in Apache) can be accessed
       # By default it may be inaccessible if your Apache security is tight.
       <Location "/Shibboleth.sso">
         Order deny,allow
         Allow from all
         # Also ensure Shibboleth/mod_shib responds to this path
         SetHandler shib
       </Location>
  
       # Finally, you may need to ensure requests to /Shibboleth.sso are NOT redirected
       # to Tomcat (as they need to be handled by mod_shib instead).
       # NOTE: THIS SETTING IS LIKELY ONLY NEEDED IF YOU ARE USING mod_proxy TO REDIRECT
       # ALL REQUESTS TO TOMCAT (e.g. ProxyPass /server ajp://localhost:8009/server)
       ProxyPass /Shibboleth.sso !
   </IfModule>
  
   ...
 
 
   # You will likely need Proxy settings to ensure Apache is proxying requests to Tomcat for the DSpace REST API
   # The below is just an example of proxying for REST API only. It requires installing & enabling "mod_proxy" and "mod_proxy_ajp"
   ## Proxy / Forwarding Settings ##
   <Proxy *>
      AddDefaultCharset Off
      Order allow,deny
      Allow from all
   </Proxy>
 
   # Proxy all requests to /server to Tomcat via AJP
   ProxyPass /server ajp://localhost:8009/server
   ProxyPassReverse /server ajp://localhost:8009/server
 
   # Optionally, also proxy Angular UI (if on same server). This requires "mod_proxy_http"
   #ProxyPass / http://localhost:4000/
   #ProxyPassReverse / http://localhost:4000/
</VirtualHost>


Ejemplo de configuración shibboleth2.xml

Además, aquí hay un ejemplo de configuración "ApplicationOverride" para el archivo "shibboleth2.xml". Esta configuración específica está preparada para utilizar el IdP de prueba proporcionado por https://samltest.id/ y se ofrece solo como referencia. Para habilitarla con fines de prueba, debe especificar ShibRequestSetting applicationId samltest en su configuración de Apach mod_shib (consulte la sección anterior). Un ejemplo adicional, más detallado, está disponible en nuestras configuraciones Docker de "dspace-shibboleth" en https://github.com/DSpace/DSpace/blob/main/dspace/src/main/docker/dspace-shibboleth/shibboleth2.xml

        <!-- *** Sample Shibboleth Settings for  https://samltest.id/  ***     -->
        <!-- This provides a simple sample of how you could configure            -->
        <!-- shibboleth2.xml for DSpace sites.                                   -->
        <!-- TO ENABLE: You'd need to specify "applicationId" as "samltest" in   -->
        <!-- your mod_shib settings, e.g.                                        -->
        <!-- <Location />                                                        -->
        <!--     ...                                                             -->
        <!--     ShibRequestSetting applicationId samltest                       -->
        <!-- </Location>                                                         -->
        <ApplicationOverride id="samltest" entityID="http://[mydspace.edu]/shibboleth" REMOTE_USER="eppn persistent-id targeted-id">

            <!-- We'll use a TEST IdP, hosted by the awesome https://samltest.id/ testing service. -->
            <!-- See also: https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPServiceSSO -->
            <!-- DSPACE 7 requires Shibboleth to use "SameSite=None" property for its Cookies -->
            <Sessions lifetime="28800" timeout="3600" checkAddress="false" relayState="ss:mem" handlerSSL="true" cookieProps="; path=/; SameSite=None; secure; HttpOnly">
               <SSO entityID="https://samltest.id/saml/idp">
                 SAML2 SAML1
               </SSO>
            </Sessions>

            <!-- Loads and trusts a metadata file that describes the IdP and how to communicate with it. -->
            <!-- By default, metadata is retrieved from the TEST IdP at https://samltest.id/ -->
            <!-- and is cached in a local file named "samltest-metadata.xml". -->
            <!-- See also: https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPMetadataProvider -->
            <MetadataProvider type="XML" uri="https://samltest.id/saml/idp"
                          backingFilePath="samltest-metadata.xml" reloadInterval="180000"/>
        </ApplicationOverride>


Ejemplo de configuración attribute-map.xml (para samltest.id)

Para utilizar el ejemplo anterior con https://samltest.id/, también puede ser necesario modificar su archivo attribute-map.xml para admitir los atributos que este servicio proporciona. Nuevamente, se encuentra un ejemplo más completo en nuestras configuraciones Docker de "dspace-shibboleth", disponible en https://github.com/DSpace/DSpace/blob/main/dspace/src/main/docker/dspace-shibboleth/attribute-map.xml

<Attributes xmlns="urn:mace:shibboleth:2.0:attribute-map" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <!-- Custom Attributes specific to samltest.id -->
    <Attribute name="urn:oid:0.9.2342.19200300.100.1.1" id="uid"/>
    <Attribute name="urn:oid:0.9.2342.19200300.100.1.3" id="mail"/>
    <Attribute name="urn:oid:2.5.4.4" id="sn"/>
    <Attribute name="urn:oid:2.16.840.1.113730.3.1.241" id="displayName"/>
    <Attribute name="urn:oid:2.5.4.20" id="telephoneNumber"/>
    <Attribute name="urn:oid:2.5.4.42" id="givenName"/>
    <Attribute name="https://samltest.id/attributes/role" id="role"/>
  
    ...


    <!-- In addition to the attribute mapping, DSpace expects the following Shibboleth Headers to be set:
           - SHIB-NETID
           - SHIB-MAIL
           - SHIB-GIVENNAME
           - SHIB-SURNAME
         These are set by mapping the respective IdP attribute (left hand side) to the header attribute (right hand side).
    -->
    <Attribute name="urn:oid:0.9.2342.19200300.100.1.1" id="SHIB-NETID"/>
    <Attribute name="urn:mace:dir:attribute-def:uid" id="SHIB-NETID"/>
    
    <Attribute name="urn:oid:0.9.2342.19200300.100.1.3" id="SHIB-MAIL"/>
    <Attribute name="urn:mace:dir:attribute-def:mail" id="SHIB-MAIL"/>
    
    <Attribute name="urn:oid:2.5.4.42" id="SHIB-GIVENNAME"/>
    <Attribute name="urn:mace:dir:attribute-def:givenName" id="SHIB-GIVENNAME"/>
    
    <Attribute name="urn:oid:2.5.4.4" id="SHIB-SURNAME"/>
    <Attribute name="urn:mace:dir:attribute-def:sn" id="SHIB-SURNAME"/>


</Attributes>


Opciones de configuración de Shibboleth en DSpace

Métodos de autenticación:

DSpace admite la autenticación mediante NetID o dirección de correo electrónico. El NetID de un usuario es un identificador único proporcionado por el IdP que identifica a un usuario en particular. El NetID puede tener casi cualquier forma, como un número entero único, una cadena de texto, o incluso "identificadores dirigidos" (targeted IDs) en el caso de Shibboleth 2.0. Será necesario coordinar esto con su federación Shibboleth o proveedor de identidad. Existen tres formas de proporcionar información de identidad a DSpace:

1) NetID desde la cabecera de Shibboleth ( recomendado )

El método basado en NetID es preferible porque los usuarios pueden cambiar su dirección de correo electrónico con el proveedor de identidad. Cuando esto sucede, DSpace no podrá asociar su nueva dirección con su cuenta anterior.

2) Dirección de correo electrónico desde la cabecera de Shibboleth ( aceptable )

En caso de que no se encuentre disponible una cabecera con el NetID, DSpace recurrirá a identificar al usuario basándose en su dirección de correo electrónico.

3) Usuario remoto de Tomcat ( menos recomendado )

En caso de que no se encuentren cabeceras de Shibboleth, DSpace recurrirá como último recurso al campo de usuario remoto (remote user) de Tomcat. Esta es la opción menos recomendable, ya que Tomcat no tiene forma de proporcionar atributos adicionales sobre el usuario. Por esta razón, la opción de registro automático (autoregister) no es compatible si se utiliza este método.

Estrategias de migración del esquema de identidad:

Si actualmente está utilizando la autenticación basada en correo electrónico (ya sea el método 1 o 2) y desea actualizar a la autenticación basada en NetID, existe un camino sencillo. Simplemente habilite Shibboleth para que transmita el atributo NetID y configure el parámetro netid-header con el valor correcto. Cuando un usuario intente iniciar sesión en DSpace, primero buscará una cuenta EPerson que tenga el NetID proporcionado. Si no encuentra ninguna, DSpace recurrirá a la autenticación basada en correo electrónico. Entonces, DSpace actualizará el registro de la cuenta EPerson del usuario para asignarle su NetID, de modo que futuras autenticaciones de ese usuario se basen en el NetID. Es importante tener en cuenta que DSpace impide que una cuenta cambie de NetID. Si una cuenta ya tiene asignado un NetID y luego intenta autenticarse con uno diferente, la autenticación fallará.

Metadatos de EPerson:

Uno de los principales beneficios de utilizar autenticación basada en Shibboleth es la posibilidad de recibir atributos adicionales sobre los usuarios, como sus nombres, números de teléfono, e incluso su departamento académico o semestre de graduación, si así se desea. DSpace trata los atributos de nombre y apellido de forma especial, ya que estos (junto con la dirección de correo electrónico) constituyen la información mínima necesaria para crear una nueva cuenta de usuario. Para ambos campos (nombre y apellido), se deben proporcionar mapeos directos a las cabeceras de Shibboleth. Además del nombre y apellido, DSpace permite almacenar otros campos de metadatos, como teléfono, o cualquier otro dato que desee guardar en un objeto eperson. Excepto el campo de teléfono, que es accesible desde la pantalla de perfil del usuario, ninguno de estos campos adicionales de metadatos se utilizará por defecto en DSpace. No obstante, si se desarrollan modificaciones locales, se pueden acceder a estos atributos desde el objeto EPerson. Por ejemplo, el sistema de flujo de trabajo Vireo ETD utiliza esta funcionalidad para ayudar a los estudiantes durante el envío de una tesis (ETD).

Grupos basados en roles:

DSpace es capaz de asignar usuarios a grupos predefinidos en función de los valores recibidos desde Shibboleth. Mediante esta opción, por ejemplo, puede colocar a todos los miembros del profesorado dentro de un grupo de DSpace cuando se proporcione el atributo de afiliación correspondiente. Cuando DSpace realiza esta asignación, se los considera 'grupos especiales'. Estos son realmente grupos, pero la pertenencia del usuario a estos grupos no se registra en la base de datos. Cada vez que un usuario se autentica, se le asigna automáticamente el grupo de DSpace predefinido. Por lo tanto, si el usuario pierde su afiliación, en su siguiente inicio de sesión ya no será parte de ese grupo.

Dependiendo del atributo de Shibboleth utilizado en el encabezado role-header, este puede estar "scoped". Scoped es un término en la terminología de Shibboleth que se refiere a identificar el origen de un atributo. Por ejemplo, la afiliación de un estudiante puede codificarse como: "student@tamu.edu". La parte posterior al símbolo @ representa el scope (ámbito), y la parte anterior representa el valor. Usted puede utilizar el valor completo, solo el valor, o solo el scope. Con esta funcionalidad, es posible generar un rol para los estudiantes de una institución que sea diferente al de los estudiantes de otra. O bien, si activa la opción ignore-scope, puede ignorar la institución y agrupar a todos los estudiantes en un mismo grupo.

Los valores extraídos (un usuario puede tener múltiples roles) se utilizarán para determinar en qué grupos se debe colocar al usuario. Los grupos se definen como "authentication-shibboleth.role.<role-name>" que es una lista de grupos de DSpace separados por comas.

Having issues getting Safari working?

In addition to the below settings, you may need to ensure your Shibboleth IdP is trusted by the DSpace backend by adding it to your rest.cors.allowed-origins configuration. This is required for Safari web browsers to work with DSpace's Shibboleth plugin.

For example, if your IdP is https://samltest.id/, then you need to append that URL to the comma-separated list of "allowed-origins" like:

rest.cors.allowed-origins = ${dspace.ui.url}, https://samltest.id

More information on this configuration can be found in the REST API documentation.


Configuration File:

[dspace]/config/modules/authentication-shibboleth.cfg

Property:

authentication-shibboleth.lazysession

Example Value:

authentication-shibboleth.lazysession = true

Informational Note:

Whether to use lazy sessions or active sessions. For more DSpace instances, you will likely want to use lazy sessions. Active sessions will force every user to authenticate via Shibboleth before they can access your DSpace (essentially resulting in a "dark archive").

Property:

authentication-shibboleth.lazysession.loginurl

Example Value:

authentication-shibboleth. lazysession.loginurl = /Shibboleth.sso/Login

Informational Note:

The url to start a shibboleth session (only for lazy sessions). Generally this setting will be "/Shibboleth.sso/Login"

Property:

authentication-shibboleth.lazysession.secure

Example Value:

authentication-shibboleth.lazysession.secure = true

Informational Note:

Force HTTPS when authenticating (only for lazy sessions). Generally this is recommended to be "true".

Property:

authentication-shibboleth.netid-header

Example Value:

authentication-shibboleth.netid-header = SHIB-NETID

Informational Note:

The HTTP header where shibboleth will supply a user's NetID. This HTTP header should be specified as an Attribute within your Shibboleth "attribute-map.xml" configuration file.

Property:

authentication-shibboleth.email-header

Example Value:

authentication-shibboleth.email-header = SHIB-MAIL

Informational Note:

The HTTP header where the shibboleth will supply a user's email address. This HTTP header should be specified as an Attribute within your Shibboleth "attribute-map.xml" configuration file.

Property:

authentication-shibboleth.email-use-tomcat-remote-user

Example Value:

authentication-shibboleth.email-use-tomcat-remote-user = false

Informational Note:

Used when a netid or email headers are not available should Shibboleth authentication fall back to using Tomcat's remote user feature? Generally this is not recommended. See the "Authentication Methods" section above.

Property:

authentication-shibboleth.reconvert.attributes

Example Value authentication-shibboleth.reconvert.attributes = false
Informational Note:Shibboleth attributes are by default UTF-8 encoded. Some servlet container automatically converts the attributes from ISO-8859-1 (latin-1) to UTF-8. As the attributes already were UTF-8 encoded it may be necessary to reconvert them. If you set this property true, DSpace converts all shibboleth attributes retrieved from the servlet container from UTF-8 to ISO-8859-1 and uses the result as if it were UTF-8. This procedure restores the shibboleth attributes if the servlet container wrongly converted them from ISO-8859-1 to UTF-8. Set this true, if you notice character encoding problems within shibboleth attributes.

Property:

authentication-shibboleth.autoregister

Example Value:

authentication-shibboleth.autoregister = true

Informational Note:

Should we allow new users to be registered automatically?

Property:

authentication-shibboleth.sword.compatibility

Example Value:

authentication-shibboleth.sword.compatibility = false

Informational Note:

SWORD compatibility will allow this authentication method to work when using SWORD. SWORD relies on username and password based authentication and is entirely incapable of supporting shibboleth. This option allows you to authenticate username and passwords for SWORD sessions with out adding another authentication method onto the stack. You will need to ensure that a user has a password. One way to do that is to create the user via the create-administrator command line command and then edit their permissions.
WARNING: If you enable this option while ALSO having "PasswordAuthentication" enabled, then you should ensure that "PasswordAuthentication" is listed prior to "ShibAuthentication" in your authentication.cfg file. Otherwise, ShibAuthentication will be used to authenticate all of your users INSTEAD OF PasswordAuthentication.

Property:

authentication-shibboleth.firstname-header

Example Value:

authentication-shibboleth.firstname-header = SHIB_GIVENNAME

Informational Note:

The HTTP header where the shibboleth will supply a user's given name. This HTTP header should be specified as an Attribute within your Shibboleth "attribute-map.xml" configuration file.

Property:

authentication-shibboleth.lastname-header

Example Value:

authentication-shibboleth.lastname-header = SHIB_SN

Informational Note:

The HTTP header where the shibboleth will supply a user's surname. This HTTP header should be specified as an Attribute within your Shibboleth "attribute-map.xml" configuration file.

Property:

authentication-shibboleth.eperson.metadata

Example Value:

authentication-shibboleth.eperson.metadata = \
 SHIB-telephone => phone, \
 SHIB-cn => cn

Informational Note:

Additional user attributes mapping, multiple attributes may be stored for each user. The left side is the Shibboleth-based metadata Header and the right side is the eperson metadata field to map the attribute to.

Property:

authentication-shibboleth.eperson.metadata.autocreate

Example Value:

authentication-shibboleth.eperson.metadata.autocreate = true

Informational Note:

If the eperson metadata field is not found, should it be automatically created?

Property:

authentication-shibboleth.role-header

Example Value:

authentication-shibboleth.role-header = SHIB_SCOPED_AFFILIATION

Informational Note:

The Shibboleth header holding the user's Shibboleth roles. See the "Role-based Groups" section above for more info.

Property:

authentication-shibboleth.role-header.ignore-scope

Example Value:

authentication-shibboleth.role-header.ignore-scope = true

Informational Note:

Whether to ignore roles' scopes (everything after the @ sign for scoped attributes)

Property:

authentication-shibboleth.role-header.ignore-value

Example Value:

authentication-shibboleth.role-header.ignore-value = false

Informational Note:

Whether to ignore roles' values (everything before the @ sign for scoped attributes)

Property:

authentication-shibboleth.role.[affiliation-attribute]

Example Value:

authentication-shibboleth.role.faculty = Faculty, Member
authentication-shibboleth.role.staff = Staff, Member
authentication-shibboleth.role.student = Students, Member

Informational Note:

Mapping of affiliation values to DSpace groups. See the "Role-based Groups" section above for more info.

Property:

authentication-shibboleth.default-roles

Example Value:

authentication-shibboleth.default-roles = GenericUser

Informational Note:

These roles are assumed if no roles were sent by Shibboleth or there was no header with name matching the value of authentication-shibboleth.role_header. May be repeated to provide multiple default roles.

Autenticación LDAP

Introducción a la terminología específica de LDAP

Si no está familiarizado con LDAP, la siguiente introducción a algunos de sus términos puede resultarle útil:

https://stackoverflow.com/questions/18756688/what-are-cn-ou-dc-in-an-ldap-search

Habilitar la autenticación LDAP

Para habilitar la autenticación LDAP, debe asegurarse de que la clase org.dspace.authenticate.LDAPAuthentication esté incluida como uno de los métodos de autenticación en la siguiente configuración:

Configuration File:

[dspace]/config/modules/authentication.cfg

Property:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod

Example Value:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod = org.dspace.authenticate.LDAPAuthentication


Configuración de la autenticación LDAP

Si LDAP está habilitado, los nuevos usuarios podrán registrarse ingresando su nombre de usuario y contraseña sin necesidad de recibir un token de registro. Si los usuarios no tienen un nombre de usuario y contraseña, aún podrán registrarse e iniciar sesión solo con su dirección de correo electrónico, de la misma manera en que lo hacen actualmente.

Si desea otorgar privilegios especiales a los usuarios LDAP, puede crear un método de autenticación apilable que coloque automáticamente a las personas que tienen un netid en un grupo especial. También podría querer asignar privilegios especiales a ciertas direcciones de correo electrónico. Consulte la sección Código de autenticación personalizado más abajo para obtener más información sobre cómo hacerlo.

Asegúrese de que las comas requeridas se escapan en la configuración LDAP

NOTA: A partir de DSpace 6, las comas (,) son ahora un carácter especial en el sistema de configuración. Como algunas configuraciones LDAP pueden contener comas, debe tener cuidado de escapar cualquier coma requerida añadiendo una barra invertida (\) antes de cada coma, por ejemplo "\,". La referencia de configuración para authentication-ldap.cfg se ha actualizado a continuación con ejemplos adicionales.

A continuación se ofrece una explicación de cada uno de los diferentes parámetros de configuración de LDAP:

Configuration File:

[dspace]/config/modules/authentication-ldap.cfg

Property:

authentication-ldap.enable

Example Value:

authentication-ldap.enable = false

Informational Note:

This setting will enable or disable LDAP authentication in DSpace. With the setting off, users will be required to register and login with their email address. With this setting on, users will be able to login and register with their LDAP user ids and passwords.

Property:

authentication-ldap.autoregister

Example Value:

authentication-ldap.autoregister = true

Informational Note:

This will turn LDAP autoregistration on or off. With this on, a new EPerson object will be created for any user who successfully authenticates against the LDAP server when they first login. With this setting off, the user must first register to get an EPerson object by entering their ldap username and password and filling out the forms.

Property:

authentication-ldap.provider_url

Example Value:

authentication-ldap.provider_url = ldap://ldap.myu.edu/o=myu.edu\,ou=mydept

Informational Note:

This is the url to your institution's LDAP server. You may or may not need the /o=myu.edu part at the end. Your server may also require the ldaps:// protocol. (This field has no default value)

NOTE: As of DSpace 6, commas (,) are now a special character in the Configuration system. Therefore, be careful to escape any required commas in this configuration by adding a backslash (\) before each comma, e.g. "\,"

Property:

authentication-ldap.starttls

Example Value:authentication-ldap. starttls = false
Informational Note:

Should we issue StartTLS after establishing TCP connection in order to initiate an encrypted connection?
Note: This (TLS) is different from LDAPS:

  • TLS is a tunnel for plain LDAP and is typically recognized on the same port (standard LDAP port: 389)
  • LDAPS is a separate protocol, deprecated in favor of the standard TLS method . (standard LDAPS port: 636)

Property:

authentication-ldap.id_field

Example Value:

authentication-ldap.id_field = uid

Explanation:

This is the unique identifier field in the LDAP directory where the username is stored. (This field has no default value)

Property:

authentication-ldap.object_context

Example Value:

authentication-ldap.object_context = ou=people\,o=myu.edu

Informational Note:

This is the LDAP object context to use when authenticating the user. By default, DSpace will use this value to create the user's DN in order to attempt to authenticate them. It is appended to the id_field and username. For example uid=username\,ou=people\,o=myu.edu. You will need to modify this to match your LDAP configuration. (This field has no default value)

If your users do NOT all exist under a single "object_context" in LDAP, then you should ignore this setting and INSTEAD use the Hierarchical LDAP Authentication settings below (especially see "search.user" or "search.anonymous")

NOTE: As of DSpace 6, commas (,) are now a special character in the Configuration system. Therefore, be careful to escape any required commas in this configuration by adding a backslash (\) before each comma, e.g. "\,"

Property:

authentication-ldap.search_context

Example Value:

authentication-ldap.search_context = ou=people

Informational Note:

This is the search context used when looking up a user's LDAP object to retrieve their data for autoregistering. With autoregister=true, when a user authenticates without an EPerson object we search the LDAP directory to get their name (id_field) and email address (email_field) so that we can create one for them. So after we have authenticated against uid=username,ou=people,o=byu.edu we now search in ou=people for filtering on [uid=username]. Often the search_context is the same as the object_context parameter. But again this depends on your LDAP server configuration. (This field has no default value, and it MUST be specified when either search.anonymous=true or search.user is specified)

NOTE: As of DSpace 6, commas (,) are now a special character in the Configuration system. Therefore, be careful to escape any required commas in this configuration by adding a backslash (\) before each comma, e.g. "\,"

Property:

authentication-ldap.email_field

Example Value:

authentication-ldap.email_field = mail

Informational Note:

This is the LDAP object field where the user's email address is stored. "mail" is the most common for LDAP servers. (This field has no default value)

If the "email_field" is unspecified, or the user has no email address in LDAP, his/her username (id_field value) will be saved as the email in DSpace (or appended to netid_email_domain, when specified)

Property: authentication-ldap.netid_email_domain
Example Value: authentication-ldap.netid_email_domain = @example.com
Informational Note:

If your LDAP server does not hold an email address for a user (i.e. no email_field), you can use the following field to specify your email domain. This value is appended to the netid (id_field) in order to make an email address (which is then stored in the DSpace EPerson). For example, a netid of 'user' and netid_email_domain as @example.com would set the email of the user to be user@example.com

Please note: this field will only be used if "email_field" is unspecified OR the user in question has no email address stored in LDAP. If both "email_field" and "netid_email_domain" are unspecified, then the "id_field" will be used as the email address.

Property:

authentication-ldap.surname_field

Example Value:

authentication-ldap.surname_field = sn

Informational Note:

This is the LDAP object field where the user's last name is stored. "sn" is the most common for LDAP servers. If the field is not found the field will be left blank in the new eperson object. (This field has no default value)

Property:

authentication-ldap. givenname_field

Example Value:

authentication-ldap.givenname_field = givenName

Informational Note:

This is the LDAP object field where the user's given names are stored. I'm not sure how common the givenName field is in different LDAP instances. If the field is not found the field will be left blank in the new eperson object. (This field has no default value)

Property:

authentication-ldap.phone_field

Example Value:

authentication-ldap.phone_field = telephoneNumber

Informational Note:

This is the field where the user's phone number is stored in the LDAP directory. If the field is not found the field will be left blank in the new eperson object. (This field has no default value)

Property:

authentication-ldap.login.specialgroup

Example Value:

authentication-ldap.login.specialgroup = group-name

Informational Note:

If specified, all user sessions successfully logged in via LDAP will automatically become members of this DSpace Group (for the remainder of their current, logged in session). This DSpace Group must already exist (it will not be automatically created).
This is useful if you want a DSpace Group made up of all internal authenticated users. This DSpace Group can then be used to bestow special permissions on any users who have authenticated via LDAP (e.g. you could allow anyone authenticated via LDAP to view special, on campus only collections or similar)

Property:
login.groupmap.*
Example Value: authentication-ldap.login.groupmap.1 = ou=Students:ALL_STUDENTS
authentication-ldap.login.groupmap.2 = ou=Employees:ALL_EMPLOYEES
authentication-ldap.login.groupmap.3 = ou=Faculty:ALL_FACULTY
Informational Note:

The left part of the value (before the ":") must correspond to a portion of a user's DN (unless "login.group.attribute" is specified..please see below). The right part of the value corresponds to the name of an existing DSpace group.

For example, if the authenticated user's DN in LDAP is in the following form:

cn=jdoe,OU=Students,OU=Users,dc=example,dc=edu

that user would get assigned to the ALL_STUDENTS DSpace group for the remainder of their current session.

However, if that same user later graduates and is employed by the university, their DN in LDAP may change to:

cn=jdoe,OU=Employees,OU=Users,dc=example,dc=edu

Upon logging into DSpace after that DN change, the authenticated user would now be assigned to the ALL_EMPLOYEES DSpace group for the remainder of their current session.

Note: This option can be used independently from the login.specialgroup option, which will put all LDAP users into a single DSpace group. Both options may be used together.

Property: authentication-ldap. login.groupmap.attribute
Example Value: authentication-ldap. login.groupmap.attribute = group
Informational Note:

The value of the "authentication-ldap.login.groupmap.attribute" should specify the name of a single LDAP attribute. If this property is uncommented, it changes the meaning of the left part of " authentication-ldap.login.groupmap.*" (see above) as follows:

  • If the authenticated user has this LDAP attribute, look up the value of this LDAP attribute in the left part (before the ":") of the authentication-ldap.login.groupmap.* value
  • If that LDAP value is found in any " authentication-ldap.login.groupmap.*" field, assign this authenticated user to the DSpace Group specified by the right part (after the ":") of the authentication-ldap.login.groupmap.* value.

For example:

  • authentication-ldap.login.groupmap.attribute = group
  • authentication-ldap.login.groupmap.1 = mathematics:Mathematics_Group

The above would ensure that any authenticated users where their LDAP "group" attribute equals "mathematics" would be added to the DSpace Group named "Mathematics_Group" for the remainder of their current session. However, if that same user logged in later with a new LDAP "group" value of "computer science", he/she would no longer be a member of the "Mathematics_Group" in DSpace.

Depuración de la conexión y configuración LDAP

Dado que cada LDAP es diferente, configurar su instancia de DSpace para que se comunique con su LDAP puede ser un desafío. Se recomienda utilizar herramientas externas de LDAP para probar la conexión, el nombre de usuario, la contraseña y realizar búsquedas de prueba, con el fin de comprender mejor qué información devuelve su servidor LDAP local. Esto ayudará a que la configuración de LDAP se realice de forma más fluida.

Un ejemplo de herramienta LDAP es el comando de línea de comandos ldapsearch , disponible en la mayoría de los sistemas operativos Linux (por ejemplo, en Debian/Ubuntu está incluido en el paquete ldap-utils). A continuación, se muestran algunos ejemplos de comandos ldapsearch que pueden utilizarse para determinar y/o depurar configuraciones específicas en su archivo authentication-ldap.cfg. En los siguientes ejemplos, se han utilizado los nombres de configuraciones específicas de DSpace como marcadores de posición (entre corchetes).

# Basic anonymous connection (for VERBOSE, add -v)
ldapsearch -x -H [provider_url]
  
# Debug a connection error (add -d-1)
# If you are connecting to an LDAPS URL and see connection errors (e.g. "peer cert untrusted or revoked")
# then see below note about "SSL Connection Errors"
ldapsearch -x -H [provider_url] -d-1


# Attempt to connect to [provider_url] as [search.user] (will prompt for search.user's password)
# This doesn't actually perform a query, just ensures that authentication is working
# NOTE: "search.user" is USUALLY either the full user DN (e.g. "cn=dspaceadmin,ou=people,o=myu.edu")
# or "DOMAIN\USERNAME" (e.g. "MYU\DSpaceUser"). The latter is more likely with Windows Active Directory
ldapsearch -x -H [provider_url] -D [search.user] -W


# Attempt to list the first 100 users in a given [search_context], returning the "cn", "mail" and "sn" fields for each
ldapsearch -x -H [provider_url] -D [search.user] -W -b [search_context] -z 100 cn mail sn  


# Attempt to find the first 100 users whose [id_field] starts with the letter "t", returning the [id_field], "cn", "mail" and "sn" fields for each
ldapsearch -x -H [provider_url] -D [search.user] -W -b [search_context] -z 100 -s sub "([id_field]=t*)" [id_field] cn mail sn


Errores de conexión SSL: Si está utilizando ldapsearch con una conexión LDAPS (conexión segura), puede recibir errores como "peer cert untrusted or revoked" si el certificado SSL del servidor LDAP es autofirmado. Puede indicarle temporalmente a LDAP que acepte cualquier certificado de seguridad estableciendo TLS_REQCERT allow en el archivo ldap.conf utilizado por ldapsearch. ¡Asegúrese de eliminar esta configuración una vez que haya terminado con las pruebas!

# FOR TESTING ONLY! This setting disables the check for a valid LDAP Server security certificate,
# which is considered a security issue for production LDAP setups. Setting this to "allow" tells
# the LDAP client to accept any security certificates that it cannot verify or validate.
TLS_REQCERT allow

Puede encontrar más información sobre esta solución temporal para SSL en:

Habilitación de la autenticación LDAP jerárquica

Tenga en cuenta que DSpace ya no contiene la clase LDAPHierarchicalAuthentication. Esta funcionalidad ahora está soportada por LDAPAuthentication, que utiliza las mismas opciones de configuración.

Si sus usuarios están distribuidos a lo largo de un árbol jerárquico en su servidor LDAP, puede que desee que DSpace busque el nombre de usuario dentro de ese árbol. Así es como funciona:

  1. DSpace obtiene el nombre de usuario desde el formulario de inicio de sesión.
  2. DSpace se conecta a LDAP como un usuario administrativo con permisos para buscar en los DNs (también es posible configurar LDAP para permitir búsquedas anónimas).
  3. DSpace realiza una búsqueda del nombre de usuario dentro de los DNs (el nombre de usuario es parte del DN completo).
  4. DSpace se enlaza utilizando el DN completo encontrado y la contraseña ingresada en el formulario de inicio de sesión.
  5. DSpace permite el inicio de sesión si LDAP reporta una autenticación exitosa; de lo contrario, deniega el acceso.

Configuración de la autenticación LDAP jerárquica

La autenticación LDAP jerárquica comparte todas las configuraciones estándar de LDAP mencionadas anteriormente, pero incluye algunas configuraciones adicionales.

Opcionalmente, puede especificar el alcance de búsqueda. Si el acceso anónimo no está habilitado en su servidor LDAP, deberá especificar el DN completo y la contraseña de un usuario que tenga permisos para enlazarse (bind) y realizar búsquedas de usuarios.

Configuration File:

[dspace]/config/modules/authentication-ldap.cfg

Property:

authentication-ldap.search_scope

Example Value:

authentication-ldap.search_scope = 2

Informational Note:

This is the search scope value for the LDAP search during autoregistering ( autoregister=true ) . This will depend on your LDAP server setup, and is only really necessary i f your users are spread out across a hierarchical tree on your LDAP server . This value must be one of the following integers corresponding to the following values:
object scope : 0
one level scope : 1
subtree scope : 2

Please note that "search_context" in the LDAP configurations must also be specified.

Property:

authentication-ldap.search.anonymous

Example Value:

authentication-ldap.search.anonymous = true

Informational Note:

If true, DSpace will anonymously search LDAP (in the "search_context") for the DN of the user trying to login to DSpace. This setting is "false" by default. By default, DSpace will either use "search.user" to authenticate for the LDAP search (if search.user is specified), or will use the " object_context " value to create the user's DN.

Property:

authentication-ldap.search.user
authentication-ldap.search.password

Example Value:

authentication-ldap.search.user = cn=admin\,ou=people\,o=myu.edu
authentication-ldap.search.password = password

Informational Note:

The full DN and password of a user allowed to connect to the LDAP server and search (in the " search_context ") for the DN of the user trying to login. By default, if unspecified, DSpace will either search LDAP anonymously for the user's DN (when search.anonymous=true ), or will use the " object_context " value to create the user's DN.

NOTE: As of DSpace 6, commas (,) are now a special character in the Configuration system. Therefore, be careful to escape any required commas in this configuration by adding a backslash (\) before each comma, e.g. "\,"

Autenticación ORCID

Habilitación de la autenticación ORCID

Habilitar la autenticación ORCID también requiere habilitar las Entidades Configurables y los Perfiles de Investigador

Para habilitar la autenticación ORCID, consulte la documentación sobre cómo habilitar la integración con ORCID. No es necesario habilitar la sincronización con ORCID, pero actualmente sí debe habilitar los Perfiles de Investigador y las Entidades Configurables.

Autenticación IP

Habilitación de la autenticación IP

Para habilitar la autenticación por IP, debe asegurarse de que la clase org.dspace.authenticate.IPAuthentication esté incluida como uno de los métodos de autenticación en la siguiente configuración:

Configuration File:

[dspace]/config/modules/authentication.cfg

Property:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod

Example Value:

plugin.sequence.org.dspace.authenticate.AuthenticationMethod = org.dspace.authenticate.IPAuthentication

Configuración de la autenticación por IP

Configuration File:

[dspace]/config/modules/authentication-ip.cfg

Una vez habilitada, podrá asignar grupos de DSpace a direcciones IP en el archivo authentication-ip.cfg, estableciendo la propiedad de la siguiente manera: ip.NOMBRE_DEL_GRUPO = rangoIP[, rangoIP ...], por ejemplo:

authentication-ip.MY_UNIVERSITY = 10.1.2.3, \                  # Full IP
13.5, \                      # Partial IP
11.3.4.5/24, \               # with CIDR
12.7.8.9/255.255.128.0, \    # with netmask
2001:18e8::32                # IPv6 too

Se pueden establecer coincidencias negativas anteponiendo un guion (-) a la entrada. Por ejemplo, si desea incluir toda una red clase B excepto los usuarios de una subred clase C contenida, podría usar: 111.222,-111.222.333.

Notas:

  • Si el nombre del grupo contiene espacios, debe escapar los espacios con una barra invertida (\), por ejemplo: "Department\ of\ Statistics"
  • Si su instalación de DSpace está detrás de un proxy web, recuerde establecer la opción de configuración useProxies dentro de la sección 'Logging' de dspace.cfg, para que se utilice la dirección IP del usuario en lugar de la dirección IP del servidor proxy.

Autenticación mediante certificado X.509

Habilitación de la autenticación mediante certificado X.509

El método de autenticación X.509 utiliza un certificado X.509 enviado por el cliente para establecer su identidad. Requiere que el cliente tenga instalado en su navegador (u otro software cliente) un certificado web personal emitido por una Autoridad Certificadora (CA) reconocida por el servidor web.

  1. Consulta las instrucciones de instalación de HTTPS para configurar tu servidor web. Si estás utilizando HTTPS con Tomcat, ten en cuenta que la etiqueta <Connector> debe incluir el atributo clientAuth="true" para que el servidor solicite un certificado web personal al cliente.
  2. Agrega primero el plugin org.dspace.authenticate.X509Authentication a la lista de métodos de autenticación apilables en el valor de la clave de configuración plugin.sequence.org.dspace.authenticate.AuthenticationMethod

    Configuration File:

    [dspace]/config/modules/authentication.cfg

    Property:

    plugin.sequence.org.dspace.authenticate.AuthenticationMethod

    Example Value:

    plugin.sequence.org.dspace.authenticate.AuthenticationMethod = org.dspace.authenticate.X509Authentication
    plugin.sequence.org.dspace.authenticate.AuthenticationMethod = org.dspace.authenticate.PasswordAuthentication

Configuración de la autenticación mediante certificado X.509

Configuration File:

[dspace]/config/modules/authentication-x509.cfg

  1. También debes configurar DSpace con los mismos certificados de Autoridad Certificadora (CA) que el servidor web, para que pueda aceptar e interpretar los certificados de los clientes. Puede compartir el mismo archivo de almacén de claves (keystore) que el servidor web, utilizar uno separado o un archivo que contenga únicamente el certificado de la CA. Configúralo mediante uno de estos métodos, ya sea usando el almacén de claves de Java.

    authentication-x509.keystore.path =  path to Java keystore file
    authentication-x509.keystore.password =  password to access the keystore

    ...o el archivo de certificado de CA por separado (en formato PEM o DER):

    authentication-x509.ca.cert =  path to certificate file for CA whose client certs to accept.
  2. Elige si deseas habilitar el registro automático: Si deseas que los usuarios que se autentican correctamente se registren automáticamente como nuevos E-Persons en caso de que aún no lo estén, establece la propiedad de configuración autoregister en true. Esto permite aceptar automáticamente a todos los usuarios con certificados personales válidos. El valor predeterminado es false.

PENDIENTE: documentar las propiedades restantes de authentication-x509.*.

Ejemplo de un método de autenticación personalizado

También se incluye en el código fuente una implementación de un método de autenticación utilizado en el MIT, edu.mit.dspace.MITSpecialGroup. Este método no auténtica realmente a un usuario, sino que solo agrega la sesión del usuario actual a un grupo especial (dinámico) llamado 'MIT Users' (¡el cual debe estar presente en el sistema!). Esto nos permite crear políticas de autorización para usuarios del MIT sin tener que mantener manualmente la membresía del grupo 'MIT Users'.

Al mantener este código en un método separado, podemos personalizar el proceso de autenticación para el MIT simplemente agregándole a la pila en la configuración de DSpace. No es necesario modificar ningún código.

Puedes crear tu propio método de autenticación personalizado y agregarlo a la pila. Utiliza como modelo el método existente más similar, por ejemplo, org.dspace.authenticate.PasswordAuthentication para un método "explícito" (con credenciales ingresadas interactivamente) o org.dspace.authenticate.X509Authentication para un método implícito.


  • No labels