Skip to content

Commit

Permalink
Step 2: add azure library source
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew Omondi committed Jul 5, 2024
1 parent 83d6bc6 commit 7dbfc4b
Show file tree
Hide file tree
Showing 11 changed files with 436 additions and 11 deletions.
27 changes: 18 additions & 9 deletions Microsoft.Kiota.sln
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,40 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
SUPPORT.md = SUPPORT.md
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Kiota.Abstractions", "src\abstractions\Microsoft.Kiota.Abstractions.csproj", "{7D843C30-B856-49BD-97BC-B74F9F234EF9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Kiota.Abstractions.Tests", "tests\abstractions\Microsoft.Kiota.Abstractions.Tests.csproj", "{B112E9CF-055E-45FB-A32F-25CAB57936DB}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Kiota.Abstractions", "src\abstractions\Microsoft.Kiota.Abstractions.csproj", "{61B7F639-6456-41CA-B53E-492115888F84}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Kiota.Authentication.Azure", "src\authentication\azure\Microsoft.Kiota.Authentication.Azure.csproj", "{ED943ED1-CC3E-41B9-BE79-C3C301D2267B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Kiota.Authentication.Azure.Tests", "tests\authentication\azure\Microsoft.Kiota.Authentication.Azure.Tests.csproj", "{71161CE4-C748-4CD3-A5ED-A2B806B24360}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7D843C30-B856-49BD-97BC-B74F9F234EF9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7D843C30-B856-49BD-97BC-B74F9F234EF9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7D843C30-B856-49BD-97BC-B74F9F234EF9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7D843C30-B856-49BD-97BC-B74F9F234EF9}.Release|Any CPU.Build.0 = Release|Any CPU
{B112E9CF-055E-45FB-A32F-25CAB57936DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B112E9CF-055E-45FB-A32F-25CAB57936DB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B112E9CF-055E-45FB-A32F-25CAB57936DB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B112E9CF-055E-45FB-A32F-25CAB57936DB}.Release|Any CPU.Build.0 = Release|Any CPU
{61B7F639-6456-41CA-B53E-492115888F84}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{61B7F639-6456-41CA-B53E-492115888F84}.Debug|Any CPU.Build.0 = Debug|Any CPU
{61B7F639-6456-41CA-B53E-492115888F84}.Release|Any CPU.ActiveCfg = Release|Any CPU
{61B7F639-6456-41CA-B53E-492115888F84}.Release|Any CPU.Build.0 = Release|Any CPU
{ED943ED1-CC3E-41B9-BE79-C3C301D2267B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ED943ED1-CC3E-41B9-BE79-C3C301D2267B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ED943ED1-CC3E-41B9-BE79-C3C301D2267B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ED943ED1-CC3E-41B9-BE79-C3C301D2267B}.Release|Any CPU.Build.0 = Release|Any CPU
{71161CE4-C748-4CD3-A5ED-A2B806B24360}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{71161CE4-C748-4CD3-A5ED-A2B806B24360}.Debug|Any CPU.Build.0 = Debug|Any CPU
{71161CE4-C748-4CD3-A5ED-A2B806B24360}.Release|Any CPU.ActiveCfg = Release|Any CPU
{71161CE4-C748-4CD3-A5ED-A2B806B24360}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{7D843C30-B856-49BD-97BC-B74F9F234EF9} = {812D9C21-411D-4987-AB8E-C96185F01AD0}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B0E38E50-7BC8-4E28-BDAC-BF38F7AF2CD2}
EndGlobalSection
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Read more about Kiota [here](https://github.com/microsoft/kiota/blob/main/README
## Libraries

1. [Abstractions](./src/abstractions/README.md)
1. [Authentication - Azure](./src/authentication/azure/README.md)

## Debugging

Expand Down
4 changes: 2 additions & 2 deletions src/abstractions/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Read more about Kiota [here](https://github.com/microsoft/kiota/blob/main/README
## Using the Abstractions Library

```shell
dotnet add package Microsoft.Kiota.Abstractions --prerelease
dotnet add package Microsoft.Kiota.Abstractions
```

## Debugging
Expand All @@ -38,4 +38,4 @@ This project may contain trademarks or logos for projects, products, or services
trademarks or logos is subject to and must follow
[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general).
Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.
Any use of third-party trademarks or logos are subject to those third-party's policies.
Any use of third-party trademarks or logos are subject to those third-party's policies.
Binary file added src/authentication/azure/35MSSharedLib1024.snk
Binary file not shown.
103 changes: 103 additions & 0 deletions src/authentication/azure/AzureIdentityAccessTokenProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Microsoft.Kiota.Abstractions.Authentication;

namespace Microsoft.Kiota.Authentication.Azure;
/// <summary>
/// Provides an implementation of <see cref="IAccessTokenProvider"/> for Azure.Identity.
/// </summary>
public class AzureIdentityAccessTokenProvider : IAccessTokenProvider, IDisposable
{
private static readonly object BoxedTrue = true;
private static readonly object BoxedFalse = false;

private readonly TokenCredential _credential;
private readonly ActivitySource _activitySource;
private readonly HashSet<string> _scopes;
/// <inheritdoc />
public AllowedHostsValidator AllowedHostsValidator { get; protected set; }

/// <summary>
/// The <see cref="AzureIdentityAccessTokenProvider"/> constructor
/// </summary>
/// <param name="credential">The credential implementation to use to obtain the access token.</param>
/// <param name="allowedHosts">The list of allowed hosts for which to request access tokens.</param>
/// <param name="scopes">The scopes to request the access token for.</param>
/// <param name="observabilityOptions">The observability options to use for the authentication provider.</param>
public AzureIdentityAccessTokenProvider(TokenCredential credential, string []? allowedHosts = null, ObservabilityOptions? observabilityOptions = null, params string[] scopes)
{
_credential = credential ?? throw new ArgumentNullException(nameof(credential));

AllowedHostsValidator = new AllowedHostsValidator(allowedHosts);

if(scopes == null)
_scopes = new();
else
_scopes = new(scopes, StringComparer.OrdinalIgnoreCase);

_activitySource = new((observabilityOptions ?? new()).TracerInstrumentationName);
}

private const string ClaimsKey = "claims";

private readonly HashSet<string> _localHostStrings = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"localhost",
"[::1]",
"::1",
"127.0.0.1"
};

/// <inheritdoc/>
public async Task<string> GetAuthorizationTokenAsync(Uri uri, Dictionary<string, object>? additionalAuthenticationContext = default, CancellationToken cancellationToken = default)
{
using var span = _activitySource?.StartActivity(nameof(GetAuthorizationTokenAsync));
if(!AllowedHostsValidator.IsUrlHostValid(uri)) {
span?.SetTag("com.microsoft.kiota.authentication.is_url_valid", BoxedFalse);
return string.Empty;
}

if(!uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) && !_localHostStrings.Contains(uri.Host)) {
span?.SetTag("com.microsoft.kiota.authentication.is_url_valid", BoxedFalse);
throw new ArgumentException("Only https is supported");
}
span?.SetTag("com.microsoft.kiota.authentication.is_url_valid", BoxedTrue);

string? decodedClaim = null;
if (additionalAuthenticationContext is not null &&
additionalAuthenticationContext.ContainsKey(ClaimsKey) &&
additionalAuthenticationContext[ClaimsKey] is string claims) {
span?.SetTag("com.microsoft.kiota.authentication.additional_claims_provided", BoxedTrue);
var decodedBase64Bytes = Convert.FromBase64String(claims);
decodedClaim = Encoding.UTF8.GetString(decodedBase64Bytes);
} else
span?.SetTag("com.microsoft.kiota.authentication.additional_claims_provided", BoxedFalse);

string[] scopes;
if (_scopes.Count > 0) {
scopes = new string[_scopes.Count];
_scopes.CopyTo(scopes);
} else
scopes = [ $"{uri.Scheme}://{uri.Host}/.default" ];
span?.SetTag("com.microsoft.kiota.authentication.scopes", string.Join(",", scopes));

var result = await _credential.GetTokenAsync(new TokenRequestContext(scopes, claims: decodedClaim), cancellationToken).ConfigureAwait(false);
return result.Token;
}

/// <inheritdoc/>
public void Dispose()
{
_activitySource?.Dispose();
GC.SuppressFinalize(this);
}
}
25 changes: 25 additions & 0 deletions src/authentication/azure/AzureIdentityAuthenticationProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------

