Herramientas de usuario

Herramientas del sitio


informatica:software:aplicaciones_web:authelia

¡Esta es una revisión vieja del documento!


Authelia

Aplicación web que proporciona un servidor y portal para la autenticación y autorización. Ofrece doble factor de autenticación (2FA) y Single Sign-On (SSO) para nuestras aplicaciones web mediante un portal. Compañero ideal de los proxies inversos.

Instalación

Docker

Ejemplo de docker-compose.yml para usar con Docker Compose:

---
services:
  authelia:
    image: authelia/authelia
    container_name: authelia
    user: 1000:1000
    volumes:
      - ./config:/config
    expose:
      - 9091
    environment:
      - TZ=Europe/Madrid
    restart: unless-stopped

Crearemos la carpeta config con los siguientes ficheros en su interior:

  • configuration.yml: base de la configuración de Authelia.
  • users.yml: base de datos con los usuarios que tendrán acceso a través de Authelia.

Configuración

Ejemplo de fichero configuration.yml:

###############################################################################
#                           Authelia Configuration                            #
###############################################################################

theme: auto 

jwt_secret: B0346B15DD27774E98C1E4E82562BFDB2081E8CB66C78751983380B0F1211F3C
 
# Opcional:
# default_redirection_url: https://public.midominio.com/

server:
  host: 0.0.0.0
  port: 9091

log:
  level: debug
  file_path: /config/authelia.%d.log
 
# Uso de contraseña única basada en tiempo como segundo factor de autenticación (2FA)
totp:
  disable: false
  algorithm: sha1
  issuer: tempwin.net
  digits: 6
  period: 30
  skew: 1
  secret_size: 32
 
# Uso de clave a través del navegador como segundo factor de autenticación (2FA)
webauthn:
  disable: false
  display_name: Authelia
  attestation_conveyance_preference: indirect
  user_verification: preferred
  timeout: 60s

authentication_backend:
  file:
    path: /config/users.yml 
    password:
      algorithm: argon2
      argon2:
        variant: argon2id
        iterations: 3
        memory: 65536
        parallelism: 4
        key_length: 32
        salt_length: 16

access_control:
  default_policy: deny
  rules:
    - domain: authelia.midominio.com
      policy: bypass
    - domain: sub1.midominio.com
      policy: one_factor
    - domain: 
      - sub3.midominio.com
      - sub4.midominio.com
      - sub5.midominio.com
      policy: two_factor
 
# Cookies de sesión
session:
  name: authelia_session
  domain: midominio.com
  secret: B0346B15DD27774E98C1E4E82562BFDB2081E8CB66C78751983380B0F1211F3C
  expiration: 1h
  inactivity: 5m
  remember_me_duration:  1M # 1 mes  
 
 
# Authelia puede bloquear temporalmente cuentas cuando hay demasiados intentos
# de autenticación. Esto ayuda a prevenir ataques de fuerza bruta.
regulation:
  max_retries: 3
  find_time: 10m
  ban_time: 12h
 
# Configuración del almacenamiento SQL 
# (para guardar preferencias de usuario, logs, dispositivos 2FA...)
storage:
  encryption_key: NzVCcCDh6HlEyRxbgxUpEwWsauf7xe8qrtNfUs0gKVMVTp5gNwKsfHvrd3Cjxs74
  local:
    path: /config/db.sqlite3 
  
