[筆記] 實做 BearerTokenCredential 來用 Token 建立 DefaultAzureCredential

  • 111
  • 0

在之前文章「App Service 實做身份識別存取 KeyVault (二)」有針對 DefaultAzureCredential 做介紹,最近遇到一個情境是我已經用其他方式取得了 AccessToken,想直接轉成驗證的類別,但是內建的實做卻沒有一個是單純用 Token 來建立 AzureCredential,剛好有找到解法,就做一下記錄,避免之後還會用到。

實做

只需要繼承 TokenCredential 類別之後單純把 Token 傳進去類別,並且複寫 GetToken 跟 GetTokenAsync 兩個方法就好了。

public class BearerTokenCredential : TokenCredential
{
	/// <summary>
	/// Bearer Token String
	/// </summary>
	private string Token { get; set; }

	/// <summary>
	/// Constructor that takes a Bearer Token
	/// </summary>
	/// <param name="token"/>
	public BearerTokenCredential(string token)
	{
		Token = token;
	}

	/// <summary>
	/// Return a Bearer Token
	/// </summary>
	/// <param name="requestContext"/>
	/// <param name="cancellationToken"/>
	/// <returns></returns>
	public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
	{
		return new AccessToken(Token, DateTimeOffset.Now.AddDays(1));
	}

	/// <summary>
	/// Returns a Bearer Token Asynchronously
	/// </summary>
	/// <param name="requestContext"/>
	/// <param name="cancellationToken"/>
	/// <returns></returns>
	public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)
	{
		return new ValueTask<AccessToken>(Task.FromResult(new AccessToken(Token, DateTimeOffset.Now.AddDays(1))));
	}
}

底下示範用 Azure SDK 來列出 Tenant。

using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Resources;

async Task Main()
{
	TokenCredential cred = new BearerTokenCredential("{Your Token}");

	ArmClient client = new ArmClient(cred);

	TenantCollection collection = client.GetTenants();

	await foreach (TenantResource item in collection.GetAllAsync())
	{
		TenantData resourceData = item.Data;
		Console.WriteLine($"Succeeded on id: {resourceData.Id}");
	}
}

執行之後就可以看到授權底下的目錄列表了。

參考資料