using Azure.Core;
using Microsoft.Kiota.Abstractions.Authentication;

namespace Microsoft.Kiota.Authentication.Azure;
/// <summary>
/// The <see cref="BaseBearerTokenAuthenticationProvider"/> implementation that supports implementations of <see cref="TokenCredential"/> from Azure.Identity.
/// </summary>
public class AzureIdentityAuthenticationProvider : BaseBearerTokenAuthenticationProvider
{
/// <summary>
/// The <see cref="AzureIdentityAuthenticationProvider"/> constructor
/// </summary>
/// <param name="credential">The credential implementation to use to obtain the access token.</param>
/// <param name="allowedHosts">The list of allowed hosts for which to request access tokens.</param>
/// <param name="scopes">The scopes to request the access token for.</param>
/// <param name="observabilityOptions">The observability options to use for the authentication provider.</param>
public AzureIdentityAuthenticationProvider(TokenCredential credential, string[]? allowedHosts = null, ObservabilityOptions? observabilityOptions = null, params string[] scopes)
: base(new AzureIdentityAccessTokenProvider(credential, allowedHosts, observabilityOptions, scopes))
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<Project Sdk="Microsoft.NET.Sdk">
<Sdk Name="Microsoft.DotNet.PackageValidation" Version="1.0.0-preview.7.21379.12" />

<PropertyGroup>
<Description>Kiota authentication provider implementation with Azure Identity.</Description>
<Copyright>© Microsoft Corporation. All rights reserved.</Copyright>
<AssemblyTitle>Kiota Azure Identity Authentication Library for dotnet</AssemblyTitle>
<Authors>Microsoft</Authors>
<!-- NET 5 target to be removed on next major version-->
<TargetFrameworks>netstandard2.0;netstandard2.1;net5.0;net6.0;net8.0</TargetFrameworks>
<LangVersion>latest</LangVersion>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<PackageIconUrl>http://go.microsoft.com/fwlink/?LinkID=288890</PackageIconUrl>
<RepositoryUrl>https://github.com/microsoft/kiota-authentication-azure-dotnet</RepositoryUrl>
<PackageProjectUrl>https://aka.ms/kiota/docs</PackageProjectUrl>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<Deterministic>true</Deterministic>
<VersionPrefix>1.1.7</VersionPrefix>
<VersionSuffix></VersionSuffix>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<!-- Enable this line once we go live to prevent breaking changes -->
<!-- <PackageValidationBaselineVersion>1.0.0</PackageValidationBaselineVersion> -->
<SignAssembly>false</SignAssembly>
<DelaySign>false</DelaySign>
<AssemblyOriginatorKeyFile>35MSSharedLib1024.snk</AssemblyOriginatorKeyFile>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<PackageReleaseNotes>
https://github.com/microsoft/kiota-authentication-azure-dotnet/releases
</PackageReleaseNotes>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageReadmeFile>README.md</PackageReadmeFile>
<NoWarn>$(NoWarn);NU5048;NETSDK1138</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)','net5.0'))">
<IsTrimmable>true</IsTrimmable>
</PropertyGroup>
<PropertyGroup Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)','net8.0'))">
<IsAotCompatible>true</IsAotCompatible>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
<PackageReference Include="Azure.Core" Version="1.39.0" />
<ProjectReference Include="..\..\abstractions\Microsoft.Kiota.Abstractions.csproj" />
</ItemGroup>

<!-- NET 5 target to be removed on next major version-->
<ItemGroup Condition="'$(TargetFramework)' == 'net5.0' or '$(TargetFramework)'== 'netStandard2.0' or '$(TargetFramework)' == 'netStandard2.1'">
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="[6.0.1,9.0)" />
</ItemGroup>

<PropertyGroup Condition="'$(TF_BUILD)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>

<ItemGroup>
<None Include="README.md">
<Pack>True</Pack>
<PackagePath></PackagePath>
</None>
</ItemGroup>

</Project>
17 changes: 17 additions & 0 deletions src/authentication/azure/ObservabilityOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------

using System;

namespace Microsoft.Kiota.Authentication.Azure;
/// <summary>
/// Holds the tracing, metrics and logging configuration for the authentication provider
/// </summary>
public class ObservabilityOptions {
private static readonly Lazy<string> _name = new Lazy<string>(() => typeof(ObservabilityOptions).Namespace!);
/// <summary>
/// Gets the observability name to use for the tracer
/// </summary>
public string TracerInstrumentationName => _name.Value;
}
41 changes: 41 additions & 0 deletions src/authentication/azure/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Kiota Azure Identity authentication provider library for dotnet

[![Build and Test](https://github.com/microsoft/kiota-authentication-azure-dotnet/actions/workflows/build-and-test.yml/badge.svg?branch=main)](https://github.com/microsoft/kiota-authentication-azure-dotnet/actions/workflows/build-and-test.yml) [![NuGet Version](https://buildstats.info/nuget/Microsoft.Kiota.Authentication.Azure?includePreReleases=true)](https://www.nuget.org/packages/Microsoft.Kiota.Authentication.Azure/)

The Kiota Azure Identity authentication provider library for dotnet is the authentication provider implementation with [Azure.Identity](https://docs.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme).

A [Kiota](https://github.com/microsoft/kiota) generated project will need a reference to a authentication provider library to authenticate HTTP requests to an API endpoint.

Read more about Kiota [here](https://github.com/microsoft/kiota/blob/main/README.md).

## Using Azure Identity authentication provider library for dotnet

```shell
dotnet add package Microsoft.Kiota.Authentication.Azure
```

## Debugging

If you are using Visual Studio Code as your IDE, the **launch.json** file already contains the configuration to build and test the library. Otherwise, you can open the **Microsoft.Kiota.Authentication.Azure.sln** with Visual Studio.

## Contributing

This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit [https://cla.opensource.microsoft.com](https://cla.opensource.microsoft.com).

When you submit a pull request, a CLA bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [[email protected]](mailto:[email protected]) with any additional questions or comments.

## Trademarks

This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft
trademarks or logos is subject to and must follow
[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/legal/intellectualproperty/trademarks/usage/general).
Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.
Any use of third-party trademarks or logos are subject to those third-party's policies.
Loading

0 comments on commit 7dbfc4b

Please sign in to comment.