跳到主要内容
给我们的新朋友:

Logto 是一个为现代应用和 SaaS 产品设计的 Auth0 替代方案。它提供 Cloud开源 服务,帮助你快速启动身份和管理 (IAM) 系统。享受认证 (Authentication)、授权 (Authorization) 和多租户管理 一体化

我们建议从 Logto Cloud 上的免费开发租户开始。这可以让你轻松探索所有功能。

在本文中,我们将介绍使用 GoLogto 快速构建 Microsoft Entra ID SAML enterprise SSO 登录体验(用户认证 (Authentication))的步骤。

先决条件

  • 一个正在运行的 Logto 实例。查看 介绍页面 以开始。
  • Go 的基本知识。
  • 一个可用的 Microsoft Entra ID SAML enterprise SSO 账户。

Create an application in Logto

Logto 基于 OpenID Connect (OIDC) 认证 (Authentication) 和 OAuth 2.0 授权 (Authorization)。它支持跨多个应用程序的联合身份管理,通常称为单点登录 (SSO)。

要创建你的 传统 Web 应用程序,只需按照以下步骤操作:

  1. 打开 Logto Console。在“开始使用”部分,点击“查看全部”链接以打开应用程序框架列表。或者,你可以导航到 Logto Console > Applications,然后点击“创建应用程序”按钮。 开始使用
  2. 在打开的模态窗口中,点击“传统 Web”部分,或使用左侧的快速过滤复选框过滤所有可用的“传统 Web”框架。点击 "Go" 框架卡片以开始创建你的应用程序。 框架
  3. 输入应用程序名称,例如“Bookstore”,然后点击“创建应用程序”。

🎉 太棒了!你刚刚在 Logto 中创建了你的第一个应用程序。你将看到一个祝贺页面,其中包含详细的集成指南。按照指南查看你的应用程序中的体验将会是什么样的。

Integrate Go SDK

提示:
  • 以下演示基于 Gin Web Framework 构建。你也可以通过相同的步骤将 Logto 集成到其他框架中。
  • Go 示例项目可在我们的 Go SDK 仓库 中找到。

安装

在项目根目录执行:

go get github.com/logto-io/go

github.com/logto-io/go/client 包添加到你的应用代码中:

main.go
// main.go
package main

import (
"github.com/gin-gonic/gin"
// 添加依赖
"github.com/logto-io/go/client"
)

func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
c.String(200, "Hello Logto!")
})
router.Run(":3000")
}

创建会话存储

在传统的 Web 应用程序中,用户认证信息会存储在用户会话中。

Logto SDK 提供了一个 Storage 接口,你可以根据你的 Web 框架实现一个 Storage 适配器,以便 Logto SDK 可以将用户认证信息存储在会话中。

备注:

我们不推荐使用基于 Cookie 的会话,因为 Logto 存储的用户认证信息可能会超过 Cookie 的大小限制。在这个例子中,我们使用基于内存的会话。你可以在生产环境中使用 Redis、MongoDB 和其他技术根据需要存储会话。

Logto SDK 中的 Storage 类型如下:

github.com/logto-io/client/storage.go
package client

type Storage interface {
GetItem(key string) string
SetItem(key, value string)
}

我们使用 github.com/gin-contrib/sessions 中间件作为示例来演示这个过程。

将中间件应用到应用程序中,以便我们可以在路由处理程序中通过用户请求上下文获取用户会话:

main.go
package main

import (
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/memstore"
"github.com/gin-gonic/gin"
"github.com/logto-io/go/client"
)

func main() {
router := gin.Default()

// 在这个例子中我们使用基于内存的会话
store := memstore.NewStore([]byte("your session secret"))
router.Use(sessions.Sessions("logto-session", store))

router.GET("/", func(ctx *gin.Context) {
// 获取用户会话
session := sessions.Default(ctx)
// ...
ctx.String(200, "Hello Logto!")
})
router.Run(":3000")
}

创建一个 session_storage.go 文件,定义一个 SessionStorage 并实现 Logto SDK 的 Storage 接口:

session_storage.go
package main

import (
"github.com/gin-contrib/sessions"
)

type SessionStorage struct {
session sessions.Session
}

func (storage *SessionStorage) GetItem(key string) string {
value := storage.session.Get(key)
if value == nil {
return ""
}
return value.(string)
}

func (storage *SessionStorage) SetItem(key, value string) {
storage.session.Set(key, value)
storage.session.Save()
}

现在,在路由处理程序中,你可以为 Logto 创建一个会话存储:

session := sessions.Default(ctx)
sessionStorage := &SessionStorage{session: session}

初始化 LogtoClient

首先,创建一个 Logto 配置:

main.go
func main() {
// ...
logtoConfig := &client.LogtoConfig{
Endpoint: "<your-logto-endpoint>", // 例如 http://localhost:3001
AppId: "<your-application-id>",
AppSecret: "<your-application-secret>",
}
// ...
}
提示:

你可以在管理控制台的应用详情页面找到并复制“应用密钥”:

App Secret

然后,你可以为每个用户请求使用上述 Logto 配置创建一个 LogtoClient

main.go
func main() {
// ...

router.GET("/", func(ctx *gin.Context) {
// 创建 LogtoClient
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(
logtoConfig,
&SessionStorage{session: session},
)

// 使用 Logto 控制主页内容
authState := "你尚未登录此网站。:("

if logtoClient.IsAuthenticated() {
authState = "你已登录此网站!:)"
}

homePage := `<h1>Hello Logto</h1>` +
"<div>" + authState + "</div>"

ctx.Data(http.StatusOK, "text/html; charset=utf-8", []byte(homePage))
})

// ...
}

实现登录路由

在配置好重定向 URI 后,我们添加一个 sign-in 路由来处理登录请求,并在主页上添加一个登录链接:

main.go
func main() {
// ...

// 在主页上添加一个链接以执行登录请求
router.GET("/", func(ctx *gin.Context) {
// ...
homePage := `<h1>Hello Logto</h1>` +
"<div>" + authState + "</div>" +
// 添加链接
`<div><a href="/sign-in">Sign In</a></div>`

ctx.Data(http.StatusOK, "text/html; charset=utf-8", []byte(homePage))
})

// 添加一个路由来处理登录请求
router.GET("/sign-in", func(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(
logtoConfig,
&SessionStorage{session: session},
)

// 登录请求由 Logto 处理。
// 用户登录后将被重定向到重定向 URI。
signInUri, err := logtoClient.SignIn("http://localhost:3000/callback")
if err != nil {
ctx.String(http.StatusInternalServerError, err.Error())
return
}

// 将用户重定向到 Logto 登录页面。
ctx.Redirect(http.StatusTemporaryRedirect, signInUri)
})

// ...
}

现在,当用户访问 http://localhost:3000/sign-in 时,用户将被重定向到 Logto 登录页面。

实现回调路由

当用户在 Logto 登录页面成功登录后,Logto 将把用户重定向到重定向 URI。

由于重定向 URI 是 http://localhost:3000/callback,我们添加 /callback 路由来处理登录后的回调。

main.go
func main() {
// ...

// 添加一个路由来处理登录回调请求
router.GET("/callback", func(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(
logtoConfig,
&SessionStorage{session: session},
)

// 登录回调请求由 Logto 处理
err := logtoClient.HandleSignInCallback(ctx.Request)
if err != nil {
ctx.String(http.StatusInternalServerError, err.Error())
return
}

// 跳转到开发者指定的页面。
// 本例将用户带回主页。
ctx.Redirect(http.StatusTemporaryRedirect, "/")
})

// ...
}

实现登出路由

与登录流程类似,当用户登出时,Logto 将会重定向用户到登出后的重定向 URI。

现在,让我们添加 sign-out 路由来处理登出请求,并在主页上添加一个登出链接:

main.go
func main() {
// ...

// 在主页上添加一个链接以执行登出请求
router.GET("/", func(ctx *gin.Context) {
// ...
homePage := `<h1>Hello Logto</h1>` +
"<div>" + authState + "</div>" +
`<div><a href="/sign-in">Sign In</a></div>` +
// 添加链接
`<div><a href="/sign-out">Sign Out</a></div>`

ctx.Data(http.StatusOK, "text/html; charset=utf-8", []byte(homePage))
})

// 添加一个路由来处理登出请求
router.GET("/sign-out", func(ctx *gin.Context) {
session := sessions.Default(ctx)
logtoClient := client.NewLogtoClient(
logtoConfig,
&SessionStorage{session: session},
)

// 登出请求由 Logto 处理。
// 用户登出后将被重定向到登出后的重定向 URI。
signOutUri, signOutErr := logtoClient.SignOut("http://localhost:3000")

if signOutErr != nil {
ctx.String(http.StatusOK, signOutErr.Error())
return
}

ctx.Redirect(http.StatusTemporaryRedirect, signOutUri)
})

// ...
}

用户发起登出请求后,Logto 将清除会话中的所有用户认证信息。

检查点:测试你的应用程序

现在,你可以测试你的应用程序:

  1. 运行你的应用程序,你将看到登录按钮。
  2. 点击登录按钮,SDK 将初始化登录过程并将你重定向到 Logto 登录页面。
  3. 登录后,你将被重定向回你的应用程序,并看到登出按钮。
  4. 点击登出按钮以清除令牌存储并登出。

Add Microsoft Entra ID SAML enterprise SSO connector

To simplify access management and gain enterprise-level safeguards for your big clients, connect with Go as a federated identity provider. The Logto enterprise SSO connector helps you establish this connection in minutes by allowing several parameter inputs.

To add an enterprise SSO connector, simply follow these steps:

  1. Navigate to Logto console > Enterprise SSO.

SSO page

  1. Click "Add enterprise connector" button and choose your SSO provider type. Choose from prebuilt connectors for Microsoft Entra ID (Azure AD), Google Workspace, and Okta, or create a custom SSO connection using the standard OpenID Connect (OIDC) or SAML protocol.
  2. Provide a unique name (e.g., SSO sign-in for Acme Company).

Select your SSO provider

  1. Configure the connection with your IdP in the "Connection" tab. Check the guides above for each connector types.

SSO connection

  1. Customize the SSO experience and enterprise’s email domain in the "Experience" tab. Users sign in with the SSO-enabled email domain will be redirected to SSO authentication.

SSO experience

  1. Save changes.

Set up Azure AD SSO 应用程序

步骤 1:创建 Azure AD 单点登录 (SSO) 应用程序

开始 Azure AD 单点登录 (SSO) 集成,首先在 Azure AD 端创建一个 SSO 应用程序。

  1. 访问 Azure 门户 并以管理员身份登录。
  2. 选择 Microsoft Entra ID 服务。
  3. 使用侧边菜单导航到 企业应用程序。点击 新建应用程序,然后选择 创建你自己的应用程序

Azure AD create application.webp

  1. 输入应用程序名称并选择 集成任何其他在库中找不到的应用程序(非库)
  2. 选择 设置单点登录 > SAML

Azure AD set up SSO.webp

  1. 按照说明进行操作,第一步,你需要使用 Logto 提供的以下信息填写基本的 SAML 配置。

Azure AD SP config

  • 受众 (Audience) URI(SP 实体 ID):它表示为你的 Logto 服务的全局唯一标识符,在向身份提供商 (IdP) 发送认证请求时作为 SP 的 EntityId。此标识符对于在 IdP 和 Logto 之间安全交换 SAML 断言和其他认证相关数据至关重要。
  • ACS URL:断言消费者服务 (ACS) URL 是通过 POST 请求发送 SAML 断言的位置。此 URL 由 IdP 用于将 SAML 断言发送到 Logto。它充当回调 URL,Logto 期望在此接收和消费包含用户身份信息的 SAML 响应。

点击 保存 以继续。

步骤 2:在 Logto 配置 SAML 单点登录 (SSO)

要使 SAML 单点登录 (SSO) 集成正常工作,你需要将 IdP 元数据提供给 Logto。让我们切换回 Logto 端,导航到你的 Azure AD SSO 连接器的 Connection 选项卡。

Logto 提供了三种不同的方法来配置 IdP 元数据。最简单的方法是提供 Azure AD SSO 应用程序的 metadata URL

从你的 Azure AD SSO 应用程序的 SAML Certificates section 中复制 App Federation Metadata Url,并将其粘贴到 Logto 的 Metadata URL 字段中。

Azure AD Metadata URL.webp

Logto 将从该 URL 获取元数据,并自动配置 SAML 单点登录 (SSO) 集成。

步骤 3:配置用户属性映射

Logto 提供了一种灵活的方法,将从身份提供商 (IdP) 返回的用户属性映射到 Logto 中的用户属性。Logto 默认会从 IdP 同步以下用户属性:

  • id:用户的唯一标识符。Logto 将从 SAML 响应中读取 nameID 声明作为用户 SSO 身份 id。
  • email:用户的电子邮件地址。Logto 默认将从 SAML 响应中读取 email 声明作为用户的主电子邮件。
  • name:用户的姓名。

你可以在 Azure AD 端或 Logto 端管理用户属性映射逻辑。

  1. 在 Logto 端将 AzureAD 用户属性映射到 Logto 用户属性。

    访问你的 Azure AD SSO 应用程序的 Attributes & Claims 部分。

    复制以下属性名称(带有命名空间前缀)并粘贴到 Logto 中的相应字段。

    • http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress
    • http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name(建议:将此属性值映射更新为 user.displayname 以获得更好的用户体验)

Azure AD 默认属性映射.webp

  1. 在 AzureAD 端将 AzureAD 用户属性映射到 Logto 用户属性。

    访问你的 Azure AD SSO 应用程序的 Attributes & Claims 部分。

    点击 Edit,并根据 Logto 用户属性设置更新 Additional claims 字段:

    • 根据 Logto 用户属性设置更新声明名称值。
    • 移除命名空间前缀。
    • 点击 Save 继续。

    最终应得到以下设置:

Azure AD_Logto 属性映射.webp

你还可以在 Azure AD 端指定其他用户属性。Logto 将在用户的 sso_identity 字段下记录从 IdP 返回的原始用户属性。

步骤 4:将用户分配到 Azure AD 单点登录 (SSO) 应用程序

访问 Azure AD SSO 应用程序的 Users and groups 部分。点击 Add user/group 将用户分配到 Azure AD SSO 应用程序。只有分配到你的 Azure AD SSO 应用程序的用户才能通过 Azure AD SSO 连接器进行认证 (Authentication)。

Azure AD assign users.webp

步骤 5:设置电子邮件域并启用 SSO 连接器

在 Logto 的连接器 SSO 体验 选项卡中提供你组织的 电子邮件域。这将启用 SSO 连接器作为这些用户的认证 (Authentication) 方法。

具有指定域电子邮件地址的用户将被重定向使用 SAML SSO 连接器作为他们唯一的认证 (Authentication) 方法。

请查看 Azure AD 的官方文档以获取有关 Azure AD SSO 集成的更多详细信息。

Save your configuration

仔细检查你是否在 Logto 连接器配置区域填写了必要的值。点击“保存并完成”(或“保存更改”),Microsoft Entra ID SAML enterprise SSO 连接器现在应该可用了。

Enable Microsoft Entra ID SAML enterprise SSO connector in Sign-in Experience

You don’t need to configure enterprise connectors individually, Logto simplifies SSO integration into your applications with just one click.

  1. Navigate to: Console > Sign-in experience > Sign-up and sign-in.
  2. Enable the "Enterprise SSO" toggle.
  3. Save changes.

Once enabled, a "Single Sign-On" button will appear on your sign-in page. Enterprise users with SSO-enabled email domains can access your services using their enterprise identity providers (IdPs).

Auto detect SSO sign-in via email domain Navigate to SSO sign-in via manually click link button

To learn more about the SSO user experience, including SP-initiated SSO and IdP-initiated SSO, refer to User flows: Enterprise SSO.

Testing and Validation

返回到你的 Go 应用。你现在应该可以使用 Microsoft Entra ID SAML enterprise SSO 登录了。享受吧!

Further readings

终端用户流程:Logto 提供开箱即用的认证 (Authentication) 流程,包括多因素认证 (MFA) 和企业单点登录 (SSO),以及强大的 API,用于灵活实现账户设置、安全验证和多租户体验。

授权 (Authorization):授权 (Authorization) 定义了用户在被认证 (Authentication) 后可以执行的操作或访问的资源。探索如何保护你的 API 以用于原生和单页应用程序,并实现基于角色的访问控制 (RBAC)。

组织 (Organizations):在多租户 SaaS 和 B2B 应用中特别有效,组织功能支持租户创建、成员管理、组织级 RBAC 和即时供应。

客户 IAM 系列:我们关于客户(或消费者)身份和访问管理的系列博客文章,从 101 到高级主题及更深入的内容。