Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions sdk/core/core-http/lib/coreHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export { URLBuilder, URLQuery } from "./url";

// Credentials
export { TokenCredential, GetTokenOptions, AccessToken, isTokenCredential } from "@azure/core-auth";
export { AccessTokenCache, ExpiringAccessTokenCache } from "./credentials/accessTokenCache";
export { TokenCredentials } from "./credentials/tokenCredentials";
export { BasicAuthenticationCredentials } from "./credentials/basicAuthenticationCredentials";
export { ApiKeyCredentials, ApiKeyCredentialOptions } from "./credentials/apiKeyCredentials";
Expand Down
61 changes: 61 additions & 0 deletions sdk/core/core-http/lib/credentials/accessTokenCache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import { AccessToken } from "@azure/core-auth";

/**
* Defines the default token refresh buffer duration.
*/
export const TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes

/**
* Provides a cache for an AccessToken that was that
* was returned from a TokenCredential.
*/
export interface AccessTokenCache {
/**
* Sets the cached token.
*
* @param The {@link AccessToken} to be cached or null to
* clear the cached token.
*/
setCachedToken(accessToken: AccessToken | undefined): void;

/**
* Returns the cached {@link AccessToken} or undefined if nothing is cached.
*/
getCachedToken(): AccessToken | undefined;
}

/**
* Provides an {@link AccessTokenCache} implementation which clears
* the cached {@link AccessToken}'s after the expiresOnTimestamp has
* passed.
*/
export class ExpiringAccessTokenCache implements AccessTokenCache {
private tokenRefreshBufferMs: number;
private cachedToken?: AccessToken = undefined;

/**
* Constructs an instance of {@link ExpiringAccessTokenCache} with
* an optional expiration buffer time.
*/
constructor(tokenRefreshBufferMs: number = TokenRefreshBufferMs) {
this.tokenRefreshBufferMs = tokenRefreshBufferMs;
}

setCachedToken(accessToken: AccessToken | undefined): void {
this.cachedToken = accessToken;
}

getCachedToken(): AccessToken | undefined {
if (
this.cachedToken &&
Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp
) {
this.cachedToken = undefined;
}

return this.cachedToken;
}
}
24 changes: 11 additions & 13 deletions sdk/core/core-http/lib/policies/bearerTokenAuthenticationPolicy.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import { TokenCredential, AccessToken, GetTokenOptions } from "@azure/core-auth";
import { TokenCredential, GetTokenOptions } from "@azure/core-auth";
import { BaseRequestPolicy, RequestPolicy, RequestPolicyOptions, RequestPolicyFactory } from "../policies/requestPolicy";
import { Constants } from "../util/constants";
import { HttpOperationResponse } from "../httpOperationResponse";
import { HttpHeaders, } from "../httpHeaders";
import { WebResource } from "../webResource";

export const TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes
import { AccessTokenCache, ExpiringAccessTokenCache } from "../credentials/accessTokenCache";

