Skip to content

.Net: Add support for custom authentication provider for OpenAPI #2283

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Aug 11, 2023
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace Microsoft.SemanticKernel.Skills.OpenAPI.Authentication;

/// <summary>
/// Retrieves authentication content (scheme and value) via the provided delegate and applies it to HTTP requests.
/// </summary>
public sealed class CustomAuthenticationProvider
{
private readonly Func<Task<string>> _header;
private readonly Func<Task<string>> _value;

/// <summary>
/// Creates an instance of the <see cref="CustomAuthenticationProvider"/> class.
/// </summary>
/// <param name="header">Delegate for retrieving the header name.</param>
/// <param name="value">Delegate for retrieving the value.</param>
public CustomAuthenticationProvider(Func<Task<string>> header, Func<Task<string>> value)
{
this._header = header;
this._value = value;
}

/// <summary>
/// Applies the header and value to the provided HTTP request message.
/// </summary>
/// <param name="request">The HTTP request message.</param>
/// <returns></returns>
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
var header = await this._header().ConfigureAwait(false);
var value = await this._value().ConfigureAwait(false);
request.Headers.Add(header, value);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.SemanticKernel.Skills.OpenAPI.Authentication;
using Xunit;

namespace SemanticKernel.Skills.UnitTests.OpenAPI.Authentication;

public class CustomAuthenticationProviderTests
{
[Fact]
public async Task AuthenticateRequestAsyncSucceedsAsync()
{
// Arrange
var header = "X-MyHeader";
var value = Guid.NewGuid().ToString();

using var request = new HttpRequestMessage();

var target = new CustomAuthenticationProvider(() => Task.FromResult(header), () => Task.FromResult(value));

// Act
await target.AuthenticateRequestAsync(request);

// Assert
Assert.True(request.Headers.Contains(header));
Assert.Equal(request.Headers.GetValues(header).FirstOrDefault(), value);
}
}