dotnet-sdk icon indicating copy to clipboard operation
dotnet-sdk copied to clipboard

[DOCS]: Example on how to create a `GitHubClient` with different authentication providers

Open ElanHasson opened this issue 1 year ago • 3 comments

Describe the need

I have a system where users can provide PATs to use the GH API via our system.

We would like to be able to create a new authentication provider each time, however since the the client factory is immutable it doesn't seem to be possible.

I'm probably missing something, any guidance is welcome!

SDK Version

No response

API Version

No response

Code of Conduct

  • [X] I agree to follow this project's Code of Conduct

ElanHasson avatar Sep 18 '24 21:09 ElanHasson

👋 Hi! Thank you for this contribution! Just to let you know, our GitHub SDK team does a round of issue and PR reviews twice a week, every Monday and Friday! We have a process in place for prioritizing and responding to your input. Because you are a part of this community please feel free to comment, add to, or pick up any issues/PRs that are labeled with Status: Up for grabs. You & others like you are the reason all of this works! So thank you & happy coding! 🚀

github-actions[bot] avatar Sep 18 '24 21:09 github-actions[bot]

Hmm...I'm not sure I understand what you're after, sorry! Do you mind providing a little more detail, and/or maybe an imaginative code snippet that would reflect what you're looking for?

kfcampbell avatar Sep 27 '24 18:09 kfcampbell

Hi @kfcampbell!

Here are some details. I have a Multi-user system, users provide their own GH PAT.

I couldn't figure out how to modify the token directly for each request as the client disallows that.

So I cheated:

public class AsyncLocalTokenProvider : IAccessTokenProvider
{
    public static readonly AsyncLocal<string> Token = new(s => _ = s.CurrentValue);

    AllowedHostsValidator IAccessTokenProvider.AllowedHostsValidator => new();

    public Task<string> GetAuthorizationTokenAsync(Uri requestUri, Dictionary<string, object>? additionalAuthenticationContext = null, CancellationToken cancellationToken = default) => Task.FromResult(Token.Value ?? string.Empty);
}

Usage


  private static readonly HttpClientRequestAdapter Factory = new ClientFactory()
      .WithUserAgent($"InfinityFlow-{nameof(GitHubV1)}", System.Reflection.Assembly.GetAssembly(typeof(GitHubV1))?.GetName()?.Version?.ToString()
              ?? "0.0.0")
      .WithRequestTimeout(TimeSpan.FromSeconds(100))
      .WithAuthenticationProvider(new TokenAuthProvider(new GitHubAsyncLocalTokenProvider()))
      .WithBaseUrl("https://api.github.com")
      .Build();
    private static readonly GitHubClient GitHubClient = new(Factory);


 var credential = await Credential.Get();
 AsyncLocalTokenProvider.Token.Value = credential.Password;

There has to be a better way to do this with Kiota :D

ElanHasson avatar Sep 30 '24 01:09 ElanHasson