Saltar al contenido principal

Autenticación Stellar (SEP-10)

Resumen

SEP-10 (Stellar Web Authentication) permite que las aplicaciones de billetera creen sesiones autenticadas con los anchors de Stellar al demostrar el control sobre una cuenta Stellar. Una vez autenticadas, las billeteras reciben un JSON Web Token (JWT) que usan en solicitudes posteriores a los servicios estandarizados del anchor.

Para la especificación completa, consulta SEP-0010: Stellar Web Authentication.

La Plataforma Anchor implementa SEP-10 con soporte para:

  • Flujo Challenge/Response: GET /auth para solicitar un desafío, POST /auth para validar y recibir un JWT
  • Atribución del Cliente: Verificación opcional de la identidad de la aplicación cliente para billeteras no custodiales
  • Soporte para Billeteras Custodiales: Soporte para billeteras custodiales que gestionan cuentas de usuario
  • Múltiples Dominios Home: Soporte para múltiples dominios y patrones comodín

Flujo Típico de Autenticación

  1. El Cliente solicita un desafío único al Servidor
  2. El Cliente verifica y firma el desafío
  3. El Cliente envía el desafío firmado al Servidor
  4. El Servidor verifica el desafío y responde con un token de sesión JWT

Habilitar SEP-10

Para habilitar SEP-10, configura las siguientes variables de entorno en tu archivo dev.env.

# dev.env
SEP10_ENABLED=true
SEP10_HOME_DOMAINS=localhost:8080
SECRET_SEP10_SIGNING_SEED="a Stellar private key"
SECRET_SEP10_JWT_SECRET="a secret encryption key"

Configuración Requerida (Si está habilitado)

VariableValor predeterminadoDescripción
SEP10_ENABLEDfalseEstablece en true para habilitar la autenticación SEP-10
SEP10_HOME_DOMAINSlocalhost:8080Lista de dominios home (separados por comas). Soporta patrones comodín como *.stellar.org. El home_domain debe coincidir con el host donde se sirve tu archivo stellar.toml.
SECRET_SEP10_SIGNING_SEEDRequeridoLa clave privada correspondiente a la SIGNING_KEY en tu archivo stellar.toml. Se usa para firmar los desafíos de autenticación. Las billeteras verifican esta firma antes de firmar y devolver el desafío.
SECRET_SEP10_JWT_SECRETRequeridoLa clave de cifrado utilizada para firmar y verificar los tokens JWT emitidos a billeteras autenticadas.
important

La SIGNING_KEY en tu archivo stellar.toml debe ser la clave pública derivada de SECRET_SEP10_SIGNING_SEED. Las billeteras verificarán que las transacciones de desafío están firmadas con esta clave.

Configuración Opcional

# dev.env
# Optional: Specify web_auth_domain (default: first home_domain if only one is specified)
SEP10_WEB_AUTH_DOMAIN=localhost:8080

# Optional: Challenge transaction timeout in seconds (default: 900)
SEP10_AUTH_TIMEOUT=900

# Optional: JWT token timeout in seconds (default: 86400 = 24 hours)
SEP10_JWT_TIMEOUT=86400

# Optional: Require Authorization header in GET /auth requests (default: false)
SEP10_REQUIRE_AUTH_HEADER=false

# Optional: Client attribution requirement (default: false)
SEP10_CLIENT_ATTRIBUTION_REQUIRED=false

# Optional: Client allow list (default: empty, all configured clients allowed)
# Comma-separated list of client names that are allowed to authenticate
SEP10_CLIENT_ALLOW_LIST=client1,client2
VariableValor predeterminadoDescripción
SEP10_WEB_AUTH_DOMAINPrimer home_domain si se especifica solo uno, de lo contrario vacíoLa propiedad web_auth_domain usada en las respuestas SEP-10. Requerido si tienes múltiples home_domains o usas patrones comodín. Debe coincidir con el host del servidor SEP.
SEP10_AUTH_TIMEOUT900Tiempo en segundos que una transacción de desafío permanece válida. Los clientes deben firmar y enviar el desafío dentro de esta ventana.
SEP10_JWT_TIMEOUT86400Tiempo en segundos que un token JWT emitido permanece válido. Después de la expiración, los clientes deben volver a autenticarse.
SEP10_REQUIRE_AUTH_HEADERfalseSi es true, requiere un encabezado de Autorización válido (Bearer JWT) en las solicitudes GET /auth de desafío. Esto previene el acceso no autorizado al endpoint y es útil para flujos de re-autenticación donde los clientes necesitan actualizar sus tokens JWT.
SEP10_CLIENT_ATTRIBUTION_REQUIREDfalseSi es true, las billeteras no custodiales deben proporcionar un client_domain en las solicitudes de desafío. Requiere configuración del cliente (ver abajo).
SEP10_CLIENT_ALLOW_LISTVacío (todos los clientes configurados permitidos)Lista separada por comas con los nombres de clientes permitidos para autenticarse. Solo relevante cuando SEP10_CLIENT_ATTRIBUTION_REQUIRED=true. Si está vacía, todos los clientes configurados están permitidos.
consejo

