Skip to content

Add an ApiKeyAuthenticationProvider to Kiota Core libraries #1902

Closed

Description

This class should handle the common case of adding an API key to either a request header or a query parameter.

Here's an example in C#

public class ApiKeyAuthenticationProvider : IAuthenticationProvider
{
    private readonly KeyLocation location;
    private readonly string keyName;
    private readonly  string keyValue;

    public enum KeyLocation 
    {
        QueryParameter,
        Header
    }

    public ApiKeyAuthenticationProvider(string keyName, string keyValue, KeyLocation location)
    {
        this.keyName = keyName;
        this.keyValue = keyValue;
        this.location = location;
    }

    public async Task AuthenticateRequestAsync(RequestInformation request, Dictionary<string, object> additionalAuthenticationContext = null, CancellationToken cancellationToken = default)
    {
        switch (location)
        {
            case KeyLocation.QueryParameter:
                var uriString = request.URI.OriginalString + (request.URI.Query != string.Empty?"&":"?") + $"{keyName}={keyValue}";
                request.URI = new Uri(uriString);
                break;
            case KeyLocation.Header:
                request.Headers.Add(keyName, keyValue);
                break;
            default:
                throw new ArgumentOutOfRangeException(nameof(location), location, null);
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Labels

enhancementNew feature or requestfixedgeneratorIssues or improvements relater to generation capabilities.

Type

No type

Projects

  • Status

    Done ✔️

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions