Chuyển đến nội dung chính

Lesson 11: Basic Auth Methods - Token, Userpass and AppRole

Auth Methods overview, Token Auth Method (root tokens, create tokens), Userpass Auth Method (CRUD users, password policies), AppRole Auth Method (RoleID, SecretID, CIDR binding, secret_id_num_uses), response wrapping cho SecretID, AppRole best practices cho CI/CD pipelines.

🔒 DevSecOps — Lesson 11 Lesson 11: Basic Auth Methods - Token, Userpass and AppRole

HashiCorp Vault from Basic to Advanced

Part 3: Auth Methods - Authentication and Authorization

xdev.asia

1. Auth Methods Overview

Auth Methods is the mechanism Vault uses to authenticate clients — determining "who you are" before allowing access to secrets. Each auth method is enabled at a separate path and returns a Vault token after successful authentication.

Authentication process

┌──────────┐   1. Login request      ┌───────────────┐
│  Client  │ ──────────────────────▶ │  Auth Method  │
│          │                         │  (AppRole,    │
│          │   4. Vault Token        │   LDAP, K8s)  │
│          │ ◀────────────────────── │               │
└──────────┘                         └───────┬───────┘
                                             │
                                    2. Verify identity
                                             │
                                    3. Map to policies
                                             ▼
                                     ┌──────────────┐
                                     │   Identity   │
                                     │   + Policies │
                                     └──────────────┘

Types of Auth Methods

GroupAuth MethodObject
Built-inTokenAll clients
HumanUserpass, LDAP, OIDCOperators, developers
MachineAppRole, JWTCI/CD, applications
CloudAWS, Azure, GCPCloud workloads
PlatformKubernetes, SPIFFEContainer workloads

Enable Auth Method

# Enable auth method tại default path
vault auth enable userpass

# Enable tại custom path
vault auth enable -path=company-ldap ldap

# Liệt kê auth methods đã enable
vault auth list

# Disable auth method (cẩn thận - xóa toàn bộ data)
vault auth disable userpass

2. Token Auth Method

Token Auth Method is the only auth method that is always enabled and cannot be disabled. Every other auth method ultimately returns a Vault token. Tokens are the core authentication mechanism of Vault.

Token Types

TypeStoredRenewableChild tokensUse case
Service TokenYes (in storage)YesYesLong-lived operations
Batch TokenNoNoNoHigh-volume, ephemeral

Create tokens

# Tạo token với default policy
vault token create

# Tạo token với policies cụ thể
vault token create \
  -policy="app-readonly" \
  -policy="db-creds" \
  -ttl=1h \
  -display-name="app-service"

# Tạo orphan token (không có parent)
vault token create -orphan \
  -policy="monitoring" \
  -ttl=24h

# Tạo batch token
vault token create \
  -type=batch \
  -policy="app-readonly" \
  -ttl=30m

# Tạo periodic token (không bao giờ expire nếu renew đúng hạn)
vault token create \
  -policy="long-running-service" \
  -period=24h

Root Tokens

Root token has access to the entire Vault. Should only be used in emergencies:

# Tạo root token mới (cần quorum unseal keys)
vault operator generate-root -init
vault operator generate-root \
  -nonce="..." \
  -otp="..."

# Revoke root token sau khi dùng xong
vault token revoke <root-token>

Best practice: Do not store root token. Create when needed, revoke immediately after use.

Token Roles

# Tạo token role cho CI/CD
vault write auth/token/roles/ci-cd \
  allowed_policies="ci-deploy,ci-readonly" \
  disallowed_policies="admin,root" \
  orphan=true \
  renewable=true \
  token_period=1h \
  token_type=service \
  token_bound_cidrs="10.0.0.0/8"

# Tạo token từ role
vault token create -role=ci-cd

Token Accessors

Token accessor allows token management without knowing the token value:

# Lookup token bằng accessor
vault token lookup -accessor <accessor>

# Revoke token bằng accessor
vault token revoke -accessor <accessor>

# Liệt kê tất cả token accessors
vault list auth/token/accessors

3. Userpass Auth Method

Userpass is the simplest auth method for human users — authenticate with username and password. Suitable for small environments or testing.

Enable and configure

# Enable userpass
vault auth enable userpass

# Tạo user với policies
vault write auth/userpass/users/john.doe \
  password="s3cur3P@ssw0rd" \
  policies="dev-readonly,dev-kv" \
  token_ttl=8h \
  token_max_ttl=24h

# Tạo user với CIDR binding
vault write auth/userpass/users/admin.user \
  password="adm1nP@ss" \
  policies="admin" \
  token_ttl=2h \
  token_bound_cidrs="10.10.0.0/16,192.168.1.0/24"

# Liệt kê users
vault list auth/userpass/users

# Đọc thông tin user
vault read auth/userpass/users/john.doe

Login

# Login qua CLI
vault login -method=userpass \
  username=john.doe \
  password="s3cur3P@ssw0rd"

# Login qua API
curl -s --request POST \
  --data '{"password": "s3cur3P@ssw0rd"}' \
  ${VAULT_ADDR}/v1/auth/userpass/login/john.doe | jq .

Password Policies

Vault 1.5+ supports password policies to enforce password complexity:

# Tạo password policy
vault write sys/policies/password/strong-password policy=-<<EOF
length=20
rule "charset" {
  charset = "abcdefghijklmnopqrstuvwxyz"
  min-chars = 2
}
rule "charset" {
  charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  min-chars = 2
}
rule "charset" {
  charset = "0123456789"
  min-chars = 2
}
rule "charset" {
  charset = "!@#$%^&*()-_=+[]{}|;:,.<>?"
  min-chars = 2
}
EOF

# Sinh password theo policy
vault read sys/policies/password/strong-password/generate

# Áp dụng password policy cho userpass
vault write auth/userpass/users/secure.user \
  password="$(vault read -field=password sys/policies/password/strong-password/generate)" \
  policies="dev-readonly"

Update and delete user

# Cập nhật password
vault write auth/userpass/users/john.doe \
  password="n3wP@ssw0rd!"

# Cập nhật policies (không thay đổi password)
vault write auth/userpass/users/john.doe/policies \
  policies="dev-readonly,dev-kv,staging-deploy"

# Xóa user
vault delete auth/userpass/users/john.doe

4. AppRole Auth Method

AppRole is the auth method designed for machine-to-machine authentication. This is the most common method for applications and CI/CD pipelines to authenticate with Vault.

Khái niệm cốt lõi

┌─────────────────────────────────────────────────────────┐
│                     AppRole Login                       │
│                                                         │
│   RoleID (public identifier)                            │
│   + SecretID (private credential)                       │
│   = Vault Token (with assigned policies)                │
│                                                         │
│   Tương tự: username + password = session token         │
└─────────────────────────────────────────────────────────┘
ElementDescriptionSimilar
RoleIDrole public identifierUsername
SecretIDSecret Credential, short termPassword

Enable and create Role

# Enable AppRole
vault auth enable approle

# Tạo role cho web application
vault write auth/approle/role/webapp \
  token_policies="webapp-policy,db-readonly" \
  token_ttl=1h \
  token_max_ttl=4h \
  secret_id_ttl=30m \
  secret_id_num_uses=1 \
  token_num_uses=0 \
  bind_secret_id=true

# Tạo role cho CI/CD pipeline
vault write auth/approle/role/cicd-pipeline \
  token_policies="cicd-deploy" \
  token_ttl=30m \
  token_max_ttl=1h \
  secret_id_ttl=10m \
  secret_id_num_uses=1 \
  token_num_uses=10 \
  bind_secret_id=true \
  secret_id_bound_cidrs="10.0.0.0/8" \
  token_bound_cidrs="10.0.0.0/8"

Important parameters

ParameterDescriptionRecommendation
secret_id_ttlTTL of SecretIDThe shorter the better (5-30m)
secret_id_num_usesNumber of times SecretID is used1 (one-time use)
token_ttlToken default TTLSufficient for operation
token_max_ttlMaximum TTL (including renewal)Reasonable limit
token_num_usesNumber of times token used0 = unlimited
secret_id_bound_cidrsCIDR allows use of SecretIDRestrict by network
token_bound_cidrsCIDR allows token useRestrict by network

Login Process

# Bước 1: Lấy RoleID (thường được bake vào config/image)
vault read auth/approle/role/webapp/role-id
# role_id    db02de05-fa39-4855-059b-67f86261c393

# Bước 2: Sinh SecretID (thường do trusted orchestrator sinh)
vault write -f auth/approle/role/webapp/secret-id
# secret_id           6a174c20-f6de-a53c-74d2-6018fcceff64
# secret_id_accessor  c454f7e5-996e-7230-6074-6ef26b7bcf86

# Bước 3: Login
vault write auth/approle/login \
  role_id="db02de05-fa39-4855-059b-67f86261c393" \
  secret_id="6a174c20-f6de-a53c-74d2-6018fcceff64"

Response Wrapping cho SecretID

Response wrapping is an important security mechanism — the SecretID is "wrapped" in a short-term wrapping token. Only the target application can unwrap:

# Sinh SecretID với response wrapping (TTL 120 giây)
vault write -wrap-ttl=120s -f auth/approle/role/webapp/secret-id

# Response chứa wrapping_token thay vì secret_id trực tiếp
# wrapping_token:           hvs.CAES...
# wrapping_accessor:        ...
# wrapping_token_ttl:       2m
# wrapping_token_creation_time: ...

# Application unwrap để lấy SecretID thật
vault unwrap hvs.CAES...
# secret_id    6a174c20-f6de-a53c-74d2-6018fcceff64

# Nếu ai đó đã unwrap trước → lỗi (phát hiện MITM)
vault unwrap hvs.CAES...
# Error: wrapping token is not valid or does not exist

Attack detection

If wrapping token was unwrapped by attacker before application:

  • Application will receive error when unwrap → alert immediately

  • Check audit log to find attacker's source IP

  • Revoke role and re-issue credentials

5. AppRole Best Practices cho CI/CD

GitHub Actions

# .github/workflows/deploy.yml
name: Deploy with Vault
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Import Secrets from Vault
        uses: hashicorp/vault-action@v3
        with:
          url: https://vault.company.com
          method: approle
          roleId: ${{ secrets.VAULT_ROLE_ID }}
          secretId: ${{ secrets.VAULT_SECRET_ID }}
          secrets: |
            secret/data/production/db username | DB_USERNAME ;
            secret/data/production/db password | DB_PASSWORD ;
            secret/data/production/api key | API_KEY

      - name: Deploy application
        run: |
          echo "Deploying with secrets..."
          ./deploy.sh
        env:
          DB_USERNAME: ${{ env.DB_USERNAME }}
          DB_PASSWORD: ${{ env.DB_PASSWORD }}

GitLab CI

# .gitlab-ci.yml
stages:
  - deploy

deploy-production:
  stage: deploy
  image: hashicorp/vault:1.21
  variables:
    VAULT_ADDR: "https://vault.company.com"
  script:
    - |
      # Login với AppRole
      VAULT_TOKEN=$(vault write -field=token auth/approle/login \
        role_id="${VAULT_ROLE_ID}" \
        secret_id="${VAULT_SECRET_ID}")
      export VAULT_TOKEN

      # Lấy secrets
      DB_PASSWORD=$(vault kv get -field=password secret/production/db)
      export DB_PASSWORD

      # Deploy
      ./deploy.sh
  only:
    - main

Jenkins Pipeline

// Jenkinsfile
pipeline {
    agent any

    environment {
        VAULT_ADDR = 'https://vault.company.com'
    }

    stages {
        stage('Get Secrets') {
            steps {
                withVault(
                    configuration: [
                        vaultUrl: "${VAULT_ADDR}",
                        vaultCredentialId: 'vault-approle'
                    ],
                    vaultSecrets: [
                        [
                            path: 'secret/production/db',
                            secretValues: [
                                [envVar: 'DB_USER', vaultKey: 'username'],
                                [envVar: 'DB_PASS', vaultKey: 'password']
                            ]
                        ]
                    ]
                ) {
                    sh './deploy.sh'
                }
            }
        }
    }
}

6. AppRole Deployment Pattern

Trusted Orchestrator Pattern

┌──────────────┐                    ┌──────────────┐
│  Terraform/  │  1. Sinh SecretID  │    Vault     │
│  Ansible     │ ──────────────────▶│              │
│ (Orchestrator)│◀──────────────────│              │
│              │  2. Wrapped token  │              │
└──────┬───────┘                    └──────────────┘
       │
       │ 3. Deliver wrapped token
       ▼
┌──────────────┐                    ┌──────────────┐
│  Application │  4. Unwrap →       │    Vault     │
│              │     SecretID       │              │
│              │  5. Login          │              │
│              │     (RoleID +      │              │
│              │      SecretID)     │              │
│              │  6. Vault Token    │              │
└──────────────┘                    └──────────────┘
  1. RoleID is baked into the AMI/Docker image or config management

  2. SecretID generated by trusted orchestrator (Terraform, Ansible, CI/CD)

  3. SecretID is delivered as wrapped token for security

  4. Application unwrap to get SecretID, then login with RoleID + SecretID

Pull vs Push model

ModelHow it worksAdvantagesDisadvantages
PullApp self-login to Vault, get secretsApp to control lifecycleApps need to know Vault
PushOrchestrator injects secrets into appApp doesn't need to know VaultSecrets in env/file

7. Security Auth Methods

Common mistakes

  • ❌ Use root token in application

  • ❌ SecretID has too long TTL or unlimited uses

  • ❌ Do not set CIDR binding for AppRole

  • ❌ Hardcode RoleID + SecretID trong source code

  • ❌ Use userpass for machine authentication

Best practices compiled

  • ✅ SecretID: num_uses=1, ttl=5m-30m

  • ✅ Always use response wrapping for SecretID

  • ✅ Set secret_id_bound_cidrs and token_bound_cidrs

  • ✅ Each application/service has its own role

  • ✅ Revoke root token after using

  • ✅ Enable audit logging to track all authentication

8. Summary

In this article, we have learned the 3 most basic auth methods of Vault:

  • Token Auth — platform auth method, every auth method generates token

  • Userpass Auth — simple for human users, supports password policies

  • AppRole Auth — standard for machine authentication, supporting CI/CD workflows

AppRole with response wrapping is the most recommended pattern for CI/CD pipelines. In the next article, we will learn about LDAP, OIDC and JWT Auth Methods — enterprise authentication methods for both human and machine identities.