Múltiples Dominios Home: Si especificas múltiples home_domains (p. ej., ap.stellar.org,*.sdp.stellar.org), también debes establecer SEP10_WEB_AUTH_DOMAIN para especificar qué dominio aloja el endpoint de autenticación.

Atribución del Cliente

La atribución del cliente te permite restringir la autenticación a aplicaciones de billetera específicas y verificar su identidad. Esta es una función opcional que sólo debe habilitarse si es un requisito empresarial.

información

Por defecto, la Plataforma Anchor permite que cualquiera con una cuenta Stellar pueda autenticarse. La atribución del cliente solo es necesaria si quieres:

  • Restringir la autenticación a aplicaciones de billetera específicas
  • Verificar la identidad de aplicaciones de billetera no custodiales
  • Registrar qué aplicaciones de billetera usan tus usuarios

Habilitar la Atribución del Cliente

# dev.env
SEP10_CLIENT_ATTRIBUTION_REQUIRED=true

Cuando SEP10_CLIENT_ATTRIBUTION_REQUIRED=true, las billeteras no custodiales deben:

  1. Proporcionar un parámetro client_domain en la solicitud de desafío
  2. Firmar la transacción de desafío con la SIGNING_KEY del archivo stellar.toml de ese dominio
  3. Tener su dominio listado en tu configuración de clientes

Configuración del Cliente

Configura los clientes permitidos en tu archivo de configuración YAML:

clients:
# Each item in the list may contain the following fields:
# - name: (required) the name of the client
# - type: (required) `custodial` or `noncustodial`
#
# If the type is `custodial`,
# - signing_keys: (required) the custodial SEP-10 signing key(s) of the client.
# - callback_urls.sep6: (optional) the URL of the client's SEP-6 callback API endpoint.
# - callback_urls.sep24: (optional) the URL of the client's SEP-24 callback API endpoint.
# - callback_urls.sep31: (optional) the URL of the client's SEP-31 callback API endpoint.
# - callback_urls.sep12: (optional) the URL of the client's SEP-12 callback API endpoint.
# - allow_any_destination: (optional) default to false. If set to true, allows any destination for deposits.
# - destination_accounts: (optional) list of accounts allowed to be used for the deposit.
# If allow_any_destination is set to true, this configuration option is ignored.
#
# If the type is `noncustodial`,
# - domains: (required) the domains of the client.
# - callback_urls.sep6: (optional) the URL of the client's SEP-6 callback API endpoint.
# - callback_urls.sep24: (optional) the URL of the client's SEP-24 callback API endpoint.
# - callback_urls.sep31: (optional) the URL of the client's SEP-31 callback API endpoint.
# - callback_urls.sep12: (optional) the URL of the client's SEP-12 callback API endpoint.

# custodial client
- name: bluecorp
type: custodial
signing_keys: "the signing key 1 of bluecorp","the signing key 2 of bluecorp"
callback_urls:
sep6: https://callback.bluecorp.com/api/v1/anchor/callback/sep6
sep12: https://callback.bluecorp.com/api/v1/anchor/callback/sep12
allow_any_destination: false
destination_accounts: GA...

# noncustodial client
- name: pinkcorp
type: noncustodial
domains: pinkcorp.com
callback_urls:
sep6: https://callback.pinkcorp.com/api/v2/anchor/callback/sep6
sep12: https://callback.pinkcorp.com/api/v2/anchor/callback/sep12

- name: redcorp
type: custodial
signing_keys: "the signing key of redcorp",

O configura mediante variables de entorno:

# dev.env
# custodial client
CLIENTS[0]_NAME=bluecorp
CLIENTS[0]_TYPE=custodial
CLIENTS[0]_SIGNING_KEYS="the signing key 1 of bluecorp","the signing key 2 of bluecorp"
CLIENTS[0]_ALLOW_ANY_DESTINATION=false
CLIENTS[0]_DESTINATION_ACCOUNTS=GA...

# noncustodial client
CLIENTS[1]_NAME=pinkcorp
CLIENTS[1]_TYPE=noncustodial
CLIENTS[1]_DOMAINS=pinkcorp.com

# custodial client
CLIENTS[2]_NAME=redcorp
CLIENTS[2]_TYPE=custodial
CLIENTS[2]_SIGNING_KEYS="the signing key of redcorp"

Configurar stellar.toml

Actualiza tu archivo stellar.toml para anunciar soporte SEP-10. Las billeteras descubren tu endpoint de autenticación mediante este archivo.

# dev.stellar.toml
SIGNING_KEY = "add your signing key here (public key from SECRET_SEP10_SIGNING_SEED)"
WEB_AUTH_ENDPOINT = "http://localhost:8080/auth"

Estos campos deben coincidir con las opciones de configuración definidas en la sección Habilitar SEP-10 arriba.

WEB_AUTH_ENDPOINT - La URL donde se ejecuta el servicio de autenticación. Esta es la URL que los clientes usarán para autenticarse con el anchor. El endpoint debe soportar:

  • GET <WEB_AUTH_ENDPOINT> - Solicitar un desafío
  • POST <WEB_AUTH_ENDPOINT> - Intercambiar desafío firmado por un JWT de sesión

SIGNING_KEY - La clave pública correspondiente a la clave privada especificada en SECRET_SEP10_SIGNING_SEED. Esta clave se usa para firmar los desafíos de autenticación presentados a las aplicaciones de billetera.

important
  • SIGNING_KEY: Debe ser la clave pública derivada de SECRET_SEP10_SIGNING_SEED
  • WEB_AUTH_ENDPOINT: Usa https:// en producción. La ruta /auth es el endpoint estándar SEP-10.
  • Coincidencia de Host: El host en WEB_AUTH_ENDPOINT debe coincidir con uno de tus SEP10_HOME_DOMAINS (o el SEP10_WEB_AUTH_DOMAIN si está especificado).

Cómo Probar el Flujo de Autenticación

El flujo de autenticación SEP-10 consta de dos pasos:

  1. GET /auth - Solicitar una transacción desafío

    • Parámetros: account (requerido), memo (opcional), home_domain (opcional), client_domain (opcional)
    • Retorna: Una transacción desafío en formato XDR
  2. POST /auth - Validar el desafío firmado y recibir un JWT

    • Cuerpo: { "transaction": "<signed_challenge_xdr>" }
    • Retorna: { "token": "<jwt_token>" }

El token JWT debe incluirse en las solicitudes API subsecuentes como token Bearer en el encabezado Authorization.

consejo

Probando tu Configuración: Puedes probar la autenticación SEP-10 usando curl y Stellar CLI. Para más información sobre Stellar CLI, consulta la documentación de Stellar CLI.

# Verify if `stellar` command line is installed
stellar --version

# List your Stellar keys/identities
stellar keys ls

# Get your account ID (public key) and secret seed
# Replace 'alice' with your identity name from `stellar keys ls`
IDENTITY_NAME="alice"
ACCOUNT_ID=$(stellar keys public-key "$IDENTITY_NAME")
SECRET_SEED=$(stellar keys secret "$IDENTITY_NAME")

# Step 1: Request challenge and save the transaction XDR
CHALLENGE_RESPONSE=$(curl -s "http://localhost:8080/auth?account=$ACCOUNT_ID")
CHALLENGE_XDR=$(echo "$CHALLENGE_RESPONSE" | jq -r '.transaction')

# Step 2: Sign the challenge transaction using Stellar CLI
# Note: The output includes info messages; the signed XDR is on the last line
SIGNED_CHALLENGE_XDR=$(echo "$CHALLENGE_XDR" | stellar tx sign --sign-with-key "$SECRET_SEED" 2>&1 | tail -1)

# Step 3: Submit the signed challenge and receive JWT token
curl -X POST "http://localhost:8080/auth" \
-H "Content-Type: application/json" \
-d "{\"transaction\": \"$SIGNED_CHALLENGE_XDR\"}"