notifier:
  disable_startup_check: true
  smtp:
    host: smtp.servidor.com
    port: 587
    username: usuario
    password: contraseña
    sender: noreply@authelia.midominio.com
    subject: "[Authelia] {title}"
  • jwt_secret: el secreto a usar para generar tokens JWT cuando se valida por e-mail. Al menos 64 caracteres alfanuméricos aleatorios. Se puede hacer de varias maneras:
    • Con OpenSSL: openssl rand -hex 32
    • Usando esta web
    • Usando una utilidad de la imagen Docker de Authelia: docker run --rm authelia/authelia:latest authelia crypto rand --length 64 --charset alphanumeric
  • default_redirection_url: dominio que usamos para nuestro servidor de Authelia
  • access_control: subdominios que queremos gestionar con Authelia. Las políticas a establecer en rules son:
    • bypass: permite el tráfico sin solicitar nada.
    • one_factor: requiere iniciar sesión con las credenciales de Authelia.
    • two_factor: además de las credenciales de Authelia, se requiere OTP (One-time password).
  • session:
    • secret: secreto complejo de al menos 16 caracteres.
    • domain: dominio base al que pertenecen los subdominios que vamos a gestionar con Authelia.
  • storage:
    • encryption_key: la clave de cifrado para ofuscar la información a registrar en la base de datos.Al menos 64 caracteres alfanuméricos aleatorios. Ver la opción jwt_secret para saber cómo generarla.
  • notifier: datos con nuestro servidor de correo. Si no está bien configurado, no podremos activar el 2FA.

Siempre que se modifique el fichero de configuración (para añadir nuevos dominios, por ejemplo) es necesario reiniciar el contenedor. Lo más fácil es docker compose restart

La configuración se puede validar antes de aplicar mediante el binario:

authelia validate-config --config configuration.yml

Usuarios

Ejemplo de fichero users.yml:

---
###############################################################
#                         Users Database                      #
###############################################################
users:
  pepito:
    disabled: false
    displayname: "Pepito"
    password: "$argon2id$v=19$m=65536,t=3,p=4$VxEGhnJdr1BrNGzljw5123A$w1YEUhfBqTiA93l3ADlzigjLgeS6c1iPUXi5IvCCw4g"
    email: pepito.grillo@example.com
    groups:
      - admins
      - dev

Dentro del bloque users podemos definir tantos usuarios como queramos.

La contraseña no debe ser en texto plano sino estar cifrada. Podemos usar un pequeño script que proporciona la propia imagen de Docker de Authelia:

docker run --rm authelia/authelia:latest authelia hash-password -- 'nuestra_contraseña'

Devolverá algo commo:

Digest: $argon2id$v=19$m=65536,t=3,p=4$KzRQdnFKVGxrcFNwRGNheA$Gf4geiNHilF5IE/X1oIyIOQA1ePbICrMbtXKY3Sji7g

Lo que va a continuación de Digest: es lo que tendremos que ponerlo en el campo password.

Por último, el correo debe ser válido, ya que para activar el 2FA se enviará un mail de activación. Los grupos se pueden dejar como están, porque es para configuraciones más avanzadas.

Integración con Nginx

Para integrar Authelia con el proxy inverso Nginx, aplicaremos la siguiente configuración a nivel del virtual host que vamos a proteger con Authelia:

set $upstream_authelia http://authelia:9091/api/verify;

## Virtual endpoint created by nginx to forward auth requests.
location /authelia {
    ## Essential Proxy Configuration
    internal;
    proxy_pass $upstream_authelia;

    ## Headers
    ## The headers starting with X-* are required.
    proxy_set_header X-Original-URL $scheme://$http_host$request_uri;
    proxy_set_header X-Original-Method $request_method;
    proxy_set_header X-Forwarded-Method $request_method;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $http_host;
    proxy_set_header X-Forwarded-Uri $request_uri;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Content-Length "";
    proxy_set_header Connection "";

    ## Basic Proxy Configuration
    proxy_pass_request_body off;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503; # Timeout if the real server is dead
    proxy_redirect http:// $scheme://;
    proxy_http_version 1.1;
    proxy_cache_bypass $cookie_session;
    proxy_no_cache $cookie_session;
    proxy_buffers 4 32k;
    client_body_buffer_size 128k;

    ## Advanced Proxy Configuration
    send_timeout 5m;
    proxy_read_timeout 240;
    proxy_send_timeout 240;
    proxy_connect_timeout 240;
}

## Send a subrequest to Authelia to verify if the user is authenticated and has permission to access the resource.
auth_request /authelia;

## Set the $target_url variable based on the original request.

## Comment this line if you're using nginx without the http_set_misc module.
set_escape_uri $target_url $scheme://$http_host$request_uri;

## Uncomment this line if you're using NGINX without the http_set_misc module.
# set $target_url $scheme://$http_host$request_uri;

## Save the upstream response headers from Authelia to variables.
auth_request_set $user $upstream_http_remote_user;
auth_request_set $groups $upstream_http_remote_groups;
auth_request_set $name $upstream_http_remote_name;
auth_request_set $email $upstream_http_remote_email;

## Inject the response headers from the variables into the request made to the backend.
proxy_set_header Remote-User $user;
proxy_set_header Remote-Groups $groups;
proxy_set_header Remote-Name $name;
proxy_set_header Remote-Email $email;

## If the subreqest returns 200 pass to the backend, if the subrequest returns 401 redirect to the portal.
error_page 401 =302 https://auth.example.com/?rd=$target_url;

Se da por hecho que:

  • Authelia está accesible por el proceso de Nginx con el nombre de host authelia en el puerto 9091(la URL sería http://authelia:9091). Adaptar a nuestro caso particular.
  • La URL a la que quieres acceder a través de Authelia es https://auth.example.com. Adaptar a nuestro caso particular.

Usando la imagen de docker nginx-proxy

Si el servicio que queremos proteger con Authelia es https://app.midominio.com, tenemos que crear un fichero llamado como el dominio (app.midominio.com) en la carpeta /etc/nginx/vhost.d/ del contenedor con el siguiente contenido:

## Start of configuration add by letsencrypt container
location ^~ /.well-known/acme-challenge/ {
    auth_basic off;
    auth_request off;
    allow all;
    root /usr/share/nginx/html;
    try_files $uri =404;
    break;
}
## End of configuration add by letsencrypt container
## Virtual endpoint created by nginx to forward auth requests.
location /authelia {
    ## Essential Proxy Configuration
    internal;
    proxy_pass http://authelia:9091/api/verify;

    ## Headers
    ## The headers starting with X-* are required.
    proxy_set_header X-Original-URL $scheme://$http_host$request_uri;
    proxy_set_header X-Forwarded-Method $request_method;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $http_host;
    proxy_set_header X-Forwarded-Uri $request_uri;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Content-Length "";
    proxy_set_header Connection "";

    ## Basic Proxy Configuration
    proxy_pass_request_body off;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503; # Timeout if the real server is dead
    proxy_redirect http:// $scheme://;
    proxy_http_version 1.1;
    proxy_cache_bypass $cookie_session;
    proxy_no_cache $cookie_session;
    proxy_buffers 4 32k;
    client_body_buffer_size 128k;

    ## Advanced Proxy Configuration
    send_timeout 5m;
    proxy_read_timeout 240;
    proxy_send_timeout 240;
    proxy_connect_timeout 240;
}

## Send a subrequest to Authelia to verify if the user is authenticated and has permission to access the resource.
auth_request /authelia;

## Set the $target_url variable based on the original request.

## Comment this line if you're using nginx without the http_set_misc module.
#set_escape_uri $target_url $scheme://$http_host$request_uri;

## Uncomment this line if you're using NGINX without the http_set_misc module.
set $target_url $scheme://$http_host$request_uri;

## Save the upstream response headers from Authelia to variables.
auth_request_set $user $upstream_http_remote_user;
auth_request_set $groups $upstream_http_remote_groups;
auth_request_set $name $upstream_http_remote_name;
auth_request_set $email $upstream_http_remote_email;

## Inject the response headers from the variables into the request made to the backend.
proxy_set_header Remote-User $user;
proxy_set_header Remote-Groups $groups;
proxy_set_header Remote-Name $name;
proxy_set_header Remote-Email $email;

## If the subreqest returns 200 pass to the backend, if the subrequest returns 401 redirect to the portal.
error_page 401 =302 https://portal.authelia.com/?rd=$target_url;

Donde:

informatica/software/aplicaciones_web/authelia.1700557954.txt.gz · Última modificación: por tempwin