Golang实现Microsoft身份认证方案

Golang实现Microsoft身份认证方案 您好,

我是一名年轻的开发者,正在尝试为我的项目创建一个用于 Microsoft 身份验证的 Go Web 服务。我在寻找合适的包时遇到了很多困难,尤其是在新旧版本之间,以及像 github.com/AzureAD/microsoft-authentication-library-for-go v0.9.0 这样带有警告下划线的需求。我对此不太理解,需要有人为我指明正确的方向。

感谢您的善意帮助。

1 回复

更多关于Golang实现Microsoft身份认证方案的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


对于在Go中实现Microsoft身份验证,推荐使用官方的github.com/AzureAD/microsoft-authentication-library-for-go(MSAL Go)。虽然你看到v0.9.0有警告下划线,但这通常是Go模块版本管理的正常现象。以下是具体实现方案:

1. 安装MSAL Go包

go get github.com/AzureAD/microsoft-authentication-library-for-go/apps

2. 客户端凭证流示例(后台服务)

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/AzureAD/microsoft-authentication-library-for-go/apps/confidential"
)

func main() {
    clientID := "<your-client-id>"
    clientSecret := "<your-client-secret>"
    authority := "https://login.microsoftonline.com/<your-tenant-id>"
    scopes := []string{"https://graph.microsoft.com/.default"}
    
    cred, err := confidential.NewCredFromSecret(clientSecret)
    if err != nil {
        log.Fatal(err)
    }
    
    app, err := confidential.New(
        authority,
        clientID,
        cred,
        confidential.WithCache(nil))
    if err != nil {
        log.Fatal(err)
    }
    
    result, err := app.AcquireTokenSilent(
        context.Background(),
        scopes)
    if err != nil {
        result, err = app.AcquireTokenByCredential(
            context.Background(),
            scopes)
        if err != nil {
            log.Fatal(err)
        }
    }
    
    fmt.Printf("Access Token: %s\n", result.AccessToken)
}

3. 授权码流示例(Web应用)

func handleAuthCodeFlow() {
    clientID := "<your-client-id>"
    clientSecret := "<your-client-secret>"
    redirectURI := "http://localhost:8080/auth/callback"
    authority := "https://login.microsoftonline.com/<your-tenant-id>"
    
    cred, _ := confidential.NewCredFromSecret(clientSecret)
    
    app, _ := confidential.New(
        authority,
        clientID,
        cred,
        confidential.WithRedirectURI(redirectURI))
    
    // 生成授权URL
    authURL, _ := app.AuthCodeURL(
        context.Background(),
        "<your-client-id>",
        redirectURI,
        []string{"User.Read"},
        confidential.WithState("<state-value>"))
    
    // 处理回调并获取令牌
    code := "<authorization-code-from-callback>"
    result, _ := app.AcquireTokenByAuthCode(
        context.Background(),
        code,
        redirectURI,
        []string{"User.Read"})
    
    fmt.Printf("ID Token: %s\n", result.IDToken)
}

4. 令牌验证中间件示例

import (
    "net/http"
    
    "github.com/AzureAD/microsoft-authentication-library-for-go/apps/public"
)

func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        authHeader := r.Header.Get("Authorization")
        if authHeader == "" {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }
        
        // 实际项目中应使用令牌验证库
        // 例如:github.com/golang-jwt/jwt 进行JWT验证
        next.ServeHTTP(w, r)
    })
}

关键配置说明:

  • clientID: Azure应用注册中的应用ID
  • tenantID: Azure租户ID(或使用organizationscommon
  • 权限配置需在Azure门户中正确设置API权限

包版本说明: 当前稳定版本为v1.x.x,建议使用最新版本:

go get github.com/AzureAD/microsoft-authentication-library-for-go@latest

这个方案支持OAuth 2.0和OpenID Connect,覆盖了从后台服务到Web应用的身份验证场景。

回到顶部