Add go-redis authentication sample (#23266)

This commit is contained in:
Charles Lowell 2024-08-05 12:54:43 -07:00 коммит произвёл GitHub
Родитель e3b96ce0a4
Коммит 4fb2eb2cfa
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
3 изменённых файлов: 89 добавлений и 0 удалений

Просмотреть файл

@ -0,0 +1,78 @@
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package azidentity_test
import (
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/redis/go-redis/v9"
)
// This example demonstrates how to use azidentity to authenticate a [go-redis] client
// connecting to Azure Cache for Redis. See the [Azure Cache for Redis documentation]
// for information on configuring a cache to use Entra ID authentication.
//
// [Azure Cache for Redis documentation]: https://learn.microsoft.com/azure/azure-cache-for-redis/cache-azure-active-directory-for-authentication
// [go-redis]: https://pkg.go.dev/github.com/redis/go-redis/v9
func Example_redis() {
credential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
// TODO: handle error
}
client := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:6380", "TODO: redis host"),
CredentialsProviderContext: redisCredentialProvider(credential),
TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12},
})
// TODO: use the client
_ = client
}
// redisCredentialProvider returns a function that provides a username and password to a Redis
// client. The password is an Entra ID access token acquired from the given credential. The
// username is the object ID of the principal to whom Entra issued that token.
func redisCredentialProvider(credential azcore.TokenCredential) func(context.Context) (string, string, error) {
return func(ctx context.Context) (string, string, error) {
// get an access token for Azure Cache for Redis
tk, err := credential.GetToken(ctx, policy.TokenRequestOptions{
// Azure Cache for Redis uses the same scope in all clouds
Scopes: []string{"https://redis.azure.com/.default"},
})
if err != nil {
return "", "", err
}
// the token is a JWT; get the principal's object ID from its payload
parts := strings.Split(tk.Token, ".")
if len(parts) != 3 {
return "", "", errors.New("token must have 3 parts")
}
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return "", "", fmt.Errorf("couldn't decode payload: %s", err)
}
claims := struct {
OID string `json:"oid"`
}{}
err = json.Unmarshal(payload, &claims)
if err != nil {
return "", "", fmt.Errorf("couldn't unmarshal payload: %s", err)
}
if claims.OID == "" {
return "", "", errors.New("missing object ID claim")
}
return claims.OID, tk.Token, nil
}
}

Просмотреть файл

@ -9,13 +9,16 @@ require (
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2
github.com/golang-jwt/jwt/v5 v5.2.1
github.com/google/uuid v1.6.0
github.com/redis/go-redis/v9 v9.6.1
github.com/stretchr/testify v1.9.0
golang.org/x/crypto v0.25.0
)
require (
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/keybase/go-keychain v0.0.0-20231219164618-57a3676c3af6 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect

Просмотреть файл

@ -8,8 +8,14 @@ github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJ
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2 h1:XHOnouVk1mxXfQidrMEnLlPk9UMeRtyBTnEFtxkV0kU=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.2/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
@ -24,6 +30,8 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmd
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/redis/go-redis/v9 v9.6.1 h1:HHDteefn6ZkTtY5fGUE8tj8uy85AHk6zP7CpzIAM0y4=
github.com/redis/go-redis/v9 v9.6.1/go.mod h1:0C0c6ycQsdpVNQpxb1njEQIqkx5UcsM8FJCQLgE9+RA=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=