microsoft / kiota-samples

sample generation SDKs for Kiota
https://aka.ms/kiota/docs
MIT License
73 stars 26 forks source link

Authentication for APIs with basic authentication and bearer #3230

Open robertvanmolken opened 11 months ago

robertvanmolken commented 11 months ago

I'm looking for an example implementation that can call APIs protected by either basic auth as bearer token.

I see that there is a BaseBearerToken provider but can find any example implementation.

It requires an AccessTokenProvider and I am struggling how to implement that.

Can this please be added to the documentation

baywet commented 8 months ago

Hi @robertvanmolken Thank you for using kiota and sorry for the delay in the answer, it appears I was not watching issues on this repository. Which language are you referring to?

jakejscott commented 5 months ago

Examples for dotnet would be great :)

baywet commented 5 months ago

provided a bit of guidance, would either of you be willing to submit a pull request?

pickettd commented 5 months ago

@robertvanmolken and @jakejscott - I'll paste a snippet below that worked for me for using Kiota with bearer auth in dotnet. And @baywet I'm willing to submit a PR if it is useful


using KiotaPosts.Client.Models;
using Microsoft.Kiota.Abstractions.Authentication;
using Microsoft.Kiota.Http.HttpClientLibrary;

// authentication provider using class from below
TokenProvider myTokenProvider = new TokenProvider();
var authProvider = new BaseBearerTokenAuthenticationProvider(myTokenProvider);
// Create request adapter using the HttpClient-based implementation
var adapter = new HttpClientRequestAdapter(authProvider);
// Create the API client
var client = new Client(adapter);

try
{
    var findId = "<example_cust_id>";

    var idCust = await client.Customers[findId].GetAsync();
    Console.WriteLine($"Retrieved by id: {idCust.Customer.Email}");
    Console.WriteLine($"Retrieved by id: {idCust.Customer.Id}");
}
catch (Exception ex)
{
    Console.WriteLine($"ERROR: {ex.Message}");
    Console.WriteLine(ex.StackTrace);
}

internal class TokenProvider : IAccessTokenProvider
{
    public AllowedHostsValidator AllowedHostsValidator { get; }

    public Task<string> GetAuthorizationTokenAsync(
        Uri uri,
        Dictionary<string, object>? additionalAuthenticationContext = null,
        CancellationToken cancellationToken = default)
    {
        return Task.FromResult("<insert_bearer_token>");
    }
}