首页
/ 在Caddy Security中实现Microsoft Entra ID认证集成

在Caddy Security中实现Microsoft Entra ID认证集成

2025-07-09 03:55:32作者:胡唯隽

背景介绍

Caddy Security是一个为Caddy服务器提供强大安全功能的插件,它支持多种认证方式,包括OAuth2协议。本文将详细介绍如何在Caddy Security中配置Microsoft Entra ID(原Azure AD)作为身份提供商,实现企业级单点登录功能。

核心配置解析

基础配置结构

要实现Microsoft Entra ID认证,首先需要在Caddyfile中配置security块,包含三个主要部分:

  1. OAuth身份提供商配置:定义与Microsoft Entra ID的连接参数
  2. 认证门户配置:设置认证流程和JWT令牌
  3. 授权策略配置:定义访问控制规则

Microsoft Entra ID提供商配置

security {
    oauth identity provider azure {
        realm azure
        driver azure
        tenant_id tttttttt-tttt-tttt-tttt-tttttttttttt
        client_id cccccccc-cccc-cccc-cccc-cccccccccccc
        client_secret Please-Enter-Your-Client-Secret-Here
        scopes openid email profile
        enable id_token_cookie azure_token
    }
}

关键参数说明:

  • tenant_id: Microsoft Entra ID租户ID
  • client_id: 注册应用的客户端ID
  • client_secret: 应用密钥
  • scopes: 请求的权限范围,通常需要openidemailprofile
  • id_token_cookie: 启用将Azure令牌存储在cookie中

认证门户配置

authentication portal oauthportal {
    crypto key key1 sign from file /etc/caddy/jwt/sign_key1.pem
    crypto key key1 verify from file /etc/caddy/jwt/verify_key1.pem
    crypto default token lifetime 36000
    enable identity provider azure
    cookie lifetime 36000
    cookie path /
    
    transform user {
        match realm azure
        action add role authp/user
    }
}

这里使用了RSA密钥对(推荐RS512算法)来签名和验证JWT令牌。transform user块用于在认证成功后为用户添加角色。

授权策略配置

authorization policy oauthpolicy {
    crypto key key1 sign from file /etc/caddy/jwt/sign_key1.pem
    crypto key key1 verify from file /etc/caddy/jwt/verify_key1.pem
    allow roles authp/user
    validate bearer header
    inject headers with claims
}

此策略配置了:

  • 使用相同的RSA密钥验证令牌
  • 只允许具有authp/user角色的用户访问
  • 验证Bearer令牌
  • 将声明注入请求头

站点集成配置

在站点配置中,需要设置两个主要路由:

  1. 认证路由:处理所有认证相关的请求
@authportal {
    path /portal
    path /auth
    path /portal/*
    path /auth/*
    path /logout
    path /logout/*
}
route @authportal {
    authenticate with oauthportal
}
  1. 受保护资源路由:应用授权策略保护站点内容
route {
    authorize with oauthpolicy
    file_server {
        root /srv/admin
        index index.html index.htm
        precompressed zstd gzip
    }
}

高级技巧

令牌声明映射

虽然当前版本不支持直接从Azure令牌映射字段到Caddy JWT,但可以通过以下方式间接实现:

  1. 在反向代理后端解析azure_token cookie获取原始Azure令牌
  2. 使用自定义中间件提取所需字段
  3. 将这些字段作为自定义头传递给后端应用

缓存控制

对于需要认证的HTML内容,建议禁用缓存以避免安全问题:

@htmFiles {
    path *.html
    path *.htm
    path /
}
header @htmFiles {
    -Etag
    -Last-Modified
    -Expires
    Cache-Control: "no-store, no-cache, must-revalidate, max-age=0"
    defer
}

安全最佳实践

  1. 始终使用HTTPS保护所有通信
  2. 定期轮换客户端密钥和JWT签名密钥
  3. 设置合理的令牌生命周期(示例中为36000秒/10小时)
  4. 使用强密码算法(推荐RS512而非HS256)
  5. 限制cookie的作用路径和域

通过以上配置,企业可以轻松地将Microsoft Entra ID集成到Caddy服务器中,实现安全、可靠的单点登录解决方案,同时保持对后端应用的无缝集成。

登录后查看全文
热门项目推荐
相关项目推荐