Update based on azcore refactor (#15383)

Fixed some linter warnings.
Renamed UserAgent to component per new telemetry policy.
Version const is no longer exported.
This commit is contained in:
Joel Hendrix 2021-08-30 11:21:55 -07:00 коммит произвёл GitHub
Родитель d1dcbd5088
Коммит af32bacab1
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
32 изменённых файлов: 369 добавлений и 338 удалений

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

@ -95,7 +95,7 @@
## v0.2.0 (2020-09-11)
### Features Added
* Refactor `azidentity` on top of `azcore` refactor
* Updated policies to conform to `azcore.Policy` interface changes.
* Updated policies to conform to `policy.Policy` interface changes.
* Updated non-retriable errors to conform to `azcore.NonRetriableError`.
* Fixed calls to `Request.SetBody()` to include content type.
* Switched endpoints to string types and removed extra parsing code.

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

@ -14,6 +14,9 @@ import (
"time"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
)
const (
@ -45,10 +48,10 @@ type interactiveConfig struct {
}
// aadIdentityClient provides the base for authenticating with Client Secret Credentials, Client Certificate Credentials
// and Environment Credentials. This type includes an azcore.Pipeline and TokenCredentialOptions.
// and Environment Credentials. This type includes an runtime.Pipeline and TokenCredentialOptions.
type aadIdentityClient struct {
authorityHost string
pipeline azcore.Pipeline
pipeline runtime.Pipeline
}
// newAADIdentityClient creates a new instance of the aadIdentityClient with the TokenCredentialOptions
@ -57,11 +60,6 @@ type aadIdentityClient struct {
// will be used to retrieve tokens and authenticate
func newAADIdentityClient(authorityHost string, options pipelineOptions) (*aadIdentityClient, error) {
logEnvVars()
if options.Telemetry.Value == "" {
options.Telemetry.Value = UserAgent
} else {
options.Telemetry.Value += " " + UserAgent
}
return &aadIdentityClient{authorityHost: authorityHost, pipeline: newDefaultPipeline(options)}, nil
}
@ -83,7 +81,7 @@ func (c *aadIdentityClient) refreshAccessToken(ctx context.Context, tenantID str
return nil, err
}
if azcore.HasStatusCode(resp, successStatusCodes[:]...) {
if runtime.HasStatusCode(resp, successStatusCodes[:]...) {
return c.createRefreshAccessToken(resp)
}
@ -108,7 +106,7 @@ func (c *aadIdentityClient) authenticate(ctx context.Context, tenantID string, c
return nil, err
}
if azcore.HasStatusCode(resp, successStatusCodes[:]...) {
if runtime.HasStatusCode(resp, successStatusCodes[:]...) {
return c.createAccessToken(resp)
}
@ -133,7 +131,7 @@ func (c *aadIdentityClient) authenticateCertificate(ctx context.Context, tenantI
return nil, err
}
if azcore.HasStatusCode(resp, successStatusCodes[:]...) {
if runtime.HasStatusCode(resp, successStatusCodes[:]...) {
return c.createAccessToken(resp)
}
@ -146,7 +144,7 @@ func (c *aadIdentityClient) createAccessToken(res *http.Response) (*azcore.Acces
ExpiresIn json.Number `json:"expires_in"`
ExpiresOn string `json:"expires_on"`
}{}
if err := azcore.UnmarshalAsJSON(res, &value); err != nil {
if err := runtime.UnmarshalAsJSON(res, &value); err != nil {
return nil, fmt.Errorf("internal AccessToken: %w", err)
}
t, err := value.ExpiresIn.Int64()
@ -168,7 +166,7 @@ func (c *aadIdentityClient) createRefreshAccessToken(res *http.Response) (*token
ExpiresIn json.Number `json:"expires_in"`
ExpiresOn string `json:"expires_on"`
}{}
if err := azcore.UnmarshalAsJSON(res, &value); err != nil {
if err := runtime.UnmarshalAsJSON(res, &value); err != nil {
return nil, fmt.Errorf("internal AccessToken: %w", err)
}
t, err := value.ExpiresIn.Int64()
@ -182,7 +180,7 @@ func (c *aadIdentityClient) createRefreshAccessToken(res *http.Response) (*token
return &tokenResponse{token: accessToken, refreshToken: value.RefreshToken}, nil
}
func (c *aadIdentityClient) createRefreshTokenRequest(ctx context.Context, tenantID, clientID, clientSecret, refreshToken string, scopes []string) (*azcore.Request, error) {
func (c *aadIdentityClient) createRefreshTokenRequest(ctx context.Context, tenantID, clientID, clientSecret, refreshToken string, scopes []string) (*policy.Request, error) {
data := url.Values{}
data.Set(qpGrantType, "refresh_token")
data.Set(qpClientID, clientID)
@ -193,8 +191,8 @@ func (c *aadIdentityClient) createRefreshTokenRequest(ctx context.Context, tenan
data.Set(qpRefreshToken, refreshToken)
data.Set(qpScope, strings.Join(scopes, " "))
dataEncoded := data.Encode()
body := azcore.NopCloser(strings.NewReader(dataEncoded))
req, err := azcore.NewRequest(ctx, http.MethodPost, azcore.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID))))
body := streaming.NopCloser(strings.NewReader(dataEncoded))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID))))
if err != nil {
return nil, err
}
@ -204,15 +202,15 @@ func (c *aadIdentityClient) createRefreshTokenRequest(ctx context.Context, tenan
return req, nil
}
func (c *aadIdentityClient) createClientSecretAuthRequest(ctx context.Context, tenantID string, clientID string, clientSecret string, scopes []string) (*azcore.Request, error) {
func (c *aadIdentityClient) createClientSecretAuthRequest(ctx context.Context, tenantID string, clientID string, clientSecret string, scopes []string) (*policy.Request, error) {
data := url.Values{}
data.Set(qpGrantType, "client_credentials")
data.Set(qpClientID, clientID)
data.Set(qpClientSecret, clientSecret)
data.Set(qpScope, strings.Join(scopes, " "))
dataEncoded := data.Encode()
body := azcore.NopCloser(strings.NewReader(dataEncoded))
req, err := azcore.NewRequest(ctx, http.MethodPost, azcore.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID))))
body := streaming.NopCloser(strings.NewReader(dataEncoded))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID))))
if err != nil {
return nil, err
}
@ -223,8 +221,8 @@ func (c *aadIdentityClient) createClientSecretAuthRequest(ctx context.Context, t
return req, nil
}
func (c *aadIdentityClient) createClientCertificateAuthRequest(ctx context.Context, tenantID string, clientID string, cert *certContents, sendCertificateChain bool, scopes []string) (*azcore.Request, error) {
u := azcore.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID)))
func (c *aadIdentityClient) createClientCertificateAuthRequest(ctx context.Context, tenantID string, clientID string, cert *certContents, sendCertificateChain bool, scopes []string) (*policy.Request, error) {
u := runtime.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID)))
clientAssertion, err := createClientAssertionJWT(clientID, u, cert, sendCertificateChain)
if err != nil {
return nil, err
@ -237,8 +235,8 @@ func (c *aadIdentityClient) createClientCertificateAuthRequest(ctx context.Conte
data.Set(qpClientAssertion, clientAssertion)
data.Set(qpScope, strings.Join(scopes, " "))
dataEncoded := data.Encode()
body := azcore.NopCloser(strings.NewReader(dataEncoded))
req, err := azcore.NewRequest(ctx, http.MethodPost, u)
body := streaming.NopCloser(strings.NewReader(dataEncoded))
req, err := runtime.NewRequest(ctx, http.MethodPost, u)
if err != nil {
return nil, err
}
@ -267,14 +265,14 @@ func (c *aadIdentityClient) authenticateUsernamePassword(ctx context.Context, te
return nil, err
}
if azcore.HasStatusCode(resp, successStatusCodes[:]...) {
if runtime.HasStatusCode(resp, successStatusCodes[:]...) {
return c.createAccessToken(resp)
}
return nil, &AuthenticationFailedError{inner: newAADAuthenticationFailedError(resp)}
}
func (c *aadIdentityClient) createUsernamePasswordAuthRequest(ctx context.Context, tenantID string, clientID string, username string, password string, scopes []string) (*azcore.Request, error) {
func (c *aadIdentityClient) createUsernamePasswordAuthRequest(ctx context.Context, tenantID string, clientID string, username string, password string, scopes []string) (*policy.Request, error) {
data := url.Values{}
data.Set(qpResponseType, "token")
data.Set(qpGrantType, "password")
@ -283,8 +281,8 @@ func (c *aadIdentityClient) createUsernamePasswordAuthRequest(ctx context.Contex
data.Set(qpPassword, password)
data.Set(qpScope, strings.Join(scopes, " "))
dataEncoded := data.Encode()
body := azcore.NopCloser(strings.NewReader(dataEncoded))
req, err := azcore.NewRequest(ctx, http.MethodPost, azcore.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID))))
body := streaming.NopCloser(strings.NewReader(dataEncoded))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID))))
if err != nil {
return nil, err
}
@ -296,7 +294,7 @@ func (c *aadIdentityClient) createUsernamePasswordAuthRequest(ctx context.Contex
func createDeviceCodeResult(res *http.Response) (*deviceCodeResult, error) {
value := &deviceCodeResult{}
if err := azcore.UnmarshalAsJSON(res, &value); err != nil {
if err := runtime.UnmarshalAsJSON(res, &value); err != nil {
return nil, fmt.Errorf("DeviceCodeResult: %w", err)
}
return value, nil
@ -320,22 +318,22 @@ func (c *aadIdentityClient) authenticateDeviceCode(ctx context.Context, tenantID
return nil, err
}
if azcore.HasStatusCode(resp, successStatusCodes[:]...) {
if runtime.HasStatusCode(resp, successStatusCodes[:]...) {
return c.createRefreshAccessToken(resp)
}
return nil, &AuthenticationFailedError{inner: newAADAuthenticationFailedError(resp)}
}
func (c *aadIdentityClient) createDeviceCodeAuthRequest(ctx context.Context, tenantID string, clientID string, deviceCode string, scopes []string) (*azcore.Request, error) {
func (c *aadIdentityClient) createDeviceCodeAuthRequest(ctx context.Context, tenantID string, clientID string, deviceCode string, scopes []string) (*policy.Request, error) {
data := url.Values{}
data.Set(qpGrantType, deviceCodeGrantType)
data.Set(qpClientID, clientID)
data.Set(qpDeviceCode, deviceCode)
data.Set(qpScope, strings.Join(scopes, " "))
dataEncoded := data.Encode()
body := azcore.NopCloser(strings.NewReader(dataEncoded))
req, err := azcore.NewRequest(ctx, http.MethodPost, azcore.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID))))
body := streaming.NopCloser(strings.NewReader(dataEncoded))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID))))
if err != nil {
return nil, err
}
@ -356,20 +354,20 @@ func (c *aadIdentityClient) requestNewDeviceCode(ctx context.Context, tenantID,
return nil, err
}
if azcore.HasStatusCode(resp, successStatusCodes[:]...) {
if runtime.HasStatusCode(resp, successStatusCodes[:]...) {
return createDeviceCodeResult(resp)
}
return nil, &AuthenticationFailedError{inner: newAADAuthenticationFailedError(resp)}
}
func (c *aadIdentityClient) createDeviceCodeNumberRequest(ctx context.Context, tenantID string, clientID string, scopes []string) (*azcore.Request, error) {
func (c *aadIdentityClient) createDeviceCodeNumberRequest(ctx context.Context, tenantID string, clientID string, scopes []string) (*policy.Request, error) {
data := url.Values{}
data.Set(qpClientID, clientID)
data.Set(qpScope, strings.Join(scopes, " "))
dataEncoded := data.Encode()
body := azcore.NopCloser(strings.NewReader(dataEncoded))
body := streaming.NopCloser(strings.NewReader(dataEncoded))
// endpoint that will return a device code along with the other necessary authentication flow parameters in the DeviceCodeResult struct
req, err := azcore.NewRequest(ctx, http.MethodPost, azcore.JoinPaths(c.authorityHost, tenantID, path.Join(oauthPath(tenantID), "/devicecode")))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(c.authorityHost, tenantID, path.Join(oauthPath(tenantID), "/devicecode")))
if err != nil {
return nil, err
}
@ -408,7 +406,7 @@ func (c *aadIdentityClient) authenticateAuthCode(ctx context.Context, tenantID,
return nil, err
}
if azcore.HasStatusCode(resp, successStatusCodes[:]...) {
if runtime.HasStatusCode(resp, successStatusCodes[:]...) {
return c.createAccessToken(resp)
}
@ -416,7 +414,7 @@ func (c *aadIdentityClient) authenticateAuthCode(ctx context.Context, tenantID,
}
// createAuthorizationCodeAuthRequest creates a request for an Access Token for authorization_code grant types.
func (c *aadIdentityClient) createAuthorizationCodeAuthRequest(ctx context.Context, tenantID, clientID, authCode, clientSecret, codeVerifier, redirectURI string, scopes []string) (*azcore.Request, error) {
func (c *aadIdentityClient) createAuthorizationCodeAuthRequest(ctx context.Context, tenantID, clientID, authCode, clientSecret, codeVerifier, redirectURI string, scopes []string) (*policy.Request, error) {
data := url.Values{}
data.Set(qpGrantType, "authorization_code")
data.Set(qpClientID, clientID)
@ -431,8 +429,8 @@ func (c *aadIdentityClient) createAuthorizationCodeAuthRequest(ctx context.Conte
data.Set(qpScope, strings.Join(scopes, " "))
data.Set(qpCode, authCode)
dataEncoded := data.Encode()
body := azcore.NopCloser(strings.NewReader(dataEncoded))
req, err := azcore.NewRequest(ctx, http.MethodPost, azcore.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID))))
body := streaming.NopCloser(strings.NewReader(dataEncoded))
req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(c.authorityHost, tenantID, tokenEndpoint(oauthPath(tenantID))))
if err != nil {
return nil, err
}

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

@ -10,7 +10,7 @@ import (
"strings"
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)
@ -52,7 +52,7 @@ func TestTelemetryDefaultUserAgent(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@ -63,7 +63,7 @@ func TestTelemetryDefaultUserAgent(t *testing.T) {
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d", resp.StatusCode)
}
if ua := resp.Request.Header.Get(headerUserAgent); !strings.HasPrefix(ua, UserAgent) {
if ua := resp.Request.Header.Get(headerUserAgent); !strings.HasPrefix(ua, "azsdk-go-"+component+"/"+version) {
t.Fatalf("unexpected User-Agent %s", ua)
}
}
@ -76,12 +76,12 @@ func TestTelemetryCustom(t *testing.T) {
options := pipelineOptions{
HTTPClient: srv,
}
options.Telemetry.Value = customTelemetry
options.Telemetry.ApplicationID = customTelemetry
client, err := newAADIdentityClient(srv.URL(), options)
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@ -92,7 +92,7 @@ func TestTelemetryCustom(t *testing.T) {
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d", resp.StatusCode)
}
if ua := resp.Request.Header.Get(headerUserAgent); !strings.HasPrefix(ua, customTelemetry+" "+UserAgent) {
if ua := resp.Request.Header.Get(headerUserAgent); !strings.HasPrefix(ua, customTelemetry+" "+"azsdk-go-"+component+"/"+version) {
t.Fatalf("unexpected User-Agent %s", ua)
}
}

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

@ -7,6 +7,8 @@ import (
"context"
"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/azcore/runtime"
)
// AuthorizationCodeCredentialOptions contain optional parameters that can be used to configure the AuthorizationCodeCredential.
@ -19,13 +21,13 @@ type AuthorizationCodeCredentialOptions struct {
AuthorityHost string
// HTTPClient sets the transport for making HTTP requests
// Leave this as nil to use the default HTTP transport
HTTPClient azcore.Transporter
HTTPClient policy.Transporter
// Retry configures the built-in retry policy behavior
Retry azcore.RetryOptions
Retry policy.RetryOptions
// Telemetry configures the built-in telemetry policy behavior
Telemetry azcore.TelemetryOptions
Telemetry policy.TelemetryOptions
// Logging configures the built-in logging policy behavior.
Logging azcore.LogOptions
Logging policy.LogOptions
}
// AuthorizationCodeCredential enables authentication to Azure Active Directory using an authorization code
@ -68,7 +70,7 @@ func NewAuthorizationCodeCredential(tenantID string, clientID string, authCode s
// ctx: Context used to control the request lifetime.
// opts: TokenRequestOptions contains the list of scopes for which the token will have access.
// Returns an AccessToken which can be used to authenticate service client calls.
func (c *AuthorizationCodeCredential) GetToken(ctx context.Context, opts azcore.TokenRequestOptions) (*azcore.AccessToken, error) {
func (c *AuthorizationCodeCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) {
tk, err := c.client.authenticateAuthCode(ctx, c.tenantID, c.clientID, c.authCode, c.clientSecret, "", c.redirectURI, opts.Scopes)
if err != nil {
addGetTokenFailureLogs("Authorization Code Credential", err, true)
@ -79,7 +81,7 @@ func (c *AuthorizationCodeCredential) GetToken(ctx context.Context, opts azcore.
}
// NewAuthenticationPolicy implements the azcore.Credential interface on AuthorizationCodeCredential.
func (c *AuthorizationCodeCredential) NewAuthenticationPolicy(options azcore.AuthenticationOptions) azcore.Policy {
func (c *AuthorizationCodeCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy {
return newBearerTokenPolicy(c, options)
}

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

@ -11,7 +11,7 @@ import (
"net/url"
"testing"
"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/internal/mock"
)
@ -43,10 +43,10 @@ func TestAuthorizationCodeCredential_CreateAuthRequestSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Unexpectedly received an error: %v", err)
}
if req.Request.Header.Get(headerContentType) != headerURLEncoded {
if req.Raw().Header.Get(headerContentType) != headerURLEncoded {
t.Fatal("Unexpected value for Content-Type header")
}
body, err := ioutil.ReadAll(req.Request.Body)
body, err := ioutil.ReadAll(req.Raw().Body)
if err != nil {
t.Fatal("Unable to read request body")
}
@ -67,10 +67,10 @@ func TestAuthorizationCodeCredential_CreateAuthRequestSuccess(t *testing.T) {
if reqQueryParams[qpRedirectURI][0] != testRedirectURI {
t.Fatal("Unexpected redirectURI")
}
if req.Request.URL.Host != defaultTestAuthorityHost {
if req.Raw().URL.Host != defaultTestAuthorityHost {
t.Fatal("Unexpected default authority host")
}
if req.Request.URL.Scheme != "https" {
if req.Raw().URL.Scheme != "https" {
t.Fatal("Wrong request scheme")
}
}
@ -87,7 +87,7 @@ func TestAuthorizationCodeCredential_GetTokenSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
t.Fatalf("Expected an empty error but received: %v", err)
}
@ -105,7 +105,7 @@ func TestAuthorizationCodeCredential_GetTokenInvalidCredentials(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err == nil {
t.Fatalf("Expected an error but did not receive one.")
}
@ -154,7 +154,7 @@ func TestAuthorizationCodeCredential_GetTokenUnexpectedJSON(t *testing.T) {
if err != nil {
t.Fatalf("Failed to create the credential")
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err == nil {
t.Fatalf("Expected a JSON marshal error but received nil")
}

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

@ -13,6 +13,9 @@ import (
"time"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo"
)
const (
@ -96,11 +99,11 @@ func (e *AuthenticationFailedError) Error() string {
return e.msg + " details: " + e.inner.Error()
}
var _ azcore.NonRetriableError = (*AuthenticationFailedError)(nil)
var _ errorinfo.NonRetriable = (*AuthenticationFailedError)(nil)
func newAADAuthenticationFailedError(resp *http.Response) error {
authFailed := &AADAuthenticationFailedError{Response: resp}
err := azcore.UnmarshalAsJSON(resp, authFailed)
err := runtime.UnmarshalAsJSON(resp, authFailed)
if err != nil {
authFailed.Message = resp.Status
authFailed.Description = "Failed to unmarshal response: " + err.Error()
@ -126,22 +129,22 @@ func (e *CredentialUnavailableError) NonRetriable() {
// marker method
}
var _ azcore.NonRetriableError = (*CredentialUnavailableError)(nil)
var _ errorinfo.NonRetriable = (*CredentialUnavailableError)(nil)
// pipelineOptions are used to configure how requests are made to Azure Active Directory.
type pipelineOptions struct {
// HTTPClient sets the transport for making HTTP requests
// Leave this as nil to use the default HTTP transport
HTTPClient azcore.Transporter
HTTPClient policy.Transporter
// Retry configures the built-in retry policy behavior
Retry azcore.RetryOptions
Retry policy.RetryOptions
// Telemetry configures the built-in telemetry policy behavior
Telemetry azcore.TelemetryOptions
Telemetry policy.TelemetryOptions
// Logging configures the built-in logging policy behavior.
Logging azcore.LogOptions
Logging policy.LogOptions
}
// setAuthorityHost initializes the authority host for credentials.
@ -164,20 +167,22 @@ func setAuthorityHost(authorityHost string) (string, error) {
}
// newDefaultPipeline creates a pipeline using the specified pipeline options.
func newDefaultPipeline(o pipelineOptions) azcore.Pipeline {
return azcore.NewPipeline(
o.HTTPClient,
azcore.NewTelemetryPolicy(&o.Telemetry),
azcore.NewRetryPolicy(&o.Retry),
azcore.NewLogPolicy(&o.Logging))
func newDefaultPipeline(o pipelineOptions) runtime.Pipeline {
policies := []policy.Policy{}
if !o.Telemetry.Disabled {
policies = append(policies, runtime.NewTelemetryPolicy(component, version, &o.Telemetry))
}
policies = append(policies, runtime.NewRetryPolicy(&o.Retry))
policies = append(policies, runtime.NewLogPolicy(&o.Logging))
return runtime.NewPipeline(o.HTTPClient, policies...)
}
// newDefaultMSIPipeline creates a pipeline using the specified pipeline options needed
// for a Managed Identity, such as a MSI specific retry policy.
func newDefaultMSIPipeline(o ManagedIdentityCredentialOptions) azcore.Pipeline {
func newDefaultMSIPipeline(o ManagedIdentityCredentialOptions) runtime.Pipeline {
var statusCodes []int
// retry policy for MSI is not end-user configurable
retryOpts := azcore.RetryOptions{
retryOpts := policy.RetryOptions{
MaxRetries: 5,
MaxRetryDelay: 1 * time.Minute,
RetryDelay: 2 * time.Second,
@ -200,16 +205,13 @@ func newDefaultMSIPipeline(o ManagedIdentityCredentialOptions) azcore.Pipeline {
http.StatusNotExtended, // 510
http.StatusNetworkAuthenticationRequired), // 511
}
if o.Telemetry.Value == "" {
o.Telemetry.Value = UserAgent
} else {
o.Telemetry.Value += " " + UserAgent
policies := []policy.Policy{}
if !o.Telemetry.Disabled {
policies = append(policies, runtime.NewTelemetryPolicy(component, version, &o.Telemetry))
}
return azcore.NewPipeline(
o.HTTPClient,
azcore.NewTelemetryPolicy(&o.Telemetry),
azcore.NewRetryPolicy(&retryOpts),
azcore.NewLogPolicy(&o.Logging))
policies = append(policies, runtime.NewRetryPolicy(&retryOpts))
policies = append(policies, runtime.NewLogPolicy(&o.Logging))
return runtime.NewPipeline(o.HTTPClient, policies...)
}
// validTenantID return true is it receives a valid tenantID, returns false otherwise

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

@ -16,6 +16,8 @@ import (
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
)
// AzureCLITokenProvider can be used to supply the AzureCLICredential with an alternate token provider
@ -56,7 +58,7 @@ func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredent
// ctx: Context used to control the request lifetime.
// opts: TokenRequestOptions contains the list of scopes for which the token will have access.
// Returns an AccessToken which can be used to authenticate service client calls.
func (c *AzureCLICredential) GetToken(ctx context.Context, opts azcore.TokenRequestOptions) (*azcore.AccessToken, error) {
func (c *AzureCLICredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) {
// The following code will remove the /.default suffix from the scope passed into the method since AzureCLI expect a resource string instead of a scope string
opts.Scopes[0] = strings.TrimSuffix(opts.Scopes[0], defaultSuffix)
at, err := c.authenticate(ctx, opts.Scopes[0])
@ -69,7 +71,7 @@ func (c *AzureCLICredential) GetToken(ctx context.Context, opts azcore.TokenRequ
}
// NewAuthenticationPolicy implements the azcore.Credential interface on AzureCLICredential.
func (c *AzureCLICredential) NewAuthenticationPolicy(options azcore.AuthenticationOptions) azcore.Policy {
func (c *AzureCLICredential) NewAuthenticationPolicy(options azruntime.AuthenticationOptions) policy.Policy {
return newBearerTokenPolicy(c, options)
}
@ -100,7 +102,7 @@ func defaultTokenProvider() func(ctx context.Context, resource string) ([]byte,
const azureCLIDefaultPath = "/bin:/sbin:/usr/bin:/usr/local/bin"
// Validate resource, since it gets sent as a command line argument to Azure CLI
const invalidResourceErrorTemplate = "Resource %s is not in expected format. Only alphanumeric characters, [dot], [colon], [hyphen], and [forward slash] are allowed."
const invalidResourceErrorTemplate = "resource %s is not in expected format. Only alphanumeric characters, [dot], [colon], [hyphen], and [forward slash] are allowed"
match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource)
if err != nil {
return nil, err

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

@ -9,7 +9,8 @@ import (
"net/http"
"testing"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)
@ -33,7 +34,7 @@ func TestAzureCLICredential_GetTokenSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
at, err := cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
at, err := cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
t.Fatalf("Expected an empty error but received: %v", err)
}
@ -52,7 +53,7 @@ func TestAzureCLICredential_GetTokenInvalidToken(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err == nil {
t.Fatalf("Expected an error but did not receive one.")
}
@ -69,7 +70,7 @@ func TestBearerPolicy_AzureCLICredential(t *testing.T) {
t.Fatalf("Did not expect an error but received: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, scope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}

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

@ -11,6 +11,8 @@ import (
"time"
"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/azcore/runtime"
)
const (
@ -24,7 +26,7 @@ type bearerTokenPolicy struct {
auxResources map[string]*expiringResource
// the following fields are read-only
creds azcore.TokenCredential
options azcore.TokenRequestOptions
options policy.TokenRequestOptions
}
type expiringResource struct {
@ -47,7 +49,7 @@ type expiringResource struct {
type acquireResource func(state interface{}) (newResource interface{}, newExpiration time.Time, err error)
type acquiringResourceState struct {
req *azcore.Request
req *policy.Request
p bearerTokenPolicy
}
@ -55,7 +57,7 @@ type acquiringResourceState struct {
// thread/goroutine at a time ever calls this function
func acquire(state interface{}) (newResource interface{}, newExpiration time.Time, err error) {
s := state.(acquiringResourceState)
tk, err := s.p.creds.GetToken(s.req.Context(), s.p.options)
tk, err := s.p.creds.GetToken(s.req.Raw().Context(), s.p.options)
if err != nil {
return nil, time.Time{}, err
}
@ -125,7 +127,7 @@ func (er *expiringResource) GetResource(state interface{}) (interface{}, error)
return resource, err // Return the resource this thread/goroutine can use
}
func newBearerTokenPolicy(creds azcore.TokenCredential, opts azcore.AuthenticationOptions) *bearerTokenPolicy {
func newBearerTokenPolicy(creds azcore.TokenCredential, opts runtime.AuthenticationOptions) *bearerTokenPolicy {
p := &bearerTokenPolicy{
creds: creds,
options: opts.TokenRequest,
@ -141,7 +143,7 @@ func newBearerTokenPolicy(creds azcore.TokenCredential, opts azcore.Authenticati
return p
}
func (b *bearerTokenPolicy) Do(req *azcore.Request) (*http.Response, error) {
func (b *bearerTokenPolicy) Do(req *policy.Request) (*http.Response, error) {
as := acquiringResourceState{
p: *b,
req: req,
@ -151,8 +153,8 @@ func (b *bearerTokenPolicy) Do(req *azcore.Request) (*http.Response, error) {
return nil, err
}
if token, ok := tk.(*azcore.AccessToken); ok {
req.Request.Header.Set(headerXmsDate, time.Now().UTC().Format(http.TimeFormat))
req.Request.Header.Set(headerAuthorization, fmt.Sprintf("Bearer %s", token.Token))
req.Raw().Header.Set(headerXmsDate, time.Now().UTC().Format(http.TimeFormat))
req.Raw().Header.Set(headerAuthorization, fmt.Sprintf("Bearer %s", token.Token))
}
auxTokens := []string{}
for tenant, er := range b.auxResources {
@ -169,7 +171,7 @@ func (b *bearerTokenPolicy) Do(req *azcore.Request) (*http.Response, error) {
auxTokens = append(auxTokens, fmt.Sprintf("%s%s", bearerTokenPrefix, auxTk.(*azcore.AccessToken).Token))
}
if len(auxTokens) > 0 {
req.Request.Header.Set(headerAuxiliaryAuthorization, strings.Join(auxTokens, ", "))
req.Raw().Header.Set(headerAuxiliaryAuthorization, strings.Join(auxTokens, ", "))
}
return req.Next()
}

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

@ -11,6 +11,8 @@ import (
"time"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)
@ -21,16 +23,16 @@ const (
accessTokenRespShortLived = `{"access_token": "` + tokenValue + `", "expires_in": 0}`
)
func defaultTestPipeline(srv azcore.Transporter, cred azcore.Credential, scope string) azcore.Pipeline {
retryOpts := azcore.RetryOptions{
func defaultTestPipeline(srv policy.Transporter, cred azcore.Credential, scope string) runtime.Pipeline {
retryOpts := policy.RetryOptions{
MaxRetryDelay: 500 * time.Millisecond,
RetryDelay: 50 * time.Millisecond,
}
return azcore.NewPipeline(
return runtime.NewPipeline(
srv,
azcore.NewRetryPolicy(&retryOpts),
cred.NewAuthenticationPolicy(azcore.AuthenticationOptions{TokenRequest: azcore.TokenRequestOptions{Scopes: []string{scope}}}),
azcore.NewLogPolicy(nil))
runtime.NewRetryPolicy(&retryOpts),
cred.NewAuthenticationPolicy(runtime.AuthenticationOptions{TokenRequest: policy.TokenRequestOptions{Scopes: []string{scope}}}),
runtime.NewLogPolicy(nil))
}
func TestBearerPolicy_SuccessGetToken(t *testing.T) {
@ -46,7 +48,7 @@ func TestBearerPolicy_SuccessGetToken(t *testing.T) {
t.Fatalf("Unable to create credential. Received: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, scope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}
@ -73,7 +75,7 @@ func TestBearerPolicy_CredentialFailGetToken(t *testing.T) {
t.Fatalf("Unable to create credential. Received: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, scope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}
@ -104,7 +106,7 @@ func TestBearerTokenPolicy_TokenExpired(t *testing.T) {
t.Fatalf("Unable to create credential. Received: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, scope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}
@ -132,7 +134,7 @@ func TestRetryPolicy_NonRetriable(t *testing.T) {
t.Fatalf("Unable to create credential. Received: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, scope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}
@ -155,7 +157,7 @@ func TestRetryPolicy_HTTPRequest(t *testing.T) {
t.Fatalf("Unable to create credential. Received: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, scope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}
@ -174,7 +176,7 @@ func TestBearerPolicy_GetTokenFailsNoDeadlock(t *testing.T) {
cred, err := NewClientSecretCredential(tenantID, clientID, secret, &ClientSecretCredentialOptions{
HTTPClient: srv,
AuthorityHost: srv.URL(),
Retry: azcore.RetryOptions{
Retry: policy.RetryOptions{
// use a negative try timeout to trigger a deadline exceeded error causing GetToken() to fail
TryTimeout: -1 * time.Nanosecond,
MaxRetryDelay: 500 * time.Millisecond,
@ -185,7 +187,7 @@ func TestBearerPolicy_GetTokenFailsNoDeadlock(t *testing.T) {
t.Fatalf("Unable to create credential. Received: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, scope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}
@ -215,23 +217,23 @@ func TestBearerTokenWithAuxiliaryTenants(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
retryOpts := azcore.RetryOptions{
retryOpts := policy.RetryOptions{
MaxRetryDelay: 500 * time.Millisecond,
RetryDelay: 50 * time.Millisecond,
}
pipeline := azcore.NewPipeline(
pipeline := runtime.NewPipeline(
srv,
azcore.NewRetryPolicy(&retryOpts),
runtime.NewRetryPolicy(&retryOpts),
cred.NewAuthenticationPolicy(
azcore.AuthenticationOptions{
TokenRequest: azcore.TokenRequestOptions{
runtime.AuthenticationOptions{
TokenRequest: policy.TokenRequestOptions{
Scopes: []string{scope},
},
AuxiliaryTenants: []string{"tenant1", "tenant2", "tenant3"},
}),
azcore.NewLogPolicy(nil))
runtime.NewLogPolicy(nil))
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}

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

@ -8,6 +8,8 @@ import (
"errors"
"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/azcore/runtime"
)
// ChainedTokenCredential provides a TokenCredential implementation that chains multiple TokenCredential sources to be tried in order
@ -34,7 +36,7 @@ func NewChainedTokenCredential(sources ...azcore.TokenCredential) (*ChainedToken
}
// GetToken sequentially calls TokenCredential.GetToken on all the specified sources, returning the token from the first successful call to GetToken().
func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts azcore.TokenRequestOptions) (token *azcore.AccessToken, err error) {
func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (token *azcore.AccessToken, err error) {
var errList []*CredentialUnavailableError
// loop through all of the credentials provided in sources
for _, cred := range c.sources {
@ -69,7 +71,7 @@ func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts azcore.Token
}
// NewAuthenticationPolicy implements the azcore.Credential interface on ChainedTokenCredential and sets the bearer token
func (c *ChainedTokenCredential) NewAuthenticationPolicy(options azcore.AuthenticationOptions) azcore.Policy {
func (c *ChainedTokenCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy {
return newBearerTokenPolicy(c, options)
}

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

@ -9,7 +9,8 @@ import (
"net/http"
"testing"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)
@ -82,7 +83,7 @@ func TestChainedTokenCredential_GetTokenSuccess(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
tk, err := cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
tk, err := cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
t.Fatalf("Received an error when attempting to get a token but expected none")
}
@ -109,7 +110,7 @@ func TestChainedTokenCredential_GetTokenFail(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err == nil {
t.Fatalf("Expected an error but did not receive one")
}
@ -143,7 +144,7 @@ func TestChainedTokenCredential_GetTokenWithUnavailableCredentialInChain(t *test
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
tk, err := cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
tk, err := cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
t.Fatalf("Received an error when attempting to get a token but expected none")
}
@ -176,7 +177,7 @@ func TestBearerPolicy_ChainedTokenCredential(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
pipeline := defaultTestPipeline(srv, chainedCred, scope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}

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

@ -15,6 +15,8 @@ import (
"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/azcore/runtime"
"golang.org/x/crypto/pkcs12"
)
@ -31,13 +33,13 @@ type ClientCertificateCredentialOptions struct {
AuthorityHost string
// HTTPClient sets the transport for making HTTP requests
// Leave this as nil to use the default HTTP transport
HTTPClient azcore.Transporter
HTTPClient policy.Transporter
// Retry configures the built-in retry policy behavior
Retry azcore.RetryOptions
Retry policy.RetryOptions
// Telemetry configures the built-in telemetry policy behavior
Telemetry azcore.TelemetryOptions
Telemetry policy.TelemetryOptions
// Logging configures the built-in logging policy behavior.
Logging azcore.LogOptions
Logging policy.LogOptions
}
// ClientCertificateCredential enables authentication of a service principal to Azure Active Directory using a certificate that is assigned to its App Registration. More information
@ -206,7 +208,7 @@ func extractFromPFXFile(certData []byte, password string, sendCertificateChain b
// scopes: The list of scopes for which the token will have access.
// ctx: controlling the request lifetime.
// Returns an AccessToken which can be used to authenticate service client calls.
func (c *ClientCertificateCredential) GetToken(ctx context.Context, opts azcore.TokenRequestOptions) (*azcore.AccessToken, error) {
func (c *ClientCertificateCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) {
tk, err := c.client.authenticateCertificate(ctx, c.tenantID, c.clientID, c.cert, c.sendCertificateChain, opts.Scopes)
if err != nil {
addGetTokenFailureLogs("Client Certificate Credential", err, true)
@ -217,7 +219,7 @@ func (c *ClientCertificateCredential) GetToken(ctx context.Context, opts azcore.
}
// NewAuthenticationPolicy implements the azcore.Credential interface on ClientCertificateCredential.
func (c *ClientCertificateCredential) NewAuthenticationPolicy(options azcore.AuthenticationOptions) azcore.Policy {
func (c *ClientCertificateCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy {
return newBearerTokenPolicy(c, options)
}

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

@ -12,7 +12,8 @@ import (
"strings"
"testing"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)
@ -44,10 +45,10 @@ func TestClientCertificateCredential_CreateAuthRequestSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Unexpectedly received an error: %v", err)
}
if req.Request.Header.Get(headerContentType) != headerURLEncoded {
if req.Raw().Header.Get(headerContentType) != headerURLEncoded {
t.Fatalf("Unexpected value for Content-Type header")
}
body, err := ioutil.ReadAll(req.Request.Body)
body, err := ioutil.ReadAll(req.Raw().Body)
if err != nil {
t.Fatalf("Unable to read request body")
}
@ -71,10 +72,10 @@ func TestClientCertificateCredential_CreateAuthRequestSuccess(t *testing.T) {
if len(reqQueryParams[qpClientAssertion][0]) == 0 {
t.Fatalf("Client assertion is not present on the request")
}
if req.Request.URL.Host != defaultTestAuthorityHost {
if req.Raw().URL.Host != defaultTestAuthorityHost {
t.Fatalf("Unexpected default authority host")
}
if req.Request.URL.Scheme != "https" {
if req.Raw().URL.Scheme != "https" {
t.Fatalf("Wrong request scheme")
}
}
@ -90,13 +91,13 @@ func TestClientCertificateCredential_CreateAuthRequestSuccess_withCertificateCha
if err != nil {
t.Fatalf("Unexpectedly received an error: %v", err)
}
if req.Request.Header.Get(headerContentType) != headerURLEncoded {
if req.Raw().Header.Get(headerContentType) != headerURLEncoded {
t.Fatalf("Unexpected value for Content-Type header")
}
if len(cred.cert.publicCertificates) != 1 {
t.Fatalf("Wrong number of public certificates. Expected: %v, Received: %v", 1, len(cred.cert.publicCertificates))
}
body, err := ioutil.ReadAll(req.Request.Body)
body, err := ioutil.ReadAll(req.Raw().Body)
if err != nil {
t.Fatalf("Unable to read request body")
}
@ -123,7 +124,7 @@ func TestClientCertificateCredential_CreateAuthRequestSuccess_withCertificateCha
if err != nil {
t.Fatalf("Failed extract data from PEM file: %v", err)
}
assertion, err := createClientAssertionJWT(clientID, azcore.JoinPaths(AzurePublicCloud, tenantID, tokenEndpoint(oauthPath(tenantID))), cert, true)
assertion, err := createClientAssertionJWT(clientID, runtime.JoinPaths(AzurePublicCloud, tenantID, tokenEndpoint(oauthPath(tenantID))), cert, true)
if err != nil {
t.Fatalf("Failed to create client assertion: %v", err)
}
@ -143,10 +144,10 @@ func TestClientCertificateCredential_CreateAuthRequestSuccess_withCertificateCha
if len(reqQueryParams[qpClientAssertion][0]) == 0 {
t.Fatalf("Client assertion is not present on the request")
}
if req.Request.URL.Host != defaultTestAuthorityHost {
if req.Raw().URL.Host != defaultTestAuthorityHost {
t.Fatalf("Unexpected default authority host")
}
if req.Request.URL.Scheme != "https" {
if req.Raw().URL.Scheme != "https" {
t.Fatalf("Wrong request scheme")
}
}
@ -162,7 +163,7 @@ func TestClientCertificateCredential_GetTokenSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Expected an empty error but received: %s", err.Error())
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
t.Fatalf("Expected an empty error but received: %s", err.Error())
}
@ -180,7 +181,7 @@ func TestClientCertificateCredential_GetTokenSuccess_withCertificateChain(t *tes
if err != nil {
t.Fatalf("Expected an empty error but received: %s", err.Error())
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
t.Fatalf("Expected an empty error but received: %s", err.Error())
}
@ -197,7 +198,7 @@ func TestClientCertificateCredential_GetTokenInvalidCredentials(t *testing.T) {
if err != nil {
t.Fatalf("Did not expect an error but received one: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err == nil {
t.Fatalf("Expected to receive a nil error, but received: %v", err)
}
@ -231,7 +232,7 @@ func TestClientCertificateCredential_GetTokenCheckPrivateKeyBlocks(t *testing.T)
if err != nil {
t.Fatalf("Expected an empty error but received: %s", err.Error())
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
t.Fatalf("Expected an empty error but received: %s", err.Error())
}
@ -248,7 +249,7 @@ func TestClientCertificateCredential_GetTokenCheckCertificateBlocks(t *testing.T
if err != nil {
t.Fatalf("Expected an empty error but received: %s", err.Error())
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
t.Fatalf("Expected an empty error but received: %s", err.Error())
}
@ -293,7 +294,7 @@ func TestBearerPolicy_ClientCertificateCredential(t *testing.T) {
t.Fatalf("Did not expect an error but received: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, scope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}

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

@ -7,6 +7,8 @@ import (
"context"
"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/azcore/runtime"
)
// ClientSecretCredentialOptions configures the ClientSecretCredential with optional parameters.
@ -17,13 +19,13 @@ type ClientSecretCredentialOptions struct {
AuthorityHost string
// HTTPClient sets the transport for making HTTP requests
// Leave this as nil to use the default HTTP transport
HTTPClient azcore.Transporter
HTTPClient policy.Transporter
// Retry configures the built-in retry policy behavior
Retry azcore.RetryOptions
Retry policy.RetryOptions
// Telemetry configures the built-in telemetry policy behavior
Telemetry azcore.TelemetryOptions
Telemetry policy.TelemetryOptions
// Logging configures the built-in logging policy behavior.
Logging azcore.LogOptions
Logging policy.LogOptions
}
// ClientSecretCredential enables authentication to Azure Active Directory using a client secret that was generated for an App Registration. More information on how
@ -63,7 +65,7 @@ func NewClientSecretCredential(tenantID string, clientID string, clientSecret st
// ctx: Context used to control the request lifetime.
// opts: TokenRequestOptions contains the list of scopes for which the token will have access.
// Returns an AccessToken which can be used to authenticate service client calls.
func (c *ClientSecretCredential) GetToken(ctx context.Context, opts azcore.TokenRequestOptions) (*azcore.AccessToken, error) {
func (c *ClientSecretCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) {
tk, err := c.client.authenticate(ctx, c.tenantID, c.clientID, c.clientSecret, opts.Scopes)
if err != nil {
addGetTokenFailureLogs("Client Secret Credential", err, true)
@ -75,7 +77,7 @@ func (c *ClientSecretCredential) GetToken(ctx context.Context, opts azcore.Token
// NewAuthenticationPolicy implements the azcore.Credential interface on ClientSecretCredential and calls the Bearer Token policy
// to get the bearer token.
func (c *ClientSecretCredential) NewAuthenticationPolicy(options azcore.AuthenticationOptions) azcore.Policy {
func (c *ClientSecretCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy {
return newBearerTokenPolicy(c, options)
}

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

@ -11,7 +11,7 @@ import (
"net/url"
"testing"
"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/internal/mock"
)
@ -49,10 +49,10 @@ func TestClientSecretCredential_CreateAuthRequestSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Unexpectedly received an error: %v", err)
}
if req.Request.Header.Get(headerContentType) != headerURLEncoded {
if req.Raw().Header.Get(headerContentType) != headerURLEncoded {
t.Fatalf("Unexpected value for Content-Type header")
}
body, err := ioutil.ReadAll(req.Request.Body)
body, err := ioutil.ReadAll(req.Raw().Body)
if err != nil {
t.Fatalf("Unable to read request body")
}
@ -70,10 +70,10 @@ func TestClientSecretCredential_CreateAuthRequestSuccess(t *testing.T) {
if reqQueryParams[qpScope][0] != scope {
t.Fatalf("Unexpected scope in scope header")
}
if req.Request.URL.Host != defaultTestAuthorityHost {
if req.Raw().URL.Host != defaultTestAuthorityHost {
t.Fatalf("Unexpected default authority host")
}
if req.Request.URL.Scheme != "https" {
if req.Raw().URL.Scheme != "https" {
t.Fatalf("Wrong request scheme")
}
}
@ -89,7 +89,7 @@ func TestClientSecretCredential_GetTokenSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
t.Fatalf("Expected an empty error but received: %v", err)
}
@ -106,7 +106,7 @@ func TestClientSecretCredential_GetTokenInvalidCredentials(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err == nil {
t.Fatalf("Expected an error but did not receive one.")
}
@ -154,7 +154,7 @@ func TestClientSecretCredential_GetTokenUnexpectedJSON(t *testing.T) {
if err != nil {
t.Fatalf("Failed to create the credential")
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err == nil {
t.Fatalf("Expected a JSON marshal error but received nil")
}

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

@ -10,6 +10,8 @@ import (
"time"
"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/azcore/runtime"
)
const (
@ -34,13 +36,13 @@ type DeviceCodeCredentialOptions struct {
AuthorityHost string
// HTTPClient sets the transport for making HTTP requests
// Leave this as nil to use the default HTTP transport
HTTPClient azcore.Transporter
HTTPClient policy.Transporter
// Retry configures the built-in retry policy behavior
Retry azcore.RetryOptions
Retry policy.RetryOptions
// Telemetry configures the built-in telemetry policy behavior
Telemetry azcore.TelemetryOptions
Telemetry policy.TelemetryOptions
// Logging configures the built-in logging policy behavior.
Logging azcore.LogOptions
Logging policy.LogOptions
}
// init provides the default settings for DeviceCodeCredential.
@ -111,7 +113,7 @@ func NewDeviceCodeCredential(options *DeviceCodeCredentialOptions) (*DeviceCodeC
// scopes: The list of scopes for which the token will have access. The "offline_access" scope is checked for and automatically added in case it isn't present to allow for silent token refresh.
// ctx: The context for controlling the request lifetime.
// Returns an AccessToken which can be used to authenticate service client calls.
func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts azcore.TokenRequestOptions) (*azcore.AccessToken, error) {
func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) {
for i, scope := range opts.Scopes {
if scope == "offline_access" { // if we find that the opts.Scopes slice contains "offline_access" then we don't need to do anything and exit
break
@ -168,7 +170,7 @@ func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts azcore.TokenRe
}
// NewAuthenticationPolicy implements the azcore.Credential interface on DeviceCodeCredential.
func (c *DeviceCodeCredential) NewAuthenticationPolicy(options azcore.AuthenticationOptions) azcore.Policy {
func (c *DeviceCodeCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy {
return newBearerTokenPolicy(c, options)
}

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

@ -11,7 +11,8 @@ import (
"net/url"
"testing"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)
@ -48,10 +49,10 @@ func TestDeviceCodeCredential_CreateAuthRequestSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Unexpectedly received an error: %v", err)
}
if req.Request.Header.Get(headerContentType) != headerURLEncoded {
if req.Raw().Header.Get(headerContentType) != headerURLEncoded {
t.Fatalf("Unexpected value for Content-Type header")
}
body, err := ioutil.ReadAll(req.Request.Body)
body, err := ioutil.ReadAll(req.Raw().Body)
if err != nil {
t.Fatalf("Unable to read request body")
}
@ -72,10 +73,10 @@ func TestDeviceCodeCredential_CreateAuthRequestSuccess(t *testing.T) {
if reqQueryParams[qpScope][0] != deviceCodeScopes {
t.Fatalf("Unexpected scope in scope header")
}
if req.Request.URL.Host != defaultTestAuthorityHost {
if req.Raw().URL.Host != defaultTestAuthorityHost {
t.Fatalf("Unexpected default authority host")
}
if req.Request.URL.Scheme != "https" {
if req.Raw().URL.Scheme != "https" {
t.Fatalf("Wrong request scheme")
}
}
@ -91,10 +92,10 @@ func TestDeviceCodeCredential_CreateAuthRequestCustomClientID(t *testing.T) {
if err != nil {
t.Fatalf("Unexpectedly received an error: %v", err)
}
if req.Request.Header.Get(headerContentType) != headerURLEncoded {
if req.Raw().Header.Get(headerContentType) != headerURLEncoded {
t.Fatalf("Unexpected value for Content-Type header")
}
body, err := ioutil.ReadAll(req.Request.Body)
body, err := ioutil.ReadAll(req.Raw().Body)
if err != nil {
t.Fatalf("Unable to read request body")
}
@ -115,13 +116,13 @@ func TestDeviceCodeCredential_CreateAuthRequestCustomClientID(t *testing.T) {
if reqQueryParams[qpScope][0] != deviceCodeScopes {
t.Fatalf("Unexpected scope in scope header")
}
if req.Request.URL.Host != defaultTestAuthorityHost {
if req.Raw().URL.Host != defaultTestAuthorityHost {
t.Fatalf("Unexpected default authority host")
}
if req.Request.URL.Scheme != "https" {
if req.Raw().URL.Scheme != "https" {
t.Fatalf("Wrong request scheme")
}
if req.Request.URL.Path != "/organizations/oauth2/v2.0/token" {
if req.Raw().URL.Path != "/organizations/oauth2/v2.0/token" {
t.Fatalf("Did not set the right path when passing in an empty tenant ID")
}
}
@ -138,10 +139,10 @@ func TestDeviceCodeCredential_RequestNewDeviceCodeCustomTenantIDClientID(t *test
if err != nil {
t.Fatalf("Unexpectedly received an error: %v", err)
}
if req.Request.Header.Get(headerContentType) != headerURLEncoded {
if req.Raw().Header.Get(headerContentType) != headerURLEncoded {
t.Fatalf("Unexpected value for Content-Type header")
}
body, err := ioutil.ReadAll(req.Request.Body)
body, err := ioutil.ReadAll(req.Raw().Body)
if err != nil {
t.Fatalf("Unable to read request body")
}
@ -156,13 +157,13 @@ func TestDeviceCodeCredential_RequestNewDeviceCodeCustomTenantIDClientID(t *test
if reqQueryParams[qpScope][0] != deviceCodeScopes {
t.Fatalf("Unexpected scope in scope header")
}
if req.Request.URL.Host != defaultTestAuthorityHost {
if req.Raw().URL.Host != defaultTestAuthorityHost {
t.Fatalf("Unexpected default authority host")
}
if req.Request.URL.Scheme != "https" {
if req.Raw().URL.Scheme != "https" {
t.Fatalf("Wrong request scheme")
}
if req.Request.URL.Path != "/expected-tenant/oauth2/v2.0/devicecode" {
if req.Raw().URL.Path != "/expected-tenant/oauth2/v2.0/devicecode" {
t.Fatalf("Did not set the right path when passing in an empty tenant ID")
}
}
@ -180,7 +181,7 @@ func TestDeviceCodeCredential_GetTokenSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
tk, err := cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
tk, err := cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
if err != nil {
t.Fatalf("Expected an empty error but received: %s", err.Error())
}
@ -202,7 +203,7 @@ func TestDeviceCodeCredential_GetTokenInvalidCredentials(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
if err == nil {
t.Fatalf("Expected an error but did not receive one.")
}
@ -225,7 +226,7 @@ func TestDeviceCodeCredential_GetTokenAuthorizationPending(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
if err != nil {
t.Fatalf("Expected an empty error but received %v", err)
}
@ -247,7 +248,7 @@ func TestDeviceCodeCredential_GetTokenExpiredToken(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
if err == nil {
t.Fatalf("Expected an error but received none")
}
@ -267,7 +268,7 @@ func TestDeviceCodeCredential_GetTokenWithRefreshTokenFailure(t *testing.T) {
t.Fatalf("Unable to create credential. Received: %v", err)
}
cred.refreshToken = "refresh_token"
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
if err == nil {
t.Fatalf("Expected an error but did not receive one")
}
@ -292,7 +293,7 @@ func TestDeviceCodeCredential_GetTokenWithRefreshTokenSuccess(t *testing.T) {
t.Fatalf("Unable to create credential. Received: %v", err)
}
cred.refreshToken = "refresh_token"
tk, err := cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
tk, err := cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{deviceCodeScopes}})
if err != nil {
t.Fatalf("Received an unexpected error: %s", err.Error())
}
@ -318,7 +319,7 @@ func TestBearerPolicy_DeviceCodeCredential(t *testing.T) {
t.Fatalf("Unable to create credential. Received: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, deviceCodeScopes)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}

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

@ -8,6 +8,8 @@ import (
"os"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
)
@ -19,13 +21,13 @@ type EnvironmentCredentialOptions struct {
AuthorityHost string
// HTTPClient sets the transport for making HTTP requests
// Leave this as nil to use the default HTTP transport
HTTPClient azcore.Transporter
HTTPClient policy.Transporter
// Retry configures the built-in retry policy behavior
Retry azcore.RetryOptions
Retry policy.RetryOptions
// Telemetry configures the built-in telemetry policy behavior
Telemetry azcore.TelemetryOptions
Telemetry policy.TelemetryOptions
// Logging configures the built-in logging policy behavior.
Logging azcore.LogOptions
Logging policy.LogOptions
}
// EnvironmentCredential enables authentication to Azure Active Directory using either ClientSecretCredential, ClientCertificateCredential or UsernamePasswordCredential.
@ -96,12 +98,12 @@ func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*Environme
// ctx: Context used to control the request lifetime.
// opts: TokenRequestOptions contains the list of scopes for which the token will have access.
// Returns an AccessToken which can be used to authenticate service client calls.
func (c *EnvironmentCredential) GetToken(ctx context.Context, opts azcore.TokenRequestOptions) (*azcore.AccessToken, error) {
func (c *EnvironmentCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) {
return c.cred.GetToken(ctx, opts)
}
// NewAuthenticationPolicy implements the azcore.Credential interface on EnvironmentCredential.
func (c *EnvironmentCredential) NewAuthenticationPolicy(options azcore.AuthenticationOptions) azcore.Policy {
func (c *EnvironmentCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy {
return newBearerTokenPolicy(c.cred, options)
}

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

@ -3,7 +3,7 @@ module github.com/Azure/azure-sdk-for-go/sdk/azidentity
go 1.14
require (
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.18.1
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0
github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4
golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897

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

@ -1,5 +1,5 @@
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.18.1 h1:BxW0zeNz9VbxtaeyuwAsgZ2WgCG7wwjb17H3f5czlp4=
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.18.1/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw=
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA=
github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw=
github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0=
github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=

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

@ -13,6 +13,8 @@ import (
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/uuid"
"github.com/pkg/browser"
)
@ -40,13 +42,13 @@ type InteractiveBrowserCredentialOptions struct {
AuthorityHost string
// HTTPClient sets the transport for making HTTP requests
// Leave this as nil to use the default HTTP transport
HTTPClient azcore.Transporter
HTTPClient policy.Transporter
// Retry configures the built-in retry policy behavior
Retry azcore.RetryOptions
Retry policy.RetryOptions
// Telemetry configures the built-in telemetry policy behavior
Telemetry azcore.TelemetryOptions
Telemetry policy.TelemetryOptions
// Logging configures the built-in logging policy behavior.
Logging azcore.LogOptions
Logging policy.LogOptions
}
// init returns an instance of InteractiveBrowserCredentialOptions initialized with default values.
@ -92,7 +94,7 @@ func NewInteractiveBrowserCredential(options *InteractiveBrowserCredentialOption
// ctx: Context used to control the request lifetime.
// opts: TokenRequestOptions contains the list of scopes for which the token will have access.
// Returns an AccessToken which can be used to authenticate service client calls.
func (c *InteractiveBrowserCredential) GetToken(ctx context.Context, opts azcore.TokenRequestOptions) (*azcore.AccessToken, error) {
func (c *InteractiveBrowserCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) {
tk, err := c.client.authenticateInteractiveBrowser(ctx, &c.options, opts.Scopes)
if err != nil {
addGetTokenFailureLogs("Interactive Browser Credential", err, true)
@ -103,7 +105,7 @@ func (c *InteractiveBrowserCredential) GetToken(ctx context.Context, opts azcore
}
// NewAuthenticationPolicy implements the azcore.Credential interface on InteractiveBrowserCredential.
func (c *InteractiveBrowserCredential) NewAuthenticationPolicy(options azcore.AuthenticationOptions) azcore.Policy {
func (c *InteractiveBrowserCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy {
return newBearerTokenPolicy(c, options)
}
@ -119,14 +121,13 @@ var authCodeReceiver = func(ctx context.Context, authorityHost string, opts *Int
func interactiveBrowserLogin(ctx context.Context, authorityHost string, opts *InteractiveBrowserCredentialOptions, scopes []string) (*interactiveConfig, error) {
// start local redirect server so login can call us back
rs := newServer()
uuidRaw, err := uuid.New()
state, err := uuid.New()
if err != nil {
return nil, err
}
state := uuidRaw.String()
redirectURL := opts.RedirectURL
if redirectURL == "" {
redirectURL = rs.Start(state, opts.Port)
redirectURL = rs.Start(state.String(), opts.Port)
}
defer rs.Stop()
u, err := url.Parse(authorityHost)
@ -138,13 +139,13 @@ func interactiveBrowserLogin(ctx context.Context, authorityHost string, opts *In
values.Add("response_mode", "query")
values.Add("client_id", opts.ClientID)
values.Add("redirect_uri", redirectURL)
values.Add("state", state)
values.Add("state", state.String())
values.Add("scope", strings.Join(scopes, " "))
values.Add("prompt", "select_account")
cv := ""
// the code verifier is a random 32-byte sequence that's been base-64 encoded without padding.
// it's used to prevent MitM attacks during auth code flow, see https://tools.ietf.org/html/rfc7636
b := make([]byte, 32, 32) // nolint:gosimple
b := make([]byte, 32) // nolint:gosimple
if _, err := rand.Read(b); err != nil {
return nil, err
}
@ -153,7 +154,7 @@ func interactiveBrowserLogin(ctx context.Context, authorityHost string, opts *In
cvh := sha256.Sum256([]byte(cv))
values.Add("code_challenge", base64.RawURLEncoding.EncodeToString(cvh[:]))
values.Add("code_challenge_method", "S256")
u.Path = azcore.JoinPaths(u.Path, opts.TenantID, path.Join(oauthPath(opts.TenantID), "/authorize"))
u.Path = runtime.JoinPaths(u.Path, opts.TenantID, path.Join(oauthPath(opts.TenantID), "/authorize"))
u.RawQuery = values.Encode()
// open browser window so user can select credentials
if err = browser.OpenURL(u.String()); err != nil {

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

@ -9,7 +9,7 @@ import (
"net/http"
"testing"
"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/internal/mock"
"golang.org/x/net/http2"
)
@ -69,7 +69,7 @@ func TestInteractiveBrowserCredential_GetTokenSuccess(t *testing.T) {
redirectURI: srv.URL(),
}, nil
}
tk, err := cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{"https://storage.azure.com/.default"}})
tk, err := cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{"https://storage.azure.com/.default"}})
if err != nil {
t.Fatalf("Expected an empty error but received: %v", err)
}
@ -105,7 +105,7 @@ func TestInteractiveBrowserCredential_SetPort(t *testing.T) {
redirectURI: srv.URL(),
}, nil
}
tk, err := cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{"https://storage.azure.com/.default"}})
tk, err := cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{"https://storage.azure.com/.default"}})
if err != nil {
t.Fatalf("Expected an empty error but received: %v", err)
}
@ -138,7 +138,7 @@ func TestInteractiveBrowserCredential_GetTokenInvalidCredentials(t *testing.T) {
redirectURI: srv.URL(),
}, nil
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err == nil {
t.Fatalf("Expected an error but did not receive one.")
}

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

@ -48,17 +48,15 @@ func createClientAssertionJWT(clientID string, audience string, cert *certConten
headerJSON, err := json.Marshal(headerData)
if err != nil {
return "", fmt.Errorf("Marshal headerJWT: %w", err)
return "", fmt.Errorf("marshal headerJWT: %w", err)
}
header := base64.RawURLEncoding.EncodeToString(headerJSON)
rawUuid, err := uuid.New()
jti, err := uuid.New()
if err != nil {
return "", err
}
payloadData := payloadJWT{
JTI: rawUuid.String(),
JTI: jti.String(),
AUD: audience,
ISS: clientID,
SUB: clientID,
@ -68,7 +66,7 @@ func createClientAssertionJWT(clientID string, audience string, cert *certConten
payloadJSON, err := json.Marshal(payloadData)
if err != nil {
return "", fmt.Errorf("Marshal payloadJWT: %w", err)
return "", fmt.Errorf("marshal payloadJWT: %w", err)
}
payload := base64.RawURLEncoding.EncodeToString(payloadJSON)
result := header + "." + payload

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

@ -9,6 +9,7 @@ import (
"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/internal/diag"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
)
@ -45,7 +46,7 @@ func logEnvVars() {
}
}
func logGetTokenSuccess(cred azcore.TokenCredential, opts azcore.TokenRequestOptions) {
func logGetTokenSuccess(cred azcore.TokenCredential, opts policy.TokenRequestOptions) {
if !log.Should(LogCredential) {
return
}
@ -83,7 +84,7 @@ func addGetTokenFailureLogs(credName string, err error, includeStack bool) {
stack := ""
if includeStack {
// skip the stack trace frames and ourself
stack = "\n" + diag.StackTrace(3, azcore.StackFrameCount)
stack = "\n" + diag.StackTrace(3, 32)
}
log.Writef(LogCredential, "Azure Identity => ERROR in GetToken() call for %s: %s%s", credName, err.Error(), stack)
}

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

@ -17,6 +17,9 @@ import (
"time"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
)
const (
@ -49,14 +52,14 @@ const (
)
// managedIdentityClient provides the base for authenticating in managed identity environments
// This type includes an azcore.Pipeline and TokenCredentialOptions.
// This type includes an runtime.Pipeline and TokenCredentialOptions.
type managedIdentityClient struct {
pipeline azcore.Pipeline
imdsAPIVersion string
imdsAvailableTimeoutMS time.Duration
msiType msiType
endpoint string
id ManagedIdentityIDKind
pipeline runtime.Pipeline
imdsAPIVersion string
imdsAvailableTimeout time.Duration
msiType msiType
endpoint string
id ManagedIdentityIDKind
}
type wrappedNumber json.Number
@ -76,11 +79,11 @@ func (n *wrappedNumber) UnmarshalJSON(b []byte) error {
func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) *managedIdentityClient {
logEnvVars()
return &managedIdentityClient{
id: options.ID,
pipeline: newDefaultMSIPipeline(*options), // a pipeline that includes the specific requirements for MSI authentication, such as custom retry policy options
imdsAPIVersion: imdsAPIVersion, // this field will be set to whatever value exists in the constant and is used when creating requests to IMDS
imdsAvailableTimeoutMS: 500, // we allow a timeout of 500 ms since the endpoint might be slow to respond
msiType: msiTypeUnknown, // when creating a new managedIdentityClient, the current MSI type is unknown and will be tested for and replaced once authenticate() is called from GetToken on the credential side
id: options.ID,
pipeline: newDefaultMSIPipeline(*options), // a pipeline that includes the specific requirements for MSI authentication, such as custom retry policy options
imdsAPIVersion: imdsAPIVersion, // this field will be set to whatever value exists in the constant and is used when creating requests to IMDS
imdsAvailableTimeout: 500 * time.Millisecond, // we allow a timeout of 500 ms since the endpoint might be slow to respond
msiType: msiTypeUnknown, // when creating a new managedIdentityClient, the current MSI type is unknown and will be tested for and replaced once authenticate() is called from GetToken on the credential side
}
}
@ -99,7 +102,7 @@ func (c *managedIdentityClient) authenticate(ctx context.Context, clientID strin
return nil, err
}
if azcore.HasStatusCode(resp, successStatusCodes[:]...) {
if runtime.HasStatusCode(resp, successStatusCodes[:]...) {
return c.createAccessToken(resp)
}
@ -114,7 +117,7 @@ func (c *managedIdentityClient) createAccessToken(res *http.Response) (*azcore.A
ExpiresIn wrappedNumber `json:"expires_in,omitempty"` // this field should always return the number of seconds for which a token is valid
ExpiresOn interface{} `json:"expires_on,omitempty"` // the value returned in this field varies between a number and a date string
}{}
if err := azcore.UnmarshalAsJSON(res, &value); err != nil {
if err := runtime.UnmarshalAsJSON(res, &value); err != nil {
return nil, fmt.Errorf("internal AccessToken: %w", err)
}
if value.ExpiresIn != "" {
@ -147,7 +150,7 @@ func (c *managedIdentityClient) createAccessToken(res *http.Response) (*azcore.A
}
}
func (c *managedIdentityClient) createAuthRequest(ctx context.Context, clientID string, scopes []string) (*azcore.Request, error) {
func (c *managedIdentityClient) createAuthRequest(ctx context.Context, clientID string, scopes []string) (*policy.Request, error) {
switch c.msiType {
case msiTypeIMDS:
return c.createIMDSAuthRequest(ctx, clientID, scopes)
@ -176,13 +179,13 @@ func (c *managedIdentityClient) createAuthRequest(ctx context.Context, clientID
}
}
func (c *managedIdentityClient) createIMDSAuthRequest(ctx context.Context, id string, scopes []string) (*azcore.Request, error) {
request, err := azcore.NewRequest(ctx, http.MethodGet, c.endpoint)
func (c *managedIdentityClient) createIMDSAuthRequest(ctx context.Context, id string, scopes []string) (*policy.Request, error) {
request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return nil, err
}
request.Header.Set(headerMetadata, "true")
q := request.URL.Query()
request.Raw().Header.Set(headerMetadata, "true")
q := request.Raw().URL.Query()
q.Add("api-version", c.imdsAPIVersion)
q.Add("resource", strings.Join(scopes, " "))
if c.id == ResourceID {
@ -190,18 +193,18 @@ func (c *managedIdentityClient) createIMDSAuthRequest(ctx context.Context, id st
} else if id != "" {
q.Add(qpClientID, id)
}
request.URL.RawQuery = q.Encode()
request.Raw().URL.RawQuery = q.Encode()
return request, nil
}
func (c *managedIdentityClient) createAppServiceAuthRequest(ctx context.Context, id string, scopes []string) (*azcore.Request, error) {
request, err := azcore.NewRequest(ctx, http.MethodGet, c.endpoint)
func (c *managedIdentityClient) createAppServiceAuthRequest(ctx context.Context, id string, scopes []string) (*policy.Request, error) {
request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return nil, err
}
q := request.URL.Query()
q := request.Raw().URL.Query()
if c.msiType == msiTypeAppServiceV20170901 {
request.Header.Set("secret", os.Getenv(msiSecret))
request.Raw().Header.Set("secret", os.Getenv(msiSecret))
q.Add("api-version", "2017-09-01")
q.Add("resource", strings.Join(scopes, " "))
if c.id == ResourceID {
@ -211,7 +214,7 @@ func (c *managedIdentityClient) createAppServiceAuthRequest(ctx context.Context,
q.Add("clientid", id)
}
} else if c.msiType == msiTypeAppServiceV20190801 {
request.Header.Set("X-IDENTITY-HEADER", os.Getenv(identityHeader))
request.Raw().Header.Set("X-IDENTITY-HEADER", os.Getenv(identityHeader))
q.Add("api-version", "2019-08-01")
q.Add("resource", scopes[0])
if c.id == ResourceID {
@ -221,38 +224,38 @@ func (c *managedIdentityClient) createAppServiceAuthRequest(ctx context.Context,
}
}
request.URL.RawQuery = q.Encode()
request.Raw().URL.RawQuery = q.Encode()
return request, nil
}
func (c *managedIdentityClient) createServiceFabricAuthRequest(ctx context.Context, id string, scopes []string) (*azcore.Request, error) {
request, err := azcore.NewRequest(ctx, http.MethodGet, c.endpoint)
func (c *managedIdentityClient) createServiceFabricAuthRequest(ctx context.Context, id string, scopes []string) (*policy.Request, error) {
request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return nil, err
}
q := request.URL.Query()
request.Header.Set("Accept", "application/json")
request.Header.Set("Secret", os.Getenv(identityHeader))
q := request.Raw().URL.Query()
request.Raw().Header.Set("Accept", "application/json")
request.Raw().Header.Set("Secret", os.Getenv(identityHeader))
q.Add("api-version", serviceFabricAPIVersion)
q.Add("resource", strings.Join(scopes, " "))
if id != "" {
q.Add(qpClientID, id)
}
request.URL.RawQuery = q.Encode()
request.Raw().URL.RawQuery = q.Encode()
return request, nil
}
func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resources []string) (string, error) {
// create the request to retreive the secret key challenge provided by the HIMDS service
request, err := azcore.NewRequest(ctx, http.MethodGet, c.endpoint)
request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return "", err
}
request.Header.Set(headerMetadata, "true")
q := request.URL.Query()
request.Raw().Header.Set(headerMetadata, "true")
q := request.Raw().URL.Query()
q.Add("api-version", azureArcAPIVersion)
q.Add("resource", strings.Join(resources, " "))
request.URL.RawQuery = q.Encode()
request.Raw().URL.RawQuery = q.Encode()
// send the initial request to get the short-lived secret key
response, err := c.pipeline.Do(request)
if err != nil {
@ -265,47 +268,47 @@ func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resour
}
header := response.Header.Get("WWW-Authenticate")
if len(header) == 0 {
return "", errors.New("Did not receive a value from WWW-Authenticate header")
return "", errors.New("did not receive a value from WWW-Authenticate header")
}
// the WWW-Authenticate header is expected in the following format: Basic realm=/some/file/path.key
pos := strings.LastIndex(header, "=")
if pos == -1 {
return "", fmt.Errorf("Did not receive a correct value from WWW-Authenticate header: %s", header)
return "", fmt.Errorf("did not receive a correct value from WWW-Authenticate header: %s", header)
}
key, err := ioutil.ReadFile(header[pos+1:])
if err != nil {
return "", fmt.Errorf("Could not read file (%s) contents: %w", header[pos+1:], err)
return "", fmt.Errorf("could not read file (%s) contents: %w", header[pos+1:], err)
}
return string(key), nil
}
func (c *managedIdentityClient) createAzureArcAuthRequest(ctx context.Context, key string, resources []string) (*azcore.Request, error) {
request, err := azcore.NewRequest(ctx, http.MethodGet, c.endpoint)
func (c *managedIdentityClient) createAzureArcAuthRequest(ctx context.Context, key string, resources []string) (*policy.Request, error) {
request, err := runtime.NewRequest(ctx, http.MethodGet, c.endpoint)
if err != nil {
return nil, err
}
request.Header.Set(headerMetadata, "true")
request.Header.Set(headerAuthorization, fmt.Sprintf("Basic %s", key))
q := request.URL.Query()
request.Raw().Header.Set(headerMetadata, "true")
request.Raw().Header.Set(headerAuthorization, fmt.Sprintf("Basic %s", key))
q := request.Raw().URL.Query()
q.Add("api-version", azureArcAPIVersion)
q.Add("resource", strings.Join(resources, " "))
request.URL.RawQuery = q.Encode()
request.Raw().URL.RawQuery = q.Encode()
return request, nil
}
func (c *managedIdentityClient) createCloudShellAuthRequest(ctx context.Context, clientID string, scopes []string) (*azcore.Request, error) {
request, err := azcore.NewRequest(ctx, http.MethodPost, c.endpoint)
func (c *managedIdentityClient) createCloudShellAuthRequest(ctx context.Context, clientID string, scopes []string) (*policy.Request, error) {
request, err := runtime.NewRequest(ctx, http.MethodPost, c.endpoint)
if err != nil {
return nil, err
}
request.Header.Set(headerMetadata, "true")
request.Raw().Header.Set(headerMetadata, "true")
data := url.Values{}
data.Set("resource", strings.Join(scopes, " "))
if clientID != "" {
data.Set(qpClientID, clientID)
}
dataEncoded := data.Encode()
body := azcore.NopCloser(strings.NewReader(dataEncoded))
body := streaming.NopCloser(strings.NewReader(dataEncoded))
if err := request.SetBody(body, headerURLEncoded); err != nil {
return nil, err
}
@ -347,16 +350,16 @@ func (c *managedIdentityClient) getMSIType() (msiType, error) {
// performs an I/O request that has a timeout of 500 milliseconds
func (c *managedIdentityClient) imdsAvailable() bool {
tempCtx, cancel := context.WithTimeout(context.Background(), c.imdsAvailableTimeoutMS*time.Millisecond)
tempCtx, cancel := context.WithTimeout(context.Background(), c.imdsAvailableTimeout)
defer cancel()
// this should never fail
request, _ := azcore.NewRequest(tempCtx, http.MethodGet, imdsEndpoint)
q := request.URL.Query()
request, _ := runtime.NewRequest(tempCtx, http.MethodGet, imdsEndpoint)
q := request.Raw().URL.Query()
q.Add("api-version", c.imdsAPIVersion)
request.URL.RawQuery = q.Encode()
request.Raw().URL.RawQuery = q.Encode()
resp, err := c.pipeline.Do(request)
if err == nil {
azcore.Drain(resp)
runtime.Drain(resp)
}
return err == nil
}

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

@ -10,7 +10,7 @@ import (
"strings"
"testing"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)
@ -29,7 +29,7 @@ func TestMSITelemetryDefaultUserAgent(t *testing.T) {
HTTPClient: srv,
}
pipeline := newDefaultMSIPipeline(options)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@ -40,7 +40,7 @@ func TestMSITelemetryDefaultUserAgent(t *testing.T) {
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d", resp.StatusCode)
}
if ua := resp.Request.Header.Get(headerUserAgent); !strings.HasPrefix(ua, UserAgent) {
if ua := resp.Request.Header.Get(headerUserAgent); !strings.HasPrefix(ua, "azsdk-go-"+component+"/"+version) {
t.Fatalf("unexpected User-Agent %s", ua)
}
}
@ -53,9 +53,9 @@ func TestMSITelemetryCustom(t *testing.T) {
options := ManagedIdentityCredentialOptions{
HTTPClient: srv,
}
options.Telemetry.Value = customTelemetry
options.Telemetry.ApplicationID = customTelemetry
pipeline := newDefaultMSIPipeline(options)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
@ -66,7 +66,7 @@ func TestMSITelemetryCustom(t *testing.T) {
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d", resp.StatusCode)
}
if ua := resp.Request.Header.Get(headerUserAgent); !strings.HasPrefix(ua, customTelemetry+" "+UserAgent) {
if ua := resp.Request.Header.Get(headerUserAgent); !strings.HasPrefix(ua, customTelemetry+" "+"azsdk-go-"+component+"/"+version) {
t.Fatalf("unexpected User-Agent %s", ua)
}
}

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

@ -9,6 +9,8 @@ import (
"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/azcore/runtime"
)
// ManagedIdentityIDKind is used to specify the type of identifier that is passed in for a user-assigned managed identity.
@ -32,13 +34,13 @@ type ManagedIdentityCredentialOptions struct {
// HTTPClient sets the transport for making HTTP requests.
// Leave this as nil to use the default HTTP transport.
HTTPClient azcore.Transporter
HTTPClient policy.Transporter
// Telemetry configures the built-in telemetry policy behavior.
Telemetry azcore.TelemetryOptions
Telemetry policy.TelemetryOptions
// Logging configures the built-in logging policy behavior.
Logging azcore.LogOptions
Logging policy.LogOptions
}
// ManagedIdentityCredential attempts authentication using a managed identity that has been assigned to the deployment environment. This authentication type works in several
@ -84,7 +86,7 @@ func NewManagedIdentityCredential(id string, options *ManagedIdentityCredentialO
// GetToken obtains an AccessToken from the Managed Identity service if available.
// scopes: The list of scopes for which the token will have access.
// Returns an AccessToken which can be used to authenticate service client calls.
func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts azcore.TokenRequestOptions) (*azcore.AccessToken, error) {
func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) {
if opts.Scopes == nil {
err := &AuthenticationFailedError{msg: "must specify a resource in order to authenticate"}
addGetTokenFailureLogs("Managed Identity Credential", err, true)
@ -109,7 +111,7 @@ func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts azcore.To
// NewAuthenticationPolicy implements the azcore.Credential interface on ManagedIdentityCredential.
// NOTE: The TokenRequestOptions included in AuthenticationOptions must be a slice of resources in this case and not scopes.
func (c *ManagedIdentityCredential) NewAuthenticationPolicy(options azcore.AuthenticationOptions) azcore.Policy {
func (c *ManagedIdentityCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy {
return newBearerTokenPolicy(c, options)
}

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

@ -11,7 +11,8 @@ import (
"strings"
"testing"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)
@ -36,7 +37,7 @@ func TestManagedIdentityCredential_GetTokenInAzureArcLive(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -50,7 +51,7 @@ func TestManagedIdentityCredential_GetTokenInCloudShellLive(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -69,7 +70,7 @@ func TestManagedIdentityCredential_GetTokenInCloudShellMock(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -88,7 +89,7 @@ func TestManagedIdentityCredential_GetTokenInCloudShellMockFail(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err == nil {
t.Fatalf("Expected an error but did not receive one")
}
@ -108,7 +109,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceV20170901Mock_windows(t *
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
tk, err := msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
tk, err := msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -134,7 +135,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceV20170901Mock_linux(t *te
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
tk, err := msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
tk, err := msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -160,7 +161,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceV20190801Mock_windows(t *
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
tk, err := msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
tk, err := msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -186,7 +187,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceV20190801Mock_linux(t *te
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
tk, err := msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
tk, err := msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -217,7 +218,7 @@ func TestManagedIdentityCredential_GetTokenInAzureFunctions_linux(t *testing.T)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
tk, err := msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
tk, err := msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -244,10 +245,10 @@ func TestManagedIdentityCredential_CreateAppServiceAuthRequestV20190801(t *testi
if err != nil {
t.Fatal(err)
}
if req.Request.Header.Get("X-IDENTITY-HEADER") != "header" {
if req.Raw().Header.Get("X-IDENTITY-HEADER") != "header" {
t.Fatalf("Unexpected value for secret header")
}
reqQueryParams, err := url.ParseQuery(req.URL.RawQuery)
reqQueryParams, err := url.ParseQuery(req.Raw().URL.RawQuery)
if err != nil {
t.Fatalf("Unable to parse App Service request query params: %v", err)
}
@ -277,10 +278,10 @@ func TestManagedIdentityCredential_CreateAppServiceAuthRequestV20170901(t *testi
if err != nil {
t.Fatal(err)
}
if req.Request.Header.Get("secret") != "secret" {
if req.Raw().Header.Get("secret") != "secret" {
t.Fatalf("Unexpected value for secret header")
}
reqQueryParams, err := url.ParseQuery(req.URL.RawQuery)
reqQueryParams, err := url.ParseQuery(req.Raw().URL.RawQuery)
if err != nil {
t.Fatalf("Unable to parse App Service request query params: %v", err)
}
@ -309,7 +310,7 @@ func TestManagedIdentityCredential_CreateAccessTokenExpiresOnStringInt(t *testin
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -329,7 +330,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceMockFail(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err == nil {
t.Fatalf("Expected an error but did not receive one")
}
@ -349,7 +350,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceMockFail(t *testing.T) {
// options := DefaultManagedIdentityCredentialOptions()
// options.HTTPClient = srv
// msiCred := NewManagedIdentityCredential("", &options)
// _, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
// _, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
// if err == nil {
// t.Fatalf("Cannot run IMDS test in this environment")
// }
@ -377,7 +378,7 @@ func TestManagedIdentityCredential_NewManagedIdentityCredentialFail(t *testing.T
if err != nil {
t.Fatal(err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{})
if err == nil {
t.Fatalf("Expected an error but did not receive one")
}
@ -397,7 +398,7 @@ func TestBearerPolicy_ManagedIdentityCredential(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, msiScope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}
@ -420,7 +421,7 @@ func TestManagedIdentityCredential_GetTokenUnexpectedJSON(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err == nil {
t.Fatalf("Expected a JSON marshal error but received nil")
}
@ -440,10 +441,10 @@ func TestManagedIdentityCredential_CreateIMDSAuthRequest(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if req.Request.Header.Get(headerMetadata) != "true" {
if req.Raw().Header.Get(headerMetadata) != "true" {
t.Fatalf("Unexpected value for Content-Type header")
}
reqQueryParams, err := url.ParseQuery(req.URL.RawQuery)
reqQueryParams, err := url.ParseQuery(req.Raw().URL.RawQuery)
if err != nil {
t.Fatalf("Unable to parse IMDS query params: %v", err)
}
@ -456,10 +457,10 @@ func TestManagedIdentityCredential_CreateIMDSAuthRequest(t *testing.T) {
if reqQueryParams["client_id"][0] != clientID {
t.Fatalf("Unexpected client ID. Expected: %s, Received: %s", clientID, reqQueryParams["client_id"][0])
}
if u := req.Request.URL.String(); !strings.HasPrefix(u, imdsEndpoint) {
if u := req.Raw().URL.String(); !strings.HasPrefix(u, imdsEndpoint) {
t.Fatalf("Unexpected default authority host %s", u)
}
if req.Request.URL.Scheme != "http" {
if req.Raw().URL.Scheme != "http" {
t.Fatalf("Wrong request scheme")
}
}
@ -481,7 +482,7 @@ func TestManagedIdentityCredential_GetTokenEnvVar(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
at, err := msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
at, err := msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -503,7 +504,7 @@ func TestManagedIdentityCredential_GetTokenNilResource(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: nil})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: nil})
if err == nil {
t.Fatalf("Expected an error but did not receive one")
}
@ -528,7 +529,7 @@ func TestManagedIdentityCredential_ScopesImmutable(t *testing.T) {
}
scope := "https://localhost/.default"
scopes := []string{scope}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: scopes})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: scopes})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@ -550,7 +551,7 @@ func TestManagedIdentityCredential_GetTokenMultipleResources(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{"resource1", "resource2"}})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{"resource1", "resource2"}})
if err == nil {
t.Fatalf("Expected an error but did not receive one")
}
@ -574,7 +575,7 @@ func TestManagedIdentityCredential_UseResourceID(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
tk, err := cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
tk, err := cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatal(err)
}
@ -599,10 +600,10 @@ func TestManagedIdentityCredential_ResourceID_AppService(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if req.Request.Header.Get("X-IDENTITY-HEADER") != "header" {
if req.Raw().Header.Get("X-IDENTITY-HEADER") != "header" {
t.Fatalf("Unexpected value for secret header")
}
reqQueryParams, err := url.ParseQuery(req.URL.RawQuery)
reqQueryParams, err := url.ParseQuery(req.Raw().URL.RawQuery)
if err != nil {
t.Fatalf("Unable to parse App Service request query params: %v", err)
}
@ -632,7 +633,7 @@ func TestManagedIdentityCredential_ResourceID_IMDS(t *testing.T) {
if err != nil {
t.Fatal(err)
}
reqQueryParams, err := url.ParseQuery(req.URL.RawQuery)
reqQueryParams, err := url.ParseQuery(req.Raw().URL.RawQuery)
if err != nil {
t.Fatalf("Unable to parse App Service request query params: %v", err)
}
@ -661,7 +662,7 @@ func TestManagedIdentityCredential_CreateAccessTokenExpiresOnInt(t *testing.T) {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err != nil {
t.Fatalf("Received an error when attempting to retrieve a token")
}
@ -682,7 +683,7 @@ func TestManagedIdentityCredential_CreateAccessTokenExpiresOnFail(t *testing.T)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_, err = msiCred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{msiScope}})
_, err = msiCred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}})
if err == nil {
t.Fatalf("expected to receive an error but received none")
}

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

@ -7,6 +7,8 @@ import (
"context"
"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/azcore/runtime"
)
// UsernamePasswordCredentialOptions can be used to provide additional information to configure the UsernamePasswordCredential.
@ -18,13 +20,13 @@ type UsernamePasswordCredentialOptions struct {
AuthorityHost string
// HTTPClient sets the transport for making HTTP requests
// Leave this as nil to use the default HTTP transport
HTTPClient azcore.Transporter
HTTPClient policy.Transporter
// Retry configures the built-in retry policy behavior
Retry azcore.RetryOptions
Retry policy.RetryOptions
// Telemetry configures the built-in telemetry policy behavior
Telemetry azcore.TelemetryOptions
Telemetry policy.TelemetryOptions
// Logging configures the built-in logging policy behavior.
Logging azcore.LogOptions
Logging policy.LogOptions
}
// UsernamePasswordCredential enables authentication to Azure Active Directory using a user's username and password. If the user has MFA enabled this
@ -67,7 +69,7 @@ func NewUsernamePasswordCredential(tenantID string, clientID string, username st
// scopes: The list of scopes for which the token will have access.
// ctx: The context used to control the request lifetime.
// Returns an AccessToken which can be used to authenticate service client calls.
func (c *UsernamePasswordCredential) GetToken(ctx context.Context, opts azcore.TokenRequestOptions) (*azcore.AccessToken, error) {
func (c *UsernamePasswordCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) {
tk, err := c.client.authenticateUsernamePassword(ctx, c.tenantID, c.clientID, c.username, c.password, opts.Scopes)
if err != nil {
addGetTokenFailureLogs("Username Password Credential", err, true)
@ -78,7 +80,7 @@ func (c *UsernamePasswordCredential) GetToken(ctx context.Context, opts azcore.T
}
// NewAuthenticationPolicy implements the azcore.Credential interface on UsernamePasswordCredential.
func (c *UsernamePasswordCredential) NewAuthenticationPolicy(options azcore.AuthenticationOptions) azcore.Policy {
func (c *UsernamePasswordCredential) NewAuthenticationPolicy(options runtime.AuthenticationOptions) policy.Policy {
return newBearerTokenPolicy(c, options)
}

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

@ -11,7 +11,8 @@ import (
"net/url"
"testing"
"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/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)
@ -38,10 +39,10 @@ func TestUsernamePasswordCredential_CreateAuthRequestSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Unexpectedly received an error: %v", err)
}
if req.Request.Header.Get(headerContentType) != headerURLEncoded {
if req.Raw().Header.Get(headerContentType) != headerURLEncoded {
t.Fatalf("Unexpected value for Content-Type header")
}
body, err := ioutil.ReadAll(req.Request.Body)
body, err := ioutil.ReadAll(req.Raw().Body)
if err != nil {
t.Fatalf("Unable to read request body")
}
@ -68,10 +69,10 @@ func TestUsernamePasswordCredential_CreateAuthRequestSuccess(t *testing.T) {
if reqQueryParams[qpScope][0] != scope {
t.Fatalf("Unexpected scope in scope header")
}
if req.Request.URL.Host != defaultTestAuthorityHost {
if req.Raw().URL.Host != defaultTestAuthorityHost {
t.Fatalf("Unexpected default authority host")
}
if req.Request.URL.Scheme != "https" {
if req.Raw().URL.Scheme != "https" {
t.Fatalf("Wrong request scheme")
}
}
@ -87,7 +88,7 @@ func TestUsernamePasswordCredential_GetTokenSuccess(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err != nil {
t.Fatalf("Expected an empty error but received: %s", err.Error())
}
@ -104,7 +105,7 @@ func TestUsernamePasswordCredential_GetTokenInvalidCredentials(t *testing.T) {
if err != nil {
t.Fatalf("Unable to create credential. Received: %v", err)
}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: []string{scope}})
_, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}})
if err == nil {
t.Fatalf("Expected an error but did not receive one.")
}
@ -123,7 +124,7 @@ func TestBearerPolicy_UsernamePasswordCredential(t *testing.T) {
t.Fatalf("Unable to create credential. Received: %v", err)
}
pipeline := defaultTestPipeline(srv, cred, scope)
req, err := azcore.NewRequest(context.Background(), http.MethodGet, srv.URL())
req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatal(err)
}

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

@ -8,8 +8,8 @@ package azidentity
const (
// UserAgent is the string to be used in the user agent string when making requests.
UserAgent = "azidentity/" + Version
component = "azidentity"
// Version is the semantic version (see http://semver.org) of this module.
Version = "v0.9.2"
version = "v0.10.0"
)