Debian Codegraph @

apps/public/public.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright (c) Microsoft Corporation.
2 // Licensed under the MIT license.
3
4 /*
5 Package public provides a client for authentication of "public" applications. A "public"
6 application is defined as an app that runs on client devices (android, ios, windows, linux, ...).
7 These devices are "untrusted" and access resources via web APIs that must authenticate.
8 */
9 package public
10
11 /*
12 Design note:
13
14 public.Client uses client.Base as an embedded type. client.Base statically assigns its attributes
15 during creation. As it doesn't have any pointers in it, anything borrowed from it, such as
16 Base.AuthParams is a copy that is free to be manipulated here.
17 */
18
19 // TODO(msal): This should have example code for each method on client using Go's example doc framework.
20 // base usage details should be includee in the package documentation.
21
22 import (
23 "context"
24 "crypto/rand"
25 "crypto/sha256"
26 "encoding/base64"
27 "fmt"
28 "net/url"
29 "strconv"
30
31 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/cache"
32 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/base"
33 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/local"
34 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth"
35 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops"
36 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/accesstokens"
37 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/oauth/ops/authority"
38 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/options"
39 "github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/shared"
40 "github.com/google/uuid"
41 "github.com/pkg/browser"
42 )
43
44 // AuthResult contains the results of one token acquisition operation.
45 // For details see https://aka.ms/msal-net-authenticationresult
46 type AuthResult = base.AuthResult
47
48 type Account = shared.Account
49
50 // clientOptions configures the Client's behavior.
51 type clientOptions struct {
52 accessor cache.ExportReplace
53 authority string
54 capabilities []string
55 disableInstanceDiscovery bool
56 httpClient ops.HTTPClient
57 }
58
59 func (p *clientOptions) validate() error {
60 u, err := url.Parse(p.authority)
61 if err != nil {
62 return fmt.Errorf("Authority options cannot be URL parsed: %w", err)
63 }
64 if u.Scheme != "https" {
65 return fmt.Errorf("Authority(%s) did not start with https://", u.String())
66 }
67 return nil
68 }
69
70 // Option is an optional argument to the New constructor.
71 type Option func(o *clientOptions)
72
73 // WithAuthority allows for a custom authority to be set. This must be a valid https url.
74 func WithAuthority(authority string) Option {
75 return func(o *clientOptions) {
76 o.authority = authority
77 }
78 }
79
80 // WithCache provides an accessor that will read and write authentication data to an externally managed cache.
81 func WithCache(accessor cache.ExportReplace) Option {
82 return func(o *clientOptions) {
83 o.accessor = accessor
84 }
85 }
86
87 // WithClientCapabilities allows configuring one or more client capabilities such as "CP1"
88 func WithClientCapabilities(capabilities []string) Option {
89 return func(o *clientOptions) {
90 // there's no danger of sharing the slice's underlying memory with the application because
91 // this slice is simply passed to base.WithClientCapabilities, which copies its data
92 o.capabilities = capabilities
93 }
94 }
95
96 // WithHTTPClient allows for a custom HTTP client to be set.
97 func WithHTTPClient(httpClient ops.HTTPClient) Option {
98 return func(o *clientOptions) {
99 o.httpClient = httpClient
100 }
101 }
102
103 // WithInstanceDiscovery set to false to disable authority validation (to support private cloud scenarios)
104 func WithInstanceDiscovery(enabled bool) Option {
105 return func(o *clientOptions) {
106 o.disableInstanceDiscovery = !enabled
107 }
108 }
109
110 // Client is a representation of authentication client for public applications as defined in the
111 // package doc. For more information, visit https://docs.microsoft.com/azure/active-directory/develop/msal-client-applications.
112 type Client struct {
113 base base.Client
114 }
115
116 // New is the constructor for Client.
117 func New(clientID string, options ...Option) (Client, error) {
118 opts := clientOptions{
119 authority: base.AuthorityPublicCloud,
120 httpClient: shared.DefaultClient,
121 }
122
123 for _, o := range options {
124 o(&opts)
125 }
126 if err := opts.validate(); err != nil {
127 return Client{}, err
128 }
129
130 base, err := base.New(clientID, opts.authority, oauth.New(opts.httpClient), base.WithCacheAccessor(opts.accessor), base.WithClientCapabilities(opts.capabilities), base.WithInstanceDiscovery(!opts.disableInstanceDiscovery))
131 if err != nil {
132 return Client{}, err
133 }
134 return Client{base}, nil
135 }
136
137 // authCodeURLOptions contains options for AuthCodeURL
138 type authCodeURLOptions struct {
139 claims, loginHint, tenantID, domainHint string
140 }
141
142 // AuthCodeURLOption is implemented by options for AuthCodeURL
143 type AuthCodeURLOption interface {
144 authCodeURLOption()
145 }
146
147 // AuthCodeURL creates a URL used to acquire an authorization code.
148 //
149 // Options: [WithClaims], [WithDomainHint], [WithLoginHint], [WithTenantID]
150 func (pca Client) AuthCodeURL(ctx context.Context, clientID, redirectURI string, scopes []string, opts ...AuthCodeURLOption) (string, error) {
151 o := authCodeURLOptions{}
152 if err := options.ApplyOptions(&o, opts); err != nil {
153 return "", err
154 }
155 ap, err := pca.base.AuthParams.WithTenant(o.tenantID)
156 if err != nil {
157 return "", err
158 }
159 ap.Claims = o.claims
160 ap.LoginHint = o.loginHint
161 ap.DomainHint = o.domainHint
162 return pca.base.AuthCodeURL(ctx, clientID, redirectURI, scopes, ap)
163 }
164
165 // WithClaims sets additional claims to request for the token, such as those required by conditional access policies.
166 // Use this option when Azure AD returned a claims challenge for a prior request. The argument must be decoded.
167 // This option is valid for any token acquisition method.
168 func WithClaims(claims string) interface {
169 AcquireByAuthCodeOption
170 AcquireByDeviceCodeOption
171 AcquireByUsernamePasswordOption
172 AcquireInteractiveOption
173 AcquireSilentOption
174 AuthCodeURLOption
175 options.CallOption
176 } {
177 return struct {
178 AcquireByAuthCodeOption
179 AcquireByDeviceCodeOption
180 AcquireByUsernamePasswordOption
181 AcquireInteractiveOption
182 AcquireSilentOption
183 AuthCodeURLOption
184 options.CallOption
185 }{
186 CallOption: options.NewCallOption(
187 func(a any) error {
188 switch t := a.(type) {
189 case *acquireTokenByAuthCodeOptions:
190 t.claims = claims
191 case *acquireTokenByDeviceCodeOptions:
192 t.claims = claims
193 case *acquireTokenByUsernamePasswordOptions:
194 t.claims = claims
195 case *acquireTokenSilentOptions:
196 t.claims = claims
197 case *authCodeURLOptions:
198 t.claims = claims
199 case *interactiveAuthOptions:
200 t.claims = claims
201 default:
202 return fmt.Errorf("unexpected options type %T", a)
203 }
204 return nil
205 },
206 ),
207 }
208 }
209
210 // WithTenantID specifies a tenant for a single authentication. It may be different than the tenant set in [New] by [WithAuthority].
211 // This option is valid for any token acquisition method.
212 func WithTenantID(tenantID string) interface {
213 AcquireByAuthCodeOption
214 AcquireByDeviceCodeOption
215 AcquireByUsernamePasswordOption
216 AcquireInteractiveOption
217 AcquireSilentOption
218 AuthCodeURLOption
219 options.CallOption
220 } {
221 return struct {
222 AcquireByAuthCodeOption
223 AcquireByDeviceCodeOption
224 AcquireByUsernamePasswordOption
225 AcquireInteractiveOption
226 AcquireSilentOption
227 AuthCodeURLOption
228 options.CallOption
229 }{
230 CallOption: options.NewCallOption(
231 func(a any) error {
232 switch t := a.(type) {
233 case *acquireTokenByAuthCodeOptions:
234 t.tenantID = tenantID
235 case *acquireTokenByDeviceCodeOptions:
236 t.tenantID = tenantID
237 case *acquireTokenByUsernamePasswordOptions:
238 t.tenantID = tenantID
239 case *acquireTokenSilentOptions:
240 t.tenantID = tenantID
241 case *authCodeURLOptions:
242 t.tenantID = tenantID
243 case *interactiveAuthOptions:
244 t.tenantID = tenantID
245 default:
246 return fmt.Errorf("unexpected options type %T", a)
247 }
248 return nil
249 },
250 ),
251 }
252 }
253
254 // acquireTokenSilentOptions are all the optional settings to an AcquireTokenSilent() call.
255 // These are set by using various AcquireTokenSilentOption functions.
256 type acquireTokenSilentOptions struct {
257 account Account
258 claims, tenantID string
259 }
260
261 // AcquireSilentOption is implemented by options for AcquireTokenSilent
262 type AcquireSilentOption interface {
263 acquireSilentOption()
264 }
265
266 // WithSilentAccount uses the passed account during an AcquireTokenSilent() call.
267 func WithSilentAccount(account Account) interface {
268 AcquireSilentOption
269 options.CallOption
270 } {
271 return struct {
272 AcquireSilentOption
273 options.CallOption
274 }{
275 CallOption: options.NewCallOption(
276 func(a any) error {
277 switch t := a.(type) {
278 case *acquireTokenSilentOptions:
279 t.account = account
280 default:
281 return fmt.Errorf("unexpected options type %T", a)
282 }
283 return nil
284 },
285 ),
286 }
287 }
288
289 // AcquireTokenSilent acquires a token from either the cache or using a refresh token.
290 //
291 // Options: [WithClaims], [WithSilentAccount], [WithTenantID]
292 func (pca Client) AcquireTokenSilent(ctx context.Context, scopes []string, opts ...AcquireSilentOption) (AuthResult, error) {
293 o := acquireTokenSilentOptions{}
294 if err := options.ApplyOptions(&o, opts); err != nil {
295 return AuthResult{}, err
296 }
297
298 silentParameters := base.AcquireTokenSilentParameters{
299 Scopes: scopes,
300 Account: o.account,
301 Claims: o.claims,
302 RequestType: accesstokens.ATPublic,
303 IsAppCache: false,
304 TenantID: o.tenantID,
305 }
306
307 return pca.base.AcquireTokenSilent(ctx, silentParameters)
308 }
309
310 // acquireTokenByUsernamePasswordOptions contains optional configuration for AcquireTokenByUsernamePassword
311 type acquireTokenByUsernamePasswordOptions struct {
312 claims, tenantID string
313 }
314
315 // AcquireByUsernamePasswordOption is implemented by options for AcquireTokenByUsernamePassword
316 type AcquireByUsernamePasswordOption interface {
317 acquireByUsernamePasswordOption()
318 }
319
320 // AcquireTokenByUsernamePassword acquires a security token from the authority, via Username/Password Authentication.
321 // NOTE: this flow is NOT recommended.
322 //
323 // Options: [WithClaims], [WithTenantID]
324 func (pca Client) AcquireTokenByUsernamePassword(ctx context.Context, scopes []string, username, password string, opts ...AcquireByUsernamePasswordOption) (AuthResult, error) {
325 o := acquireTokenByUsernamePasswordOptions{}
326 if err := options.ApplyOptions(&o, opts); err != nil {
327 return AuthResult{}, err
328 }
329 authParams, err := pca.base.AuthParams.WithTenant(o.tenantID)
330 if err != nil {
331 return AuthResult{}, err
332 }
333 authParams.Scopes = scopes
334 authParams.AuthorizationType = authority.ATUsernamePassword
335 authParams.Claims = o.claims
336 authParams.Username = username
337 authParams.Password = password
338
339 token, err := pca.base.Token.UsernamePassword(ctx, authParams)
340 if err != nil {
341 return AuthResult{}, err
342 }
343 return pca.base.AuthResultFromToken(ctx, authParams, token, true)
344 }
345
346 type DeviceCodeResult = accesstokens.DeviceCodeResult
347
348 // DeviceCode provides the results of the device code flows first stage (containing the code)
349 // that must be entered on the second device and provides a method to retrieve the AuthenticationResult
350 // once that code has been entered and verified.
351 type DeviceCode struct {
352 // Result holds the information about the device code (such as the code).
353 Result DeviceCodeResult
354
355 authParams authority.AuthParams
356 client Client
357 dc oauth.DeviceCode
358 }
359
360 // AuthenticationResult retreives the AuthenticationResult once the user enters the code
361 // on the second device. Until then it blocks until the .AcquireTokenByDeviceCode() context
362 // is cancelled or the token expires.
363 func (d DeviceCode) AuthenticationResult(ctx context.Context) (AuthResult, error) {
364 token, err := d.dc.Token(ctx)
365 if err != nil {
366 return AuthResult{}, err
367 }
368 return d.client.base.AuthResultFromToken(ctx, d.authParams, token, true)
369 }
370
371 // acquireTokenByDeviceCodeOptions contains optional configuration for AcquireTokenByDeviceCode
372 type acquireTokenByDeviceCodeOptions struct {
373 claims, tenantID string
374 }
375
376 // AcquireByDeviceCodeOption is implemented by options for AcquireTokenByDeviceCode
377 type AcquireByDeviceCodeOption interface {
378 acquireByDeviceCodeOptions()
379 }
380
381 // AcquireTokenByDeviceCode acquires a security token from the authority, by acquiring a device code and using that to acquire the token.
382 // Users need to create an AcquireTokenDeviceCodeParameters instance and pass it in.
383 //
384 // Options: [WithClaims], [WithTenantID]
385 func (pca Client) AcquireTokenByDeviceCode(ctx context.Context, scopes []string, opts ...AcquireByDeviceCodeOption) (DeviceCode, error) {
386 o := acquireTokenByDeviceCodeOptions{}
387 if err := options.ApplyOptions(&o, opts); err != nil {
388 return DeviceCode{}, err
389 }
390 authParams, err := pca.base.AuthParams.WithTenant(o.tenantID)
391 if err != nil {
392 return DeviceCode{}, err
393 }
394 authParams.Scopes = scopes
395 authParams.AuthorizationType = authority.ATDeviceCode
396 authParams.Claims = o.claims
397
398 dc, err := pca.base.Token.DeviceCode(ctx, authParams)
399 if err != nil {
400 return DeviceCode{}, err
401 }
402
403 return DeviceCode{Result: dc.Result, authParams: authParams, client: pca, dc: dc}, nil
404 }
405
406 // acquireTokenByAuthCodeOptions contains the optional parameters used to acquire an access token using the authorization code flow.
407 type acquireTokenByAuthCodeOptions struct {
408 challenge, claims, tenantID string
409 }
410
411 // AcquireByAuthCodeOption is implemented by options for AcquireTokenByAuthCode
412 type AcquireByAuthCodeOption interface {
413 acquireByAuthCodeOption()
414 }
415
416 // WithChallenge allows you to provide a code for the .AcquireTokenByAuthCode() call.
417 func WithChallenge(challenge string) interface {
418 AcquireByAuthCodeOption
419 options.CallOption
420 } {
421 return struct {
422 AcquireByAuthCodeOption
423 options.CallOption
424 }{
425 CallOption: options.NewCallOption(
426 func(a any) error {
427 switch t := a.(type) {
428 case *acquireTokenByAuthCodeOptions:
429 t.challenge = challenge
430 default:
431 return fmt.Errorf("unexpected options type %T", a)
432 }
433 return nil
434 },
435 ),
436 }
437 }
438
439 // AcquireTokenByAuthCode is a request to acquire a security token from the authority, using an authorization code.
440 // The specified redirect URI must be the same URI that was used when the authorization code was requested.
441 //
442 // Options: [WithChallenge], [WithClaims], [WithTenantID]
443 func (pca Client) AcquireTokenByAuthCode(ctx context.Context, code string, redirectURI string, scopes []string, opts ...AcquireByAuthCodeOption) (AuthResult, error) {
444 o := acquireTokenByAuthCodeOptions{}
445 if err := options.ApplyOptions(&o, opts); err != nil {
446 return AuthResult{}, err
447 }
448
449 params := base.AcquireTokenAuthCodeParameters{
450 Scopes: scopes,
451 Code: code,
452 Challenge: o.challenge,
453 Claims: o.claims,
454 AppType: accesstokens.ATPublic,
455 RedirectURI: redirectURI,
456 TenantID: o.tenantID,
457 }
458
459 return pca.base.AcquireTokenByAuthCode(ctx, params)
460 }
461
462 // Accounts gets all the accounts in the token cache.
463 // If there are no accounts in the cache the returned slice is empty.
464 func (pca Client) Accounts(ctx context.Context) ([]Account, error) {
465 return pca.base.AllAccounts(ctx)
466 }
467
468 // RemoveAccount signs the account out and forgets account from token cache.
469 func (pca Client) RemoveAccount(ctx context.Context, account Account) error {
470 return pca.base.RemoveAccount(ctx, account)
471 }
472
473 // interactiveAuthOptions contains the optional parameters used to acquire an access token for interactive auth code flow.
474 type interactiveAuthOptions struct {
475 claims, domainHint, loginHint, redirectURI, tenantID string
476 }
477
478 // AcquireInteractiveOption is implemented by options for AcquireTokenInteractive
479 type AcquireInteractiveOption interface {
480 acquireInteractiveOption()
481 }
482
483 // WithLoginHint pre-populates the login prompt with a username.
484 func WithLoginHint(username string) interface {
485 AcquireInteractiveOption
486 AuthCodeURLOption
487 options.CallOption
488 } {
489 return struct {
490 AcquireInteractiveOption
491 AuthCodeURLOption
492 options.CallOption
493 }{
494 CallOption: options.NewCallOption(
495 func(a any) error {
496 switch t := a.(type) {
497 case *authCodeURLOptions:
498 t.loginHint = username
499 case *interactiveAuthOptions:
500 t.loginHint = username
501 default:
502 return fmt.Errorf("unexpected options type %T", a)
503 }
504 return nil
505 },
506 ),
507 }
508 }
509
510 // WithDomainHint adds the IdP domain as domain_hint query parameter in the auth url.
511 func WithDomainHint(domain string) interface {
512 AcquireInteractiveOption
513 AuthCodeURLOption
514 options.CallOption
515 } {
516 return struct {
517 AcquireInteractiveOption
518 AuthCodeURLOption
519 options.CallOption
520 }{
521 CallOption: options.NewCallOption(
522 func(a any) error {
523 switch t := a.(type) {
524 case *authCodeURLOptions:
525 t.domainHint = domain
526 case *interactiveAuthOptions:
527 t.domainHint = domain
528 default:
529 return fmt.Errorf("unexpected options type %T", a)
530 }
531 return nil
532 },
533 ),
534 }
535 }
536
537 // WithRedirectURI sets a port for the local server used in interactive authentication, for
538 // example http://localhost:port. All URI components other than the port are ignored.
539 func WithRedirectURI(redirectURI string) interface {
540 AcquireInteractiveOption
541 options.CallOption
542 } {
543 return struct {
544 AcquireInteractiveOption
545 options.CallOption
546 }{
547 CallOption: options.NewCallOption(
548 func(a any) error {
549 switch t := a.(type) {
550 case *interactiveAuthOptions:
551 t.redirectURI = redirectURI
552 default:
553 return fmt.Errorf("unexpected options type %T", a)
554 }
555 return nil
556 },
557 ),
558 }
559 }
560
561 // AcquireTokenInteractive acquires a security token from the authority using the default web browser to select the account.
562 // https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#interactive-and-non-interactive-authentication
563 //
564 // Options: [WithDomainHint], [WithLoginHint], [WithRedirectURI], [WithTenantID]
565 func (pca Client) AcquireTokenInteractive(ctx context.Context, scopes []string, opts ...AcquireInteractiveOption) (AuthResult, error) {
566 o := interactiveAuthOptions{}
567 if err := options.ApplyOptions(&o, opts); err != nil {
568 return AuthResult{}, err
569 }
570 // the code verifier is a random 32-byte sequence that's been base-64 encoded without padding.
571 // it's used to prevent MitM attacks during auth code flow, see https://tools.ietf.org/html/rfc7636
572 cv, challenge, err := codeVerifier()
573 if err != nil {
574 return AuthResult{}, err
575 }
576 var redirectURL *url.URL
577 if o.redirectURI != "" {
578 redirectURL, err = url.Parse(o.redirectURI)
579 if err != nil {
580 return AuthResult{}, err
581 }
582 }
583 authParams, err := pca.base.AuthParams.WithTenant(o.tenantID)
584 if err != nil {
585 return AuthResult{}, err
586 }
587 authParams.Scopes = scopes
588 authParams.AuthorizationType = authority.ATInteractive
589 authParams.Claims = o.claims
590 authParams.CodeChallenge = challenge
591 authParams.CodeChallengeMethod = "S256"
592 authParams.LoginHint = o.loginHint
593 authParams.DomainHint = o.domainHint
594 authParams.State = uuid.New().String()
595 authParams.Prompt = "select_account"
596 res, err := pca.browserLogin(ctx, redirectURL, authParams)
597 if err != nil {
598 return AuthResult{}, err
599 }
600 authParams.Redirecturi = res.redirectURI
601
602 req, err := accesstokens.NewCodeChallengeRequest(authParams, accesstokens.ATPublic, nil, res.authCode, cv)
603 if err != nil {
604 return AuthResult{}, err
605 }
606
607 token, err := pca.base.Token.AuthCode(ctx, req)
608 if err != nil {
609 return AuthResult{}, err
610 }
611
612 return pca.base.AuthResultFromToken(ctx, authParams, token, true)
613 }
614
615 type interactiveAuthResult struct {
616 authCode string
617 redirectURI string
618 }
619
620 // provides a test hook to simulate opening a browser
621 var browserOpenURL = func(authURL string) error {
622 return browser.OpenURL(authURL)
623 }
624
625 // parses the port number from the provided URL.
626 // returns 0 if nil or no port is specified.
627 func parsePort(u *url.URL) (int, error) {
628 if u == nil {
629 return 0, nil
630 }
631 p := u.Port()
632 if p == "" {
633 return 0, nil
634 }
635 return strconv.Atoi(p)
636 }
637
638 // browserLogin launches the system browser for interactive login
639 func (pca Client) browserLogin(ctx context.Context, redirectURI *url.URL, params authority.AuthParams) (interactiveAuthResult, error) {
640 // start local redirect server so login can call us back
641 port, err := parsePort(redirectURI)
642 if err != nil {
643 return interactiveAuthResult{}, err
644 }
645 srv, err := local.New(params.State, port)
646 if err != nil {
647 return interactiveAuthResult{}, err
648 }
649 defer srv.Shutdown()
650 params.Scopes = accesstokens.AppendDefaultScopes(params)
651 authURL, err := pca.base.AuthCodeURL(ctx, params.ClientID, srv.Addr, params.Scopes, params)
652 if err != nil {
653 return interactiveAuthResult{}, err
654 }
655 // open browser window so user can select credentials
656 if err := browserOpenURL(authURL); err != nil {
657 return interactiveAuthResult{}, err
658 }
659 // now wait until the logic calls us back
660 res := srv.Result(ctx)
661 if res.Err != nil {
662 return interactiveAuthResult{}, res.Err
663 }
664 return interactiveAuthResult{
665 authCode: res.Code,
666 redirectURI: srv.Addr,
667 }, nil
668 }
669
670 // creates a code verifier string along with its SHA256 hash which
671 // is used as the challenge when requesting an auth code.
672 // used in interactive auth flow for PKCE.
673 func codeVerifier() (codeVerifier string, challenge string, err error) {
674 cvBytes := make([]byte, 32)
675 if _, err = rand.Read(cvBytes); err != nil {
676 return
677 }
678 codeVerifier = base64.RawURLEncoding.EncodeToString(cvBytes)
679 // for PKCE, create a hash of the code verifier
680 cvh := sha256.Sum256([]byte(codeVerifier))
681 challenge = base64.RawURLEncoding.EncodeToString(cvh[:])
682 return
683 }