/**
* Creates a new BearerTokenAuthenticationPolicy factory.
Expand All @@ -17,9 +16,10 @@ export const TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes
* @param scopes The scopes for which the bearer token applies.
*/
export function bearerTokenAuthenticationPolicy(credential: TokenCredential, scopes: string | string[]): RequestPolicyFactory {
const tokenCache: AccessTokenCache = new ExpiringAccessTokenCache();
return {
create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {
return new BearerTokenAuthenticationPolicy(nextPolicy, options, credential, scopes);
return new BearerTokenAuthenticationPolicy(nextPolicy, options, credential, scopes, tokenCache);
}
};
}
Expand All @@ -32,21 +32,21 @@ export function bearerTokenAuthenticationPolicy(credential: TokenCredential, sco
*
*/
export class BearerTokenAuthenticationPolicy extends BaseRequestPolicy {
private cachedToken: AccessToken | undefined = undefined;

/**
* Creates a new BearerTokenAuthenticationPolicy object.
*
* @param nextPolicy The next RequestPolicy in the request pipeline.
* @param options Options for this RequestPolicy.
* @param credential The TokenCredential implementation that can supply the bearer token.
* @param scopes The scopes for which the bearer token applies.
* @param tokenCache The cache for the most recent AccessToken returned from the TokenCredential.
*/
constructor(
nextPolicy: RequestPolicy,
options: RequestPolicyOptions,
private credential: TokenCredential,
private scopes: string | string[],
private tokenCache: AccessTokenCache
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity, what part will manage the cache?

Copy link
Copy Markdown
Contributor Author

@daviwil daviwil Jul 3, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The consuming policy, though right after sending this I realized that there's probably value in sharing token expiration logic in a more legitimate class instead of using a simple object that must be managed by the policy implementation. Thoughts?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that there's definitely value in centralizing token expiration management, otherwise we will end up with a bug somewhere, or at least different implementations to a small extent. I wonder what would be the benefits of distributed token expiration logic, if that route is decided.

) {
super(nextPolicy, options);
}
Expand All @@ -70,14 +70,12 @@ export class BearerTokenAuthenticationPolicy extends BaseRequestPolicy {
}

private async getToken(options: GetTokenOptions): Promise<string | undefined> {
if (
this.cachedToken &&
Date.now() + TokenRefreshBufferMs < this.cachedToken.expiresOnTimestamp
) {
return this.cachedToken.token;
let accessToken = this.tokenCache.getCachedToken();
if (accessToken === undefined) {
accessToken = await this.credential.getToken(this.scopes, options) || undefined;
this.tokenCache.setCachedToken(accessToken);
}

this.cachedToken = (await this.credential.getToken(this.scopes, options)) || undefined;
return this.cachedToken ? this.cachedToken.token : undefined;
return accessToken ? accessToken.token : undefined;
}
}
39 changes: 39 additions & 0 deletions sdk/core/core-http/test/expiringAccessTokenCacheTests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { assert } from "chai";
import { ExpiringAccessTokenCache } from "../lib/credentials/accessTokenCache";

function mockToken(expirationDeltaMs: number) {
return {
token: "token",
expiresOnTimestamp: Date.now() + expirationDeltaMs
};
}

describe("ExpiringAccessTokenCache", function () {
it("returns a cached token within the expiration window", function() {
const tokenCache = new ExpiringAccessTokenCache(2000);
const accessToken = mockToken(5000);
tokenCache.setCachedToken(accessToken);

const cachedToken = tokenCache.getCachedToken();
assert.isDefined(cachedToken, "A cached token was not returned!");
});

it("returns undefined when refresh buffer is passed", function() {
const tokenCache = new ExpiringAccessTokenCache(5000);
const accessToken = mockToken(-5000);
tokenCache.setCachedToken(accessToken);

const cachedToken = tokenCache.getCachedToken();
assert.isUndefined(cachedToken, "A cached token was returned!");
});

it("clears the cached token when undefined is passed to setCachedToken", function() {
const tokenCache = new ExpiringAccessTokenCache(2000);
const accessToken = mockToken(5000);
tokenCache.setCachedToken(accessToken);
tokenCache.setCachedToken(undefined);

const cachedToken = tokenCache.getCachedToken();
assert.isUndefined(cachedToken, "A cached token was returned!");
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import { Constants } from "../../lib/util/constants";
import { HttpOperationResponse } from "../../lib/httpOperationResponse";
import { HttpHeaders, } from "../../lib/httpHeaders";
import { WebResource } from "../../lib/webResource";
import { BearerTokenAuthenticationPolicy, TokenRefreshBufferMs } from "../../lib/policies/bearerTokenAuthenticationPolicy";
import { BearerTokenAuthenticationPolicy } from "../../lib/policies/bearerTokenAuthenticationPolicy";
import { ExpiringAccessTokenCache, TokenRefreshBufferMs } from "../../lib/credentials/accessTokenCache";

describe("BearerTokenAuthenticationPolicy", function () {
const mockPolicy: RequestPolicy = {
Expand Down Expand Up @@ -76,7 +77,8 @@ describe("BearerTokenAuthenticationPolicy", function () {
mockPolicy,
new RequestPolicyOptions(),
credential,
scopes);
scopes,
new ExpiringAccessTokenCache());
}
});

Expand Down