-
Notifications
You must be signed in to change notification settings - Fork 315
Expand file tree
/
Copy pathauth_login.go
More file actions
690 lines (607 loc) · 23.1 KB
/
auth_login.go
File metadata and controls
690 lines (607 loc) · 23.1 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package cmd
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/MakeNowJust/heredoc/v2"
"github.com/azure/azure-dev/cli/azd/cmd/actions"
"github.com/azure/azure-dev/cli/azd/internal"
"github.com/azure/azure-dev/cli/azd/internal/runcontext"
"github.com/azure/azure-dev/cli/azd/internal/tracing"
"github.com/azure/azure-dev/cli/azd/internal/tracing/fields"
"github.com/azure/azure-dev/cli/azd/pkg/account"
"github.com/azure/azure-dev/cli/azd/pkg/auth"
"github.com/azure/azure-dev/cli/azd/pkg/contracts"
"github.com/azure/azure-dev/cli/azd/pkg/exec"
"github.com/azure/azure-dev/cli/azd/pkg/input"
"github.com/azure/azure-dev/cli/azd/pkg/oneauth"
"github.com/azure/azure-dev/cli/azd/pkg/output"
"github.com/azure/azure-dev/cli/azd/pkg/output/ux"
"github.com/azure/azure-dev/cli/azd/pkg/tools/github"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"go.opentelemetry.io/otel/attribute"
)
// The parent of the login command.
const loginCmdParentAnnotation = "loginCmdParent"
// azurePipelinesClientIDEnvVarName is the name of the environment variable that contains the client ID for the principal
// to use when authenticating with Azure Pipelines via OIDC. It is set by both the AzureCLI@2 and AzurePowerShell@5 tasks
// when using a service connection or can be set manually when not using these tasks.
const azurePipelinesClientIDEnvVarName = "AZURESUBSCRIPTION_CLIENT_ID"
// azurePipelinesTenantIDEnvVarName is the name of the environment variable that contains the tenant ID for the principal
// to use when authenticating with Azure Pipelines via OIDC. It is set by both the AzureCLI@2 and AzurePowerShell@5 tasks
// when using a service connection or can be set manually when not using these tasks.
const azurePipelinesTenantIDEnvVarName = "AZURESUBSCRIPTION_TENANT_ID"
// AzurePipelinesServiceConnectionNameEnvVarName is the name of the environment variable that contains the name of the
// service connection to use when authenticating with Azure Pipelines via OIDC. It is set by both the AzureCLI@2 and
// AzurePowerShell@5 tasks when using a service connection or can be set manually when not using these tasks.
const azurePipelinesServiceConnectionIDEnvVarName = "AZURESUBSCRIPTION_SERVICE_CONNECTION_ID"
// azurePipelinesProvider is the name of the federated token provider to use when authenticating with Azure Pipelines via
// OIDC.
const azurePipelinesProvider string = "azure-pipelines"
type authLoginFlags struct {
loginFlags
}
func newAuthLoginFlags(cmd *cobra.Command, global *internal.GlobalCommandOptions) *authLoginFlags {
flags := &authLoginFlags{}
flags.Bind(cmd.Flags(), global)
return flags
}
type loginFlags struct {
onlyCheckStatus bool
browser bool
managedIdentity bool
useDeviceCode boolPtr
tenantID string
clientID string
clientSecret stringPtr
clientCertificate string
federatedTokenProvider string
scopes []string
claims string
redirectPort int
global *internal.GlobalCommandOptions
}
// stringPtr implements a pflag.Value and allows us to distinguish between a flag value being explicitly set to the empty
// string vs not being present.
type stringPtr struct {
ptr *string
}
func (p *stringPtr) Set(s string) error {
p.ptr = &s
return nil
}
func (p *stringPtr) String() string {
if p.ptr != nil {
return *p.ptr
}
return ""
}
func (p *stringPtr) Type() string {
return "string"
}
// boolPtr implements a pflag.Value and allows us to distinguish between a flag value being explicitly set to
// bool vs not being present.
type boolPtr struct {
ptr *string
}
func (p *boolPtr) Set(s string) error {
p.ptr = &s
return nil
}
func (p *boolPtr) String() string {
if p.ptr != nil {
return *p.ptr
}
return "false"
}
func (p *boolPtr) Type() string {
return ""
}
const (
cClientSecretFlagName = "client-secret"
cClientCertificateFlagName = "client-certificate"
cFederatedCredentialProviderFlagName = "federated-credential-provider"
)
func (lf *loginFlags) Bind(local *pflag.FlagSet, global *internal.GlobalCommandOptions) {
local.BoolVar(&lf.onlyCheckStatus, "check-status", false, "Checks the log-in status instead of logging in.")
f := local.VarPF(
&lf.useDeviceCode,
"use-device-code",
"",
"When true, log in by using a device code instead of a browser.",
)
// ensure the flag behaves as a common boolean flag which is set to true when used without any other arg
f.NoOptDefVal = "true"
local.BoolVar(
&lf.managedIdentity,
"managed-identity",
false,
"Use a managed identity to authenticate.",
)
local.StringVar(&lf.clientID, "client-id", "", "The client id for the service principal to authenticate with.")
local.Var(
&lf.clientSecret,
cClientSecretFlagName,
"The client secret for the service principal to authenticate with. "+
"Set to the empty string to read the value from the console.")
local.StringVar(
&lf.clientCertificate,
cClientCertificateFlagName,
"",
"The path to the client certificate for the service principal to authenticate with.")
local.StringVar(
&lf.federatedTokenProvider,
cFederatedCredentialProviderFlagName,
"",
"The provider to use to acquire a federated token to authenticate with. "+
"Supported values: github, azure-pipelines, oidc")
local.StringVar(
&lf.tenantID,
"tenant-id",
"",
"The tenant id or domain name to authenticate with.")
local.StringArrayVar(
&lf.scopes,
"scope",
nil,
"The scope to acquire during login")
_ = local.MarkHidden("scope")
local.StringVar(
&lf.claims,
"claims",
"",
"Additional claims to include during login.")
_ = local.MarkHidden("claims")
local.IntVar(
&lf.redirectPort,
"redirect-port",
0,
"Choose the port to be used as part of the redirect URI during interactive login.")
if oneauth.Supported {
local.BoolVar(&lf.browser, "browser", false, "Authenticate in a web browser instead of an integrated dialog.")
}
lf.global = global
}
func newLoginCmd(parent string) *cobra.Command {
return &cobra.Command{
Use: "login",
Short: "Log in to Azure.",
Long: heredoc.Doc(`
Log in to Azure.
When run without any arguments, log in interactively using a browser. To log in using a device code, pass
--use-device-code.
To log in as a service principal, pass --client-id and --tenant-id as well as one of: --client-secret,
--client-certificate, or --federated-credential-provider.
To log in using a managed identity, pass --managed-identity, which will use the system assigned managed identity.
To use a user assigned managed identity, pass --client-id in addition to --managed-identity with the client id of
the user assigned managed identity you wish to use.
When already logged in, azd automatically clears cached authentication data (such as stale tokens)
before re-authenticating. This ensures a clean login state and prevents issues with expired or
corrupted cached credentials.
`),
Annotations: map[string]string{
loginCmdParentAnnotation: parent,
},
}
}
type loginAction struct {
formatter output.Formatter
writer io.Writer
console input.Console
authManager *auth.Manager
accountSubManager *account.SubscriptionsManager
flags *loginFlags
annotations CmdAnnotations
commandRunner exec.CommandRunner
}
func newAuthLoginAction(
formatter output.Formatter,
writer io.Writer,
authManager *auth.Manager,
accountSubManager *account.SubscriptionsManager,
flags *authLoginFlags,
console input.Console,
annotations CmdAnnotations,
commandRunner exec.CommandRunner,
) actions.Action {
return &loginAction{
formatter: formatter,
writer: writer,
console: console,
authManager: authManager,
accountSubManager: accountSubManager,
flags: &flags.loginFlags,
annotations: annotations,
commandRunner: commandRunner,
}
}
func (la *loginAction) Run(ctx context.Context) (*actions.ActionResult, error) {
loginMode, err := la.authManager.Mode()
if err != nil {
return nil, err
}
if loginMode != auth.AzdBuiltIn && !la.flags.onlyCheckStatus {
la.console.Message(ctx, "")
la.console.MessageUxItem(ctx, &ux.WarningAltMessage{
Message: fmt.Sprintf(
"azd is not using the built-in authentication mode, but rather '%s'", loginMode),
})
if loginMode == auth.AzDelegated {
la.console.Message(ctx, "Run 'az login' directly instead of 'azd auth login' when using this mode.")
}
la.console.Message(ctx, "To use azd to authenticate instead, select 'y' in the following prompt.")
la.console.Message(ctx, "")
response, err := la.console.Confirm(ctx, input.ConsoleOptions{
Message: "Do you want to switch back to azd built-in authentication?",
DefaultValue: false,
Help: "azd supports multiple authentication modes, including " + string(auth.AzDelegated) + " and " +
string(auth.ExternalRequest) + " for Auth." +
" Switching back to azd built-in authentication will try to disable the current mode.",
})
if err != nil {
return nil, err
}
if !response {
return nil, &internal.ErrorWithSuggestion{
Err: fmt.Errorf(
"current auth mode is '%s': %w", loginMode, internal.ErrLoginDisabledDelegatedMode),
Suggestion: "Use the delegated identity to authenticate." +
" To switch to built-in auth, confirm the prompt when re-running 'azd auth login'.",
}
}
if err := la.authManager.SetBuiltInAuthMode(); err != nil {
return nil, fmt.Errorf("setting auth mode: %w", err)
}
la.console.Message(ctx, "Authentication mode set to azd built-in. Continuing login...")
}
if len(la.flags.scopes) == 0 {
la.flags.scopes = la.authManager.LoginScopes()
}
if la.annotations[loginCmdParentAnnotation] == "" {
fmt.Fprintln(
la.console.Handles().Stderr,
output.WithWarningFormat(
"WARNING: `azd login` is deprecated and will be removed in a future release."))
fmt.Fprintln(
la.console.Handles().Stderr,
"Next time use `azd auth login`.")
}
if la.flags.onlyCheckStatus {
tracing.SetUsageAttributes(fields.AuthMethodKey.String("check-status"))
// In check status mode, we always print the final status to stdout.
// We print any non-setup related errors to stderr.
// We always return a zero exit code.
token, err := la.verifyLoggedIn(ctx)
// An *internal.ErrorWithSuggestion already carries actionable, user-facing guidance
// surfaced through the login result; avoid double-printing the raw error.
_, hasSuggestion := errors.AsType[*internal.ErrorWithSuggestion](err)
if err != nil &&
!errors.Is(err, auth.ErrNoCurrentUser) &&
!hasSuggestion {
fmt.Fprintln(la.console.Handles().Stderr, err.Error())
}
res := contracts.LoginResult{}
if err != nil {
res.Status = contracts.LoginStatusUnauthenticated
} else {
res.Status = contracts.LoginStatusSuccess
res.ExpiresOn = &token.ExpiresOn
}
if la.formatter.Kind() != output.NoneFormat {
return nil, la.formatter.Format(res, la.writer, nil)
} else {
var msg string
switch res.Status {
case contracts.LoginStatusSuccess:
msg = "Logged in to Azure"
case contracts.LoginStatusUnauthenticated:
msg = "Not logged in, run `azd auth login` to login to Azure"
default:
panic("Unhandled login status")
}
// get user account information - login --check-status
details, err := la.authManager.LogInDetails(ctx)
// error getting user account or not logged in
if err != nil {
log.Printf("error: getting signed in account: %v", err)
fmt.Fprintln(la.console.Handles().Stdout, msg)
return nil, nil
}
// only print the message if the user is logged in
la.console.MessageUxItem(ctx, &ux.LoggedIn{
LoggedInAs: details.Account,
LoginType: ux.LoginType(details.LoginType),
})
return nil, nil
}
}
// When already logged in (or when login state cannot be determined due to corrupted cache),
// clear cached auth data before re-authenticating. This prevents issues with stale MSAL
// tokens or corrupted credential cache files that can cause AADSTS700082 errors even after
// a successful login. Only skip cleanup when definitively not logged in.
if _, err := la.authManager.LogInDetails(ctx); !errors.Is(err, auth.ErrNoCurrentUser) {
if err := la.authManager.CleanAllAuthCache(); err != nil {
tracing.SetUsageAttributes(attribute.String("auth.cache_clear_failed", "auth"))
return nil, fmt.Errorf("clearing auth cache: %w", err)
}
if err := la.accountSubManager.ClearSubscriptions(ctx); err != nil {
tracing.SetUsageAttributes(attribute.String("auth.cache_clear_failed", "subscriptions"))
return nil, fmt.Errorf("clearing subscriptions cache: %w", err)
}
}
if err := la.login(ctx); err != nil {
return nil, err
}
if _, err := la.verifyLoggedIn(ctx); err != nil {
return nil, err
}
forceRefresh := false
if v, err := strconv.ParseBool(os.Getenv("AZD_DEBUG_LOGIN_FORCE_SUBSCRIPTION_REFRESH")); err == nil && v {
forceRefresh = true
}
if la.flags.clientID == "" || forceRefresh {
// Update the subscriptions cache for regular users (i.e. non-service-principals).
// The caching is done here to increase responsiveness of listing subscriptions in the application.
// It also allows an implicit command for the user to refresh cached subscriptions.
if err := la.accountSubManager.RefreshSubscriptions(ctx); err != nil {
// If this fails, the subscriptions will still be loaded on-demand.
// erroring out when the user interacts with subscriptions is much more user-friendly.
log.Printf("failed retrieving subscriptions: %v", err)
}
}
details, err := la.authManager.LogInDetails(ctx)
// error getting user account, successful log in
if err != nil {
log.Printf("error: getting signed in account: %v", err)
la.console.Message(ctx, "Logged in to Azure")
return nil, nil
}
la.console.MessageUxItem(ctx, &ux.LoggedIn{
LoggedInAs: details.Account,
LoginType: ux.LoginType(details.LoginType),
})
return nil, nil
}
// Verifies that the user has credentials stored,
// and that the credentials stored is accepted by the identity server (can be exchanged for access token).
func (la *loginAction) verifyLoggedIn(ctx context.Context) (*azcore.AccessToken, error) {
credOptions := auth.CredentialForCurrentUserOptions{
TenantID: la.flags.tenantID,
}
cred, err := la.authManager.CredentialForCurrentUser(ctx, &credOptions)
if err != nil {
return nil, err
}
// Ensure credential is valid, and can be exchanged for an access token
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: la.flags.scopes,
})
if err != nil {
return nil, err
}
return &token, nil
}
func countTrue(elms ...bool) int {
i := 0
for _, elm := range elms {
if elm {
i++
}
}
return i
}
// runningOnCodespacesBrowser use `code --status` which returns:
//
// > The --status argument is not yet supported in browsers.
//
// to detect when vscode is within a WebBrowser environment.
func runningOnCodespacesBrowser(ctx context.Context, commandRunner exec.CommandRunner) bool {
runArgs := exec.NewRunArgs("code", "--status")
result, err := commandRunner.Run(ctx, runArgs)
if err != nil {
// An error here means VSCode is not installed or found, or something else.
// At any case, we know VSCode is not within a webBrowser
log.Printf("error running code --status: %v", err)
return false
}
return strings.Contains(result.Stdout, "The --status argument is not yet supported in browsers")
}
func (la *loginAction) login(ctx context.Context) error {
// Track tenant ID if provided (before resolving from env vars)
if la.flags.tenantID != "" {
tracing.SetUsageAttributes(fields.TenantIdKey.String(la.flags.tenantID))
}
if la.flags.federatedTokenProvider == azurePipelinesProvider {
if la.flags.clientID == "" {
log.Printf("setting client id from environment variable %s", azurePipelinesClientIDEnvVarName)
la.flags.clientID = os.Getenv(azurePipelinesClientIDEnvVarName)
}
if la.flags.tenantID == "" {
log.Printf("setting tenant id from environment variable %s", azurePipelinesClientIDEnvVarName)
la.flags.tenantID = os.Getenv(azurePipelinesTenantIDEnvVarName)
}
}
if la.flags.managedIdentity {
tracing.SetUsageAttributes(fields.AuthMethodKey.String("managed-identity"))
if _, err := la.authManager.LoginWithManagedIdentity(
ctx, la.flags.clientID,
); err != nil {
return fmt.Errorf("logging in: %w", err)
}
return nil
}
if !la.flags.managedIdentity && la.flags.clientID != "" {
if la.flags.tenantID == "" {
return errors.New("must set both `client-id` and `tenant-id` for service principal login")
}
if countTrue(
la.flags.clientSecret.ptr != nil,
la.flags.clientCertificate != "",
la.flags.federatedTokenProvider != "",
) != 1 {
return fmt.Errorf(
"must set exactly one of %s for service principal", strings.Join([]string{
cClientSecretFlagName,
cClientCertificateFlagName,
cFederatedCredentialProviderFlagName,
}, ", "))
}
switch {
case la.flags.clientSecret.ptr != nil:
tracing.SetUsageAttributes(fields.AuthMethodKey.String("service-principal-secret"))
if *la.flags.clientSecret.ptr == "" {
v, err := la.console.Prompt(ctx, input.ConsoleOptions{
Message: "Enter your client secret",
})
if err != nil {
return fmt.Errorf("prompting for client secret: %w", err)
}
la.flags.clientSecret.ptr = &v
}
if _, err := la.authManager.LoginWithServicePrincipalSecret(
ctx, la.flags.tenantID, la.flags.clientID, *la.flags.clientSecret.ptr,
); err != nil {
return fmt.Errorf("logging in: %w", err)
}
case la.flags.clientCertificate != "":
tracing.SetUsageAttributes(fields.AuthMethodKey.String("service-principal-certificate"))
certFile, err := os.Open(la.flags.clientCertificate)
if err != nil {
return fmt.Errorf("reading certificate: %w", err)
}
defer certFile.Close()
cert, err := io.ReadAll(certFile)
if err != nil {
return fmt.Errorf("reading certificate: %w", err)
}
if _, err := la.authManager.LoginWithServicePrincipalCertificate(
ctx, la.flags.tenantID, la.flags.clientID, cert,
); err != nil {
return fmt.Errorf("logging in: %w", err)
}
case la.flags.federatedTokenProvider == "github":
tracing.SetUsageAttributes(fields.AuthMethodKey.String("federated-github"))
if _, err := la.authManager.LoginWithGitHubFederatedTokenProvider(
ctx, la.flags.tenantID, la.flags.clientID,
); err != nil {
return fmt.Errorf("logging in: %w", err)
}
case la.flags.federatedTokenProvider == azurePipelinesProvider:
tracing.SetUsageAttributes(fields.AuthMethodKey.String("federated-azure-pipelines"))
serviceConnectionID := os.Getenv(azurePipelinesServiceConnectionIDEnvVarName)
if serviceConnectionID == "" {
return fmt.Errorf("must set %s for azure-pipelines federated token provider",
azurePipelinesServiceConnectionIDEnvVarName)
}
if _, err := la.authManager.LoginWithAzurePipelinesFederatedTokenProvider(
ctx, la.flags.tenantID, la.flags.clientID, serviceConnectionID,
); err != nil {
return fmt.Errorf("logging in: %w", err)
}
case la.flags.federatedTokenProvider == "oidc": // generic oidc provider
tracing.SetUsageAttributes(fields.AuthMethodKey.String("federated-oidc"))
if _, err := la.authManager.LoginWithOidcFederatedTokenProvider(
ctx, la.flags.tenantID, la.flags.clientID,
); err != nil {
return fmt.Errorf("logging in: %w", err)
}
}
return nil
}
if la.authManager.UseExternalAuth() {
tracing.SetUsageAttributes(fields.AuthMethodKey.String("external"))
// Request a token and assume the external auth system will prompt the user to log in.
//
// TODO(ellismg): We may want instead to call some explicit `/login` endpoint on the external auth system instead
// of abusing the token request in this manner. This would allow the other end to provide a more tailored experience.
_, err := la.verifyLoggedIn(ctx)
return err
}
useDevCode, err := parseUseDeviceCode(ctx, la.flags.useDeviceCode, la.commandRunner)
if err != nil {
return err
}
claims := ""
if la.flags.claims != "" {
c, err := base64.StdEncoding.DecodeString(la.flags.claims)
if err != nil {
return fmt.Errorf("invalid claims '%s': expected a base64-encoded string", la.flags.claims)
}
claims = string(c)
}
if useDevCode {
tracing.SetUsageAttributes(fields.AuthMethodKey.String("device-code"))
_, err = la.authManager.LoginWithDeviceCode(ctx, la.flags.tenantID, la.flags.scopes, claims,
func(url string) error {
if !la.flags.global.NoPrompt {
la.console.Message(ctx, "Then press enter and continue to log in from your browser...")
la.console.WaitForEnter()
openWithDefaultBrowser(ctx, la.console, url)
return nil
}
// For no-prompt, Just provide instructions without trying to open the browser
// If manual browsing is enabled, we don't want to open the browser automatically
la.console.Message(ctx, fmt.Sprintf("Then, go to: %s", url))
return nil
})
return err
}
if oneauth.Supported && !la.flags.browser {
tracing.SetUsageAttributes(fields.AuthMethodKey.String("oneauth"))
err = la.authManager.LoginWithOneAuth(ctx, la.flags.tenantID, la.flags.scopes)
} else {
tracing.SetUsageAttributes(fields.AuthMethodKey.String("browser"))
_, err = la.authManager.LoginInteractive(ctx, la.flags.scopes, claims,
&auth.LoginInteractiveOptions{
TenantID: la.flags.tenantID,
RedirectPort: la.flags.redirectPort,
WithOpenUrl: func(url string) error {
openWithDefaultBrowser(ctx, la.console, url)
return nil
},
})
}
if err != nil {
err = fmt.Errorf("logging in: %w", err)
}
return err
}
func parseUseDeviceCode(ctx context.Context, flag boolPtr, commandRunner exec.CommandRunner) (bool, error) {
var useDevCode bool
useDevCodeFlag := flag.ptr != nil
if useDevCodeFlag {
userInput, err := strconv.ParseBool(*flag.ptr)
if err != nil {
return false, fmt.Errorf("unexpected boolean input for '--use-device-code': %w", err)
}
// honor the value from the user input. No override.
return userInput, err
}
// Detect cases where the browser isn't available for interactive auth, and we instead want to set `useDeviceCode`
// to be true by default
if github.RunningOnCodespaces() {
// For VSCode online (in web Browser), like GitHub Codespaces or VSCode online attached to any server,
// interactive browser login will 404 when attempting to redirect to localhost
// (since azd launches a localhost server running remotely and the login response is accepted locally).
// Hence, we override login to device-code. See https://github.com/Azure/azure-dev/issues/1006
useDevCode = runningOnCodespacesBrowser(ctx, commandRunner)
}
if runcontext.IsRunningInCloudShell() {
// Following az CLI behavior in Cloud Shell, use device code authentication when the user is trying to
// authenticate. The normal interactive authentication flow will not work in Cloud Shell because the browser
// cannot be opened or (if it could) cannot be redirected back to a port on the Cloud Shell instance.
return true, nil
}
return useDevCode, nil
}