Debian Codegraph @

autorest/azure/auth/auth.go

raw
1 package auth
2
3 // Copyright 2017 Microsoft Corporation
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 import (
18 "bytes"
19 "context"
20 "encoding/binary"
21 "encoding/json"
22 "errors"
23 "fmt"
24 "io/ioutil"
25 "log"
26 "os"
27 "strings"
28 "unicode/utf16"
29
30 "github.com/Azure/go-autorest/autorest"
31 "github.com/Azure/go-autorest/autorest/adal"
32 "github.com/Azure/go-autorest/autorest/azure"
33 "github.com/Azure/go-autorest/autorest/azure/cli"
34 "github.com/Azure/go-autorest/logger"
35 "github.com/dimchansky/utfbom"
36 )
37
38 // The possible keys in the Values map.
39 const (
40 SubscriptionID = "AZURE_SUBSCRIPTION_ID"
41 TenantID = "AZURE_TENANT_ID"
42 AuxiliaryTenantIDs = "AZURE_AUXILIARY_TENANT_IDS"
43 ClientID = "AZURE_CLIENT_ID"
44 ClientSecret = "AZURE_CLIENT_SECRET"
45 CertificatePath = "AZURE_CERTIFICATE_PATH"
46 CertificatePassword = "AZURE_CERTIFICATE_PASSWORD"
47 Username = "AZURE_USERNAME"
48 Password = "AZURE_PASSWORD"
49 EnvironmentName = "AZURE_ENVIRONMENT"
50 Resource = "AZURE_AD_RESOURCE"
51 ActiveDirectoryEndpoint = "ActiveDirectoryEndpoint"
52 ResourceManagerEndpoint = "ResourceManagerEndpoint"
53 GraphResourceID = "GraphResourceID"
54 SQLManagementEndpoint = "SQLManagementEndpoint"
55 GalleryEndpoint = "GalleryEndpoint"
56 ManagementEndpoint = "ManagementEndpoint"
57 )
58
59 // NewAuthorizerFromEnvironment creates an Authorizer configured from environment variables in the order:
60 // 1. Client credentials
61 // 2. Client certificate
62 // 3. Username password
63 // 4. MSI
64 func NewAuthorizerFromEnvironment() (autorest.Authorizer, error) {
65 logger.Instance.Writeln(logger.LogInfo, "NewAuthorizerFromEnvironment() determining authentication mechanism")
66 settings, err := GetSettingsFromEnvironment()
67 if err != nil {
68 return nil, err
69 }
70 return settings.GetAuthorizer()
71 }
72
73 // NewAuthorizerFromEnvironmentWithResource creates an Authorizer configured from environment variables in the order:
74 // 1. Client credentials
75 // 2. Client certificate
76 // 3. Username password
77 // 4. MSI
78 func NewAuthorizerFromEnvironmentWithResource(resource string) (autorest.Authorizer, error) {
79 logger.Instance.Writeln(logger.LogInfo, "NewAuthorizerFromEnvironmentWithResource() determining authentication mechanism")
80 settings, err := GetSettingsFromEnvironment()
81 if err != nil {
82 return nil, err
83 }
84 settings.Values[Resource] = resource
85 return settings.GetAuthorizer()
86 }
87
88 // EnvironmentSettings contains the available authentication settings.
89 type EnvironmentSettings struct {
90 Values map[string]string
91 Environment azure.Environment
92 }
93
94 // GetSettingsFromEnvironment returns the available authentication settings from the environment.
95 func GetSettingsFromEnvironment() (s EnvironmentSettings, err error) {
96 s = EnvironmentSettings{
97 Values: map[string]string{},
98 }
99 s.setValue(SubscriptionID)
100 s.setValue(TenantID)
101 s.setValue(AuxiliaryTenantIDs)
102 s.setValue(ClientID)
103 s.setValue(ClientSecret)
104 s.setValue(CertificatePath)
105 s.setValue(CertificatePassword)
106 s.setValue(Username)
107 s.setValue(Password)
108 s.setValue(EnvironmentName)
109 s.setValue(Resource)
110 if v := s.Values[EnvironmentName]; v == "" {
111 s.Environment = azure.PublicCloud
112 } else {
113 s.Environment, err = azure.EnvironmentFromName(v)
114 }
115 if s.Values[Resource] == "" {
116 s.Values[Resource] = s.Environment.ResourceManagerEndpoint
117 }
118 return
119 }
120
121 // GetSubscriptionID returns the available subscription ID or an empty string.
122 func (settings EnvironmentSettings) GetSubscriptionID() string {
123 return settings.Values[SubscriptionID]
124 }
125
126 // adds the specified environment variable value to the Values map if it exists
127 func (settings EnvironmentSettings) setValue(key string) {
128 if v := os.Getenv(key); v != "" {
129 logger.Instance.Writef(logger.LogInfo, "GetSettingsFromEnvironment() found environment var %s\n", key)
130 settings.Values[key] = v
131 }
132 }
133
134 // helper to return client and tenant IDs
135 func (settings EnvironmentSettings) getClientAndTenant() (string, string) {
136 clientID := settings.Values[ClientID]
137 tenantID := settings.Values[TenantID]
138 return clientID, tenantID
139 }
140
141 // GetClientCredentials creates a config object from the available client credentials.
142 // An error is returned if no client credentials are available.
143 func (settings EnvironmentSettings) GetClientCredentials() (ClientCredentialsConfig, error) {
144 secret := settings.Values[ClientSecret]
145 if secret == "" {
146 logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetClientCredentials() missing client secret")
147 return ClientCredentialsConfig{}, errors.New("missing client secret")
148 }
149 clientID, tenantID := settings.getClientAndTenant()
150 config := NewClientCredentialsConfig(clientID, secret, tenantID)
151 config.AADEndpoint = settings.Environment.ActiveDirectoryEndpoint
152 config.Resource = settings.Values[Resource]
153 if auxTenants, ok := settings.Values[AuxiliaryTenantIDs]; ok {
154 config.AuxTenants = strings.Split(auxTenants, ";")
155 for i := range config.AuxTenants {
156 config.AuxTenants[i] = strings.TrimSpace(config.AuxTenants[i])
157 }
158 }
159 return config, nil
160 }
161
162 // GetClientCertificate creates a config object from the available certificate credentials.
163 // An error is returned if no certificate credentials are available.
164 func (settings EnvironmentSettings) GetClientCertificate() (ClientCertificateConfig, error) {
165 certPath := settings.Values[CertificatePath]
166 if certPath == "" {
167 logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetClientCertificate() missing certificate path")
168 return ClientCertificateConfig{}, errors.New("missing certificate path")
169 }
170 certPwd := settings.Values[CertificatePassword]
171 clientID, tenantID := settings.getClientAndTenant()
172 config := NewClientCertificateConfig(certPath, certPwd, clientID, tenantID)
173 config.AADEndpoint = settings.Environment.ActiveDirectoryEndpoint
174 config.Resource = settings.Values[Resource]
175 return config, nil
176 }
177
178 // GetUsernamePassword creates a config object from the available username/password credentials.
179 // An error is returned if no username/password credentials are available.
180 func (settings EnvironmentSettings) GetUsernamePassword() (UsernamePasswordConfig, error) {
181 username := settings.Values[Username]
182 password := settings.Values[Password]
183 if username == "" || password == "" {
184 logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetUsernamePassword() missing username and/or password")
185 return UsernamePasswordConfig{}, errors.New("missing username/password")
186 }
187 clientID, tenantID := settings.getClientAndTenant()
188 config := NewUsernamePasswordConfig(username, password, clientID, tenantID)
189 config.AADEndpoint = settings.Environment.ActiveDirectoryEndpoint
190 config.Resource = settings.Values[Resource]
191 return config, nil
192 }
193
194 // GetMSI creates a MSI config object from the available client ID.
195 func (settings EnvironmentSettings) GetMSI() MSIConfig {
196 config := NewMSIConfig()
197 config.Resource = settings.Values[Resource]
198 config.ClientID = settings.Values[ClientID]
199 return config
200 }
201
202 // GetDeviceFlow creates a device-flow config object from the available client and tenant IDs.
203 func (settings EnvironmentSettings) GetDeviceFlow() DeviceFlowConfig {
204 clientID, tenantID := settings.getClientAndTenant()
205 config := NewDeviceFlowConfig(clientID, tenantID)
206 config.AADEndpoint = settings.Environment.ActiveDirectoryEndpoint
207 config.Resource = settings.Values[Resource]
208 return config
209 }
210
211 // GetAuthorizer creates an Authorizer configured from environment variables in the order:
212 // 1. Client credentials
213 // 2. Client certificate
214 // 3. Username password
215 // 4. MSI
216 func (settings EnvironmentSettings) GetAuthorizer() (autorest.Authorizer, error) {
217 //1.Client Credentials
218 if c, e := settings.GetClientCredentials(); e == nil {
219 logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetAuthorizer() using client secret credentials")
220 return c.Authorizer()
221 }
222
223 //2. Client Certificate
224 if c, e := settings.GetClientCertificate(); e == nil {
225 logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetAuthorizer() using client certificate credentials")
226 return c.Authorizer()
227 }
228
229 //3. Username Password
230 if c, e := settings.GetUsernamePassword(); e == nil {
231 logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetAuthorizer() using user name/password credentials")
232 return c.Authorizer()
233 }
234
235 // 4. MSI
236 if !adal.MSIAvailable(context.Background(), nil) {
237 return nil, errors.New("MSI not available")
238 }
239 logger.Instance.Writeln(logger.LogInfo, "EnvironmentSettings.GetAuthorizer() using MSI authentication")
240 return settings.GetMSI().Authorizer()
241 }
242
243 // NewAuthorizerFromFile creates an Authorizer configured from a configuration file in the following order.
244 // 1. Client credentials
245 // 2. Client certificate
246 // The path to the configuration file must be specified in the AZURE_AUTH_LOCATION environment variable.
247 // resourceBaseURI - used to determine the resource type
248 func NewAuthorizerFromFile(resourceBaseURI string) (autorest.Authorizer, error) {
249 settings, err := GetSettingsFromFile()
250 if err != nil {
251 return nil, err
252 }
253 if a, err := settings.ClientCredentialsAuthorizer(resourceBaseURI); err == nil {
254 return a, err
255 }
256 if a, err := settings.ClientCertificateAuthorizer(resourceBaseURI); err == nil {
257 return a, err
258 }
259 return nil, errors.New("auth file missing client and certificate credentials")
260 }
261
262 // NewAuthorizerFromFileWithResource creates an Authorizer configured from a configuration file in the following order.
263 // 1. Client credentials
264 // 2. Client certificate
265 // The path to the configuration file must be specified in the AZURE_AUTH_LOCATION environment variable.
266 func NewAuthorizerFromFileWithResource(resource string) (autorest.Authorizer, error) {
267 s, err := GetSettingsFromFile()
268 if err != nil {
269 return nil, err
270 }
271 if a, err := s.ClientCredentialsAuthorizerWithResource(resource); err == nil {
272 return a, err
273 }
274 if a, err := s.ClientCertificateAuthorizerWithResource(resource); err == nil {
275 return a, err
276 }
277 return nil, errors.New("auth file missing client and certificate credentials")
278 }
279
280 // NewAuthorizerFromCLI creates an Authorizer configured from Azure CLI 2.0 for local development scenarios.
281 func NewAuthorizerFromCLI() (autorest.Authorizer, error) {
282 settings, err := GetSettingsFromEnvironment()
283 if err != nil {
284 return nil, err
285 }
286
287 if settings.Values[Resource] == "" {
288 settings.Values[Resource] = settings.Environment.ResourceManagerEndpoint
289 }
290
291 return NewAuthorizerFromCLIWithResource(settings.Values[Resource])
292 }
293
294 // NewAuthorizerFromCLIWithResource creates an Authorizer configured from Azure CLI 2.0 for local development scenarios.
295 func NewAuthorizerFromCLIWithResource(resource string) (autorest.Authorizer, error) {
296 token, err := cli.GetTokenFromCLI(resource)
297 if err != nil {
298 return nil, err
299 }
300
301 adalToken, err := token.ToADALToken()
302 if err != nil {
303 return nil, err
304 }
305
306 return autorest.NewBearerAuthorizer(&adalToken), nil
307 }
308
309 // GetSettingsFromFile returns the available authentication settings from an Azure CLI authentication file.
310 func GetSettingsFromFile() (FileSettings, error) {
311 s := FileSettings{}
312 fileLocation := os.Getenv("AZURE_AUTH_LOCATION")
313 if fileLocation == "" {
314 return s, errors.New("environment variable AZURE_AUTH_LOCATION is not set")
315 }
316
317 contents, err := ioutil.ReadFile(fileLocation)
318 if err != nil {
319 return s, err
320 }
321
322 // Auth file might be encoded
323 decoded, err := decode(contents)
324 if err != nil {
325 return s, err
326 }
327
328 authFile := map[string]interface{}{}
329 err = json.Unmarshal(decoded, &authFile)
330 if err != nil {
331 return s, err
332 }
333
334 s.Values = map[string]string{}
335 s.setKeyValue(ClientID, authFile["clientId"])
336 s.setKeyValue(ClientSecret, authFile["clientSecret"])
337 s.setKeyValue(CertificatePath, authFile["clientCertificate"])
338 s.setKeyValue(CertificatePassword, authFile["clientCertificatePassword"])
339 s.setKeyValue(SubscriptionID, authFile["subscriptionId"])
340 s.setKeyValue(TenantID, authFile["tenantId"])
341 s.setKeyValue(ActiveDirectoryEndpoint, authFile["activeDirectoryEndpointUrl"])
342 s.setKeyValue(ResourceManagerEndpoint, authFile["resourceManagerEndpointUrl"])
343 s.setKeyValue(GraphResourceID, authFile["activeDirectoryGraphResourceId"])
344 s.setKeyValue(SQLManagementEndpoint, authFile["sqlManagementEndpointUrl"])
345 s.setKeyValue(GalleryEndpoint, authFile["galleryEndpointUrl"])
346 s.setKeyValue(ManagementEndpoint, authFile["managementEndpointUrl"])
347 return s, nil
348 }
349
350 // FileSettings contains the available authentication settings.
351 type FileSettings struct {
352 Values map[string]string
353 }
354
355 // GetSubscriptionID returns the available subscription ID or an empty string.
356 func (settings FileSettings) GetSubscriptionID() string {
357 return settings.Values[SubscriptionID]
358 }
359
360 // adds the specified value to the Values map if it isn't nil
361 func (settings FileSettings) setKeyValue(key string, val interface{}) {
362 if val != nil {
363 settings.Values[key] = val.(string)
364 }
365 }
366
367 // returns the specified AAD endpoint or the public cloud endpoint if unspecified
368 func (settings FileSettings) getAADEndpoint() string {
369 if v, ok := settings.Values[ActiveDirectoryEndpoint]; ok {
370 return v
371 }
372 return azure.PublicCloud.ActiveDirectoryEndpoint
373 }
374
375 // ServicePrincipalTokenFromClientCredentials creates a ServicePrincipalToken from the available client credentials.
376 func (settings FileSettings) ServicePrincipalTokenFromClientCredentials(baseURI string) (*adal.ServicePrincipalToken, error) {
377 resource, err := settings.getResourceForToken(baseURI)
378 if err != nil {
379 return nil, err
380 }
381 return settings.ServicePrincipalTokenFromClientCredentialsWithResource(resource)
382 }
383
384 // ClientCredentialsAuthorizer creates an authorizer from the available client credentials.
385 func (settings FileSettings) ClientCredentialsAuthorizer(baseURI string) (autorest.Authorizer, error) {
386 resource, err := settings.getResourceForToken(baseURI)
387 if err != nil {
388 return nil, err
389 }
390 return settings.ClientCredentialsAuthorizerWithResource(resource)
391 }
392
393 // ServicePrincipalTokenFromClientCredentialsWithResource creates a ServicePrincipalToken
394 // from the available client credentials and the specified resource.
395 func (settings FileSettings) ServicePrincipalTokenFromClientCredentialsWithResource(resource string) (*adal.ServicePrincipalToken, error) {
396 if _, ok := settings.Values[ClientSecret]; !ok {
397 return nil, errors.New("missing client secret")
398 }
399 config, err := adal.NewOAuthConfig(settings.getAADEndpoint(), settings.Values[TenantID])
400 if err != nil {
401 return nil, err
402 }
403 return adal.NewServicePrincipalToken(*config, settings.Values[ClientID], settings.Values[ClientSecret], resource)
404 }
405
406 func (settings FileSettings) clientCertificateConfigWithResource(resource string) (ClientCertificateConfig, error) {
407 if _, ok := settings.Values[CertificatePath]; !ok {
408 return ClientCertificateConfig{}, errors.New("missing certificate path")
409 }
410 cfg := NewClientCertificateConfig(settings.Values[CertificatePath], settings.Values[CertificatePassword], settings.Values[ClientID], settings.Values[TenantID])
411 cfg.AADEndpoint = settings.getAADEndpoint()
412 cfg.Resource = resource
413 return cfg, nil
414 }
415
416 // ClientCredentialsAuthorizerWithResource creates an authorizer from the available client credentials and the specified resource.
417 func (settings FileSettings) ClientCredentialsAuthorizerWithResource(resource string) (autorest.Authorizer, error) {
418 spToken, err := settings.ServicePrincipalTokenFromClientCredentialsWithResource(resource)
419 if err != nil {
420 return nil, err
421 }
422 return autorest.NewBearerAuthorizer(spToken), nil
423 }
424
425 // ServicePrincipalTokenFromClientCertificate creates a ServicePrincipalToken from the available certificate credentials.
426 func (settings FileSettings) ServicePrincipalTokenFromClientCertificate(baseURI string) (*adal.ServicePrincipalToken, error) {
427 resource, err := settings.getResourceForToken(baseURI)
428 if err != nil {
429 return nil, err
430 }
431 return settings.ServicePrincipalTokenFromClientCertificateWithResource(resource)
432 }
433
434 // ClientCertificateAuthorizer creates an authorizer from the available certificate credentials.
435 func (settings FileSettings) ClientCertificateAuthorizer(baseURI string) (autorest.Authorizer, error) {
436 resource, err := settings.getResourceForToken(baseURI)
437 if err != nil {
438 return nil, err
439 }
440 return settings.ClientCertificateAuthorizerWithResource(resource)
441 }
442
443 // ServicePrincipalTokenFromClientCertificateWithResource creates a ServicePrincipalToken from the available certificate credentials.
444 func (settings FileSettings) ServicePrincipalTokenFromClientCertificateWithResource(resource string) (*adal.ServicePrincipalToken, error) {
445 cfg, err := settings.clientCertificateConfigWithResource(resource)
446 if err != nil {
447 return nil, err
448 }
449 return cfg.ServicePrincipalToken()
450 }
451
452 // ClientCertificateAuthorizerWithResource creates an authorizer from the available certificate credentials and the specified resource.
453 func (settings FileSettings) ClientCertificateAuthorizerWithResource(resource string) (autorest.Authorizer, error) {
454 cfg, err := settings.clientCertificateConfigWithResource(resource)
455 if err != nil {
456 return nil, err
457 }
458 return cfg.Authorizer()
459 }
460
461 func decode(b []byte) ([]byte, error) {
462 reader, enc := utfbom.Skip(bytes.NewReader(b))
463
464 switch enc {
465 case utfbom.UTF16LittleEndian:
466 u16 := make([]uint16, (len(b)/2)-1)
467 err := binary.Read(reader, binary.LittleEndian, &u16)
468 if err != nil {
469 return nil, err
470 }
471 return []byte(string(utf16.Decode(u16))), nil
472 case utfbom.UTF16BigEndian:
473 u16 := make([]uint16, (len(b)/2)-1)
474 err := binary.Read(reader, binary.BigEndian, &u16)
475 if err != nil {
476 return nil, err
477 }
478 return []byte(string(utf16.Decode(u16))), nil
479 }
480 return ioutil.ReadAll(reader)
481 }
482
483 func (settings FileSettings) getResourceForToken(baseURI string) (string, error) {
484 // Compare default base URI from the SDK to the endpoints from the public cloud
485 // Base URI and token resource are the same string. This func finds the authentication
486 // file field that matches the SDK base URI. The SDK defines the public cloud
487 // endpoint as its default base URI
488 if !strings.HasSuffix(baseURI, "/") {
489 baseURI += "/"
490 }
491 switch baseURI {
492 case azure.PublicCloud.ServiceManagementEndpoint:
493 return settings.Values[ManagementEndpoint], nil
494 case azure.PublicCloud.ResourceManagerEndpoint:
495 return settings.Values[ResourceManagerEndpoint], nil
496 case azure.PublicCloud.ActiveDirectoryEndpoint:
497 return settings.Values[ActiveDirectoryEndpoint], nil
498 case azure.PublicCloud.GalleryEndpoint:
499 return settings.Values[GalleryEndpoint], nil
500 case azure.PublicCloud.GraphEndpoint:
501 return settings.Values[GraphResourceID], nil
502 }
503 return "", fmt.Errorf("auth: base URI not found in endpoints")
504 }
505
506 // NewClientCredentialsConfig creates an AuthorizerConfig object configured to obtain an Authorizer through Client Credentials.
507 // Defaults to Public Cloud and Resource Manager Endpoint.
508 func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string) ClientCredentialsConfig {
509 return ClientCredentialsConfig{
510 ClientID: clientID,
511 ClientSecret: clientSecret,
512 TenantID: tenantID,
513 Resource: azure.PublicCloud.ResourceManagerEndpoint,
514 AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint,
515 }
516 }
517
518 // NewClientCertificateConfig creates a ClientCertificateConfig object configured to obtain an Authorizer through client certificate.
519 // Defaults to Public Cloud and Resource Manager Endpoint.
520 func NewClientCertificateConfig(certificatePath string, certificatePassword string, clientID string, tenantID string) ClientCertificateConfig {
521 return ClientCertificateConfig{
522 CertificatePath: certificatePath,
523 CertificatePassword: certificatePassword,
524 ClientID: clientID,
525 TenantID: tenantID,
526 Resource: azure.PublicCloud.ResourceManagerEndpoint,
527 AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint,
528 }
529 }
530
531 // NewUsernamePasswordConfig creates an UsernamePasswordConfig object configured to obtain an Authorizer through username and password.
532 // Defaults to Public Cloud and Resource Manager Endpoint.
533 func NewUsernamePasswordConfig(username string, password string, clientID string, tenantID string) UsernamePasswordConfig {
534 return UsernamePasswordConfig{
535 Username: username,
536 Password: password,
537 ClientID: clientID,
538 TenantID: tenantID,
539 Resource: azure.PublicCloud.ResourceManagerEndpoint,
540 AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint,
541 }
542 }
543
544 // NewMSIConfig creates an MSIConfig object configured to obtain an Authorizer through MSI.
545 func NewMSIConfig() MSIConfig {
546 return MSIConfig{
547 Resource: azure.PublicCloud.ResourceManagerEndpoint,
548 }
549 }
550
551 // NewDeviceFlowConfig creates a DeviceFlowConfig object configured to obtain an Authorizer through device flow.
552 // Defaults to Public Cloud and Resource Manager Endpoint.
553 func NewDeviceFlowConfig(clientID string, tenantID string) DeviceFlowConfig {
554 return DeviceFlowConfig{
555 ClientID: clientID,
556 TenantID: tenantID,
557 Resource: azure.PublicCloud.ResourceManagerEndpoint,
558 AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint,
559 }
560 }
561
562 //AuthorizerConfig provides an authorizer from the configuration provided.
563 type AuthorizerConfig interface {
564 Authorizer() (autorest.Authorizer, error)
565 }
566
567 // ClientCredentialsConfig provides the options to get a bearer authorizer from client credentials.
568 type ClientCredentialsConfig struct {
569 ClientID string
570 ClientSecret string
571 TenantID string
572 AuxTenants []string
573 AADEndpoint string
574 Resource string
575 }
576
577 // ServicePrincipalToken creates a ServicePrincipalToken from client credentials.
578 func (ccc ClientCredentialsConfig) ServicePrincipalToken() (*adal.ServicePrincipalToken, error) {
579 oauthConfig, err := adal.NewOAuthConfig(ccc.AADEndpoint, ccc.TenantID)
580 if err != nil {
581 return nil, err
582 }
583 return adal.NewServicePrincipalToken(*oauthConfig, ccc.ClientID, ccc.ClientSecret, ccc.Resource)
584 }
585
586 // MultiTenantServicePrincipalToken creates a MultiTenantServicePrincipalToken from client credentials.
587 func (ccc ClientCredentialsConfig) MultiTenantServicePrincipalToken() (*adal.MultiTenantServicePrincipalToken, error) {
588 oauthConfig, err := adal.NewMultiTenantOAuthConfig(ccc.AADEndpoint, ccc.TenantID, ccc.AuxTenants, adal.OAuthOptions{})
589 if err != nil {
590 return nil, err
591 }
592 return adal.NewMultiTenantServicePrincipalToken(oauthConfig, ccc.ClientID, ccc.ClientSecret, ccc.Resource)
593 }
594
595 // Authorizer gets the authorizer from client credentials.
596 func (ccc ClientCredentialsConfig) Authorizer() (autorest.Authorizer, error) {
597 if len(ccc.AuxTenants) == 0 {
598 spToken, err := ccc.ServicePrincipalToken()
599 if err != nil {
600 return nil, fmt.Errorf("failed to get SPT from client credentials: %v", err)
601 }
602 return autorest.NewBearerAuthorizer(spToken), nil
603 }
604 mtSPT, err := ccc.MultiTenantServicePrincipalToken()
605 if err != nil {
606 return nil, fmt.Errorf("failed to get multitenant SPT from client credentials: %v", err)
607 }
608 return autorest.NewMultiTenantServicePrincipalTokenAuthorizer(mtSPT), nil
609 }
610
611 // ClientCertificateConfig provides the options to get a bearer authorizer from a client certificate.
612 type ClientCertificateConfig struct {
613 ClientID string
614 CertificatePath string
615 CertificatePassword string
616 TenantID string
617 AuxTenants []string
618 AADEndpoint string
619 Resource string
620 }
621
622 // ServicePrincipalToken creates a ServicePrincipalToken from client certificate.
623 func (ccc ClientCertificateConfig) ServicePrincipalToken() (*adal.ServicePrincipalToken, error) {
624 oauthConfig, err := adal.NewOAuthConfig(ccc.AADEndpoint, ccc.TenantID)
625 if err != nil {
626 return nil, err
627 }
628 certData, err := ioutil.ReadFile(ccc.CertificatePath)
629 if err != nil {
630 return nil, fmt.Errorf("failed to read the certificate file (%s): %v", ccc.CertificatePath, err)
631 }
632 certificate, rsaPrivateKey, err := adal.DecodePfxCertificateData(certData, ccc.CertificatePassword)
633 if err != nil {
634 return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err)
635 }
636 return adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, ccc.ClientID, certificate, rsaPrivateKey, ccc.Resource)
637 }
638
639 // MultiTenantServicePrincipalToken creates a MultiTenantServicePrincipalToken from client certificate.
640 func (ccc ClientCertificateConfig) MultiTenantServicePrincipalToken() (*adal.MultiTenantServicePrincipalToken, error) {
641 oauthConfig, err := adal.NewMultiTenantOAuthConfig(ccc.AADEndpoint, ccc.TenantID, ccc.AuxTenants, adal.OAuthOptions{})
642 if err != nil {
643 return nil, err
644 }
645 certData, err := ioutil.ReadFile(ccc.CertificatePath)
646 if err != nil {
647 return nil, fmt.Errorf("failed to read the certificate file (%s): %v", ccc.CertificatePath, err)
648 }
649 certificate, rsaPrivateKey, err := adal.DecodePfxCertificateData(certData, ccc.CertificatePassword)
650 if err != nil {
651 return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err)
652 }
653 return adal.NewMultiTenantServicePrincipalTokenFromCertificate(oauthConfig, ccc.ClientID, certificate, rsaPrivateKey, ccc.Resource)
654 }
655
656 // Authorizer gets an authorizer object from client certificate.
657 func (ccc ClientCertificateConfig) Authorizer() (autorest.Authorizer, error) {
658 if len(ccc.AuxTenants) == 0 {
659 spToken, err := ccc.ServicePrincipalToken()
660 if err != nil {
661 return nil, fmt.Errorf("failed to get oauth token from certificate auth: %v", err)
662 }
663 return autorest.NewBearerAuthorizer(spToken), nil
664 }
665 mtSPT, err := ccc.MultiTenantServicePrincipalToken()
666 if err != nil {
667 return nil, fmt.Errorf("failed to get multitenant SPT from certificate auth: %v", err)
668 }
669 return autorest.NewMultiTenantServicePrincipalTokenAuthorizer(mtSPT), nil
670 }
671
672 // DeviceFlowConfig provides the options to get a bearer authorizer using device flow authentication.
673 type DeviceFlowConfig struct {
674 ClientID string
675 TenantID string
676 AADEndpoint string
677 Resource string
678 }
679
680 // Authorizer gets the authorizer from device flow.
681 func (dfc DeviceFlowConfig) Authorizer() (autorest.Authorizer, error) {
682 spToken, err := dfc.ServicePrincipalToken()
683 if err != nil {
684 return nil, fmt.Errorf("failed to get oauth token from device flow: %v", err)
685 }
686 return autorest.NewBearerAuthorizer(spToken), nil
687 }
688
689 // ServicePrincipalToken gets the service principal token from device flow.
690 func (dfc DeviceFlowConfig) ServicePrincipalToken() (*adal.ServicePrincipalToken, error) {
691 oauthConfig, err := adal.NewOAuthConfig(dfc.AADEndpoint, dfc.TenantID)
692 if err != nil {
693 return nil, err
694 }
695 oauthClient := &autorest.Client{}
696 deviceCode, err := adal.InitiateDeviceAuth(oauthClient, *oauthConfig, dfc.ClientID, dfc.Resource)
697 if err != nil {
698 return nil, fmt.Errorf("failed to start device auth flow: %s", err)
699 }
700 log.Println(*deviceCode.Message)
701 token, err := adal.WaitForUserCompletion(oauthClient, deviceCode)
702 if err != nil {
703 return nil, fmt.Errorf("failed to finish device auth flow: %s", err)
704 }
705 return adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, dfc.ClientID, dfc.Resource, *token)
706 }
707
708 // UsernamePasswordConfig provides the options to get a bearer authorizer from a username and a password.
709 type UsernamePasswordConfig struct {
710 ClientID string
711 Username string
712 Password string
713 TenantID string
714 AADEndpoint string
715 Resource string
716 }
717
718 // ServicePrincipalToken creates a ServicePrincipalToken from username and password.
719 func (ups UsernamePasswordConfig) ServicePrincipalToken() (*adal.ServicePrincipalToken, error) {
720 oauthConfig, err := adal.NewOAuthConfig(ups.AADEndpoint, ups.TenantID)
721 if err != nil {
722 return nil, err
723 }
724 return adal.NewServicePrincipalTokenFromUsernamePassword(*oauthConfig, ups.ClientID, ups.Username, ups.Password, ups.Resource)
725 }
726
727 // Authorizer gets the authorizer from a username and a password.
728 func (ups UsernamePasswordConfig) Authorizer() (autorest.Authorizer, error) {
729 spToken, err := ups.ServicePrincipalToken()
730 if err != nil {
731 return nil, fmt.Errorf("failed to get oauth token from username and password auth: %v", err)
732 }
733 return autorest.NewBearerAuthorizer(spToken), nil
734 }
735
736 // MSIConfig provides the options to get a bearer authorizer through MSI.
737 type MSIConfig struct {
738 Resource string
739 ClientID string
740 }
741
742 // ServicePrincipalToken creates a ServicePrincipalToken from MSI.
743 func (mc MSIConfig) ServicePrincipalToken() (*adal.ServicePrincipalToken, error) {
744 spToken, err := adal.NewServicePrincipalTokenFromManagedIdentity(mc.Resource, &adal.ManagedIdentityOptions{
745 ClientID: mc.ClientID,
746 })
747 if err != nil {
748 return nil, fmt.Errorf("failed to get oauth token from MSI: %v", err)
749 }
750 return spToken, nil
751 }
752
753 // Authorizer gets the authorizer from MSI.
754 func (mc MSIConfig) Authorizer() (autorest.Authorizer, error) {
755 spToken, err := mc.ServicePrincipalToken()
756 if err != nil {
757 return nil, err
758 }
759
760 return autorest.NewBearerAuthorizer(spToken), nil
761 }