-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathazure_default_identity_provider.go
76 lines (62 loc) · 2.6 KB
/
azure_default_identity_provider.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package entraid
import (
"context"
"fmt"
"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"
)
// DefaultAzureIdentityProviderOptions represents the options for the DefaultAzureIdentityProvider.
type DefaultAzureIdentityProviderOptions struct {
// AzureOptions is the options used to configure the Azure identity provider.
AzureOptions *azidentity.DefaultAzureCredentialOptions
// Scopes is the list of scopes used to request a token from the identity provider.
Scopes []string
// credFactory is a factory for creating the default Azure credential.
// This is used for testing purposes, to allow mocking the credential creation.
// If not provided, the default implementation - azidentity.NewDefaultAzureCredential will be used
credFactory credFactory
}
type credFactory interface {
NewDefaultAzureCredential(options *azidentity.DefaultAzureCredentialOptions) (defaultAzureCredential, error)
}
type defaultAzureCredential interface {
GetToken(ctx context.Context, options policy.TokenRequestOptions) (azcore.AccessToken, error)
}
type defaultCredFactory struct{}
func (d *defaultCredFactory) NewDefaultAzureCredential(options *azidentity.DefaultAzureCredentialOptions) (defaultAzureCredential, error) {
return azidentity.NewDefaultAzureCredential(options)
}
type DefaultAzureIdentityProvider struct {
options *azidentity.DefaultAzureCredentialOptions
credFactory credFactory
scopes []string
}
// NewDefaultAzureIdentityProvider creates a new DefaultAzureIdentityProvider.
func NewDefaultAzureIdentityProvider(opts DefaultAzureIdentityProviderOptions) (*DefaultAzureIdentityProvider, error) {
if opts.Scopes == nil {
opts.Scopes = []string{RedisScopeDefault}
}
return &DefaultAzureIdentityProvider{
options: opts.AzureOptions,
scopes: opts.Scopes,
credFactory: opts.credFactory,
}, nil
}
// RequestToken requests a token from the Azure Default Identity provider.
// It returns the token, the expiration time, and an error if any.
func (a *DefaultAzureIdentityProvider) RequestToken() (IdentityProviderResponse, error) {
credFactory := a.credFactory
if credFactory == nil {
credFactory = &defaultCredFactory{}
}
cred, err := credFactory.NewDefaultAzureCredential(a.options)
if err != nil {
return nil, fmt.Errorf("failed to create default azure credential: %w", err)
}
token, err := cred.GetToken(context.TODO(), policy.TokenRequestOptions{Scopes: a.scopes})
if err != nil {
return nil, fmt.Errorf("failed to get token: %w", err)
}
return NewIDPResponse(ResponseTypeAccessToken, &token)
}