-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Andrew Omondi
committed
Jul 5, 2024
1 parent
83d6bc6
commit 7dbfc4b
Showing
11 changed files
with
436 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Binary file not shown.
103 changes: 103 additions & 0 deletions
103
src/authentication/azure/AzureIdentityAccessTokenProvider.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
25
src/authentication/azure/AzureIdentityAuthenticationProvider.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | ||
{ | ||
} | ||
} |
67 changes: 67 additions & 0 deletions
67
src/authentication/azure/Microsoft.Kiota.Authentication.Azure.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
Oops, something went wrong.