Git Product home page Git Product logo

microsoft-identity-abstractions-for-dotnet's Introduction

CI

Microsoft.Identity.Abstractions

Microsoft.Identity.Abstractions contain interfaces and POCO classes used in the Microsoft .NET authentication libraries (Microsoft.IdentityModel, MSAL.NET and Microsoft.Identity.Web). It exposes concepts in three domains:

  1. Application options and credentials loader

    The application options are typically the options that you find in configuration files like the appsettings.json file. They describe the authentication aspects of your application. The library offers two layer. A standard layer, and a Microsoft Identity platform specialization.

    image

    An important part of the application options are the credentials. In addition to the credential descriptions, the library offers extensibility mechanisms so that implementers can add their own credential source loaders.

    image

    There can be several application options with different names (for instance in ASP.NET Core these would be different authentication schemes)

  2. Acquire tokens from Azure AD

    Once configured, an application can acquire tokens from the Identity provider. This is a low level API, in the sense that you would probably prefer to call downstream web APIs without having to be preoccupied about the authentication aspects. If you really want to use the lower level API, you should:

    • get hold of a ITokenAcquirerFactory. Implementations can provide a TokenAcquirerFactory for instance, with a singleton.
    • get a ITokenAcquirer (by its name, for instance). This corresponds to the application options
    • From the token acquirer get a token for on behalf of the user, or the app. If you don't specify any AcquireTokenOptions, the implementation should do its best effort. The AcquireTokenOptions enable you to override the defaults.

    image

  3. Calling downstream web APIs

    It's also possible (and recommended) to use higher level APIs:

    • IDownstreamApi enables you to call a downstream web API and let the implementation handle the serialization of the input parameter (if any), handling the getting the authorization header and attaching it to the HttpClient, call the downstream web API, handle errors, deserialize the answer and return it as a strongly typed object. You can use customize all these steps, for instance by providing your own serializer / deserializer.
    • IAuthorizationHeaderProvider is the component that provides the authorization header, delegating to the ITokenAcquirer. Whereas ITokenAcquirer only knows about tokens, IAuthorizationHeaderProvider knows about protocols (for instance bearer, Pop, etc ...)

    image

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.

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. For more information see the Code of Conduct FAQ or contact [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. 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.

microsoft-identity-abstractions-for-dotnet's People

Contributors

brentschmaltz avatar jennyf19 avatar jmprieur avatar joshlozensky avatar kellyyangsong avatar localden avatar microsoft-github-operations[bot] avatar microsoftopensource avatar sruke avatar trwalke avatar westin-m avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

localden

microsoft-identity-abstractions-for-dotnet's Issues

[Bug] Improve the serializability of DownstreamApiOptions

Which version of Microsoft Identity Abstractions for dotnet are you using?
4.1.0

Is this a new or an existing app?
This is an app that I'm trying to compile with AoT

Repro

<Project Sdk="Microsoft.NET.Sdk">
	<PropertyGroup>
		<OutputType>Exe</OutputType>
		<TargetFramework>net8.0</TargetFramework>
		<ImplicitUsings>enable</ImplicitUsings>
		<Nullable>enable</Nullable>
		<PublishAot>true</PublishAot>
		<InvariantGlobalization>true</InvariantGlobalization>
		<EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
		<LangVersion>latest</LangVersion>
		<Features>InterceptorsPreview</Features>
		<AdditionalCompilerArguments>-outputgeneratedcode:GeneratedCode</AdditionalCompilerArguments>
	</PropertyGroup>

	<ItemGroup>
	  <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.0-rc.1.23419.4" />
	  <PackageReference Include="Microsoft.Identity.Abstractions" Version="4.1.0" />
	</ItemGroup>

</Project>

And the code:

#pragma warning disable SYSLIB1100 // Did not generate binding logic for a type
#pragma warning disable SYSLIB1101 // Did not generate binding logic for a property on a type
            builder.Configuration.GetSection("DownstreamApi").Bind(downstreamApiOptions);
#pragma warning restore SYSLIB1101 // Did not generate binding logic for a property on a type
#pragma warning restore SYSLIB1100 // Did not generate binding logic for a type
            downstreamApiOptions.HttpMethod = HttpMethod.Parse(builder.Configuration.GetSection("DownstreamApi")["HttpMethod"]);

Expected behavior
No issues. The code generator can produce the binding on .NET 8 (we won't even try on lower versions of .NET, as we don't want to force a new dependency for these)

Actual behavior
The following properties issue warnings

  • Method (System.Net.HttpMethod), is not bound/de-serialized.
  • Serializer, Deserializer, CustomizeHttpRequestMessage should not be serializable (they are code-only configuration). Add a JsonIgnore attribute.

Possible solution

  • Direct the serialization better with attribute and a type converter

[Bug] Reference documentation: wrong reference to code snippets

Which version of Microsoft Identity Abstractions for dotnet are you using?
5.1.0

In the ManagedIdentity member of AcquireTokenOptions, there is this content:

<format type="text/markdown"><![CDATA[
            The Json fragment below describes how to use a system-assigned Managed Identity for authentication in a confidential client application :
            :::code language="json" source="~/../abstractions-samples/test/Microsoft.Identity.Abstractions.Tests/AquireTokenOptions.cs" id="managedidentitysystem_json":::
            
            The code below describes the same, programmatically in C#.
            :::code language="csharp" source="~/../abstractions-samples/test/Microsoft.Identity.Abstractions.Tests/AquireTokenOptions.cs" id="managedidentitysystem_csharp":::
            
            The Json fragment below describes how to use a user-assigned Managed Identity for authentication in a confidential client application :
            :::code language="json" source="~/../abstractions-samples/test/Microsoft.Identity.Abstractions.Tests/AquireTokenOptions.cs" id="managedidentityuser_json":::
            
            The code below describes the same, programmatically in C#.
            :::code language="csharp" source="~/../abstractions-samples/test/Microsoft.Identity.Abstractions.Tests/AquireTokenOptions.cs" id="managedidentityuser_csharp":::
            ]]></format>

However the file is not AquireTokenOptions.cs, it's AquireTokenOptionsTests.cs

[Feature Request] Address API review feedback

  1. Remove this override of ITokenAcquirerFactory.GetTokenAcquirer():

    ITokenAcquirer GetTokenAcquirer(string authority, string clientId, IEnumerable<CredentialDescription> clientCredentials, string? region);

  2. Rename:

    • ApplicationAuthenticationOptions to IdentityApplicationOptions,
    • and MicrosoftAuthenticationOptions to MicrosoftIdentityApplicationOptions
  3. Remove HasClientCredentials in ApplicationAuthenticationOptions / IdentityApplicationOptions

Add support for managed identities.

The downstream library Microsoft.Identity.Web needs additional information in these abstractions in order to support user-assigned/system-assigned managed identities see the correlated Identity.Web issue #1775 for more details.

To do this we can:

  • Create a new ManagedIdentityOptions class to hold necessary information like the Client ID of a user-assigned identity.
  • Add a ManagedIdentity property to the AcquireTokenOptions class in order to hold an instance of ManagedIdentityOptions.

[Bug] CertificateDescription from path with passwords reads the password for both the path and the password

What?
Having this JSON content

"ClientCredentials": [
            {
                "SourceType": "Path",
                "CertificateDiskPath": "C:\\myCert.pfx",
                "CertificatePassword": "something here"
            }

and then reading the certificate description, this will read "something here" for both the CertificateDiskPath and CertificatePassword

Analysis?
This is because of the Container/ReferenceOrValue calculated properties that are not consistent with each other in this case

Suggestion
Write the unit test for these as well (even if they are only used for testing)

[Feature Request] Add Unreferenced Code Attributes to address Trim Warnings

Is your feature request related to a problem? Please describe.
Because the implementations of the Downstream Api methods rely on generic types (and often reflection), warnings for these methods will always have trim warnings.

Describe the solution you'd like
Apply RequiresUnreferencedCode attributes to the methods whose implementations are trim-unfriendly.

[Feature Request] Consider add the docfx-console NuGet package to previsualize the reference documentation

Alongside the descriptions, we’re also able to include example code snippets. For enhanced rendering, the platform also allows us to include markdown content in the triple slash comments. Here’s a good example for ML.NET API ref:· 
 - Source: machinelearning/ValueMapping.cs at main · dotnet/machinelearning (github.com) · 
 - Rendered file - ValueMappingEstimator Class (Microsoft.ML.Transforms) | Microsoft Learn 

 Notice how in the above ML.NET ref, we have example snippets, member/type descriptions, and even markdown content (you’d usually put this in a wiki) all surfacing in the autogenerated library reference.

[Feature Request] Microsoft.Identity.Abstractions should bring a net462 target framework

Is your feature request related to a problem? Please describe.
When net462 libraries (think Id.Web, SAL) take a dependency on netstandard2.0 libraries, this ends-up pulling the whole framework, whereas Microsoft.Identity.Abstractions is tiny and does not reference much. By adding direct support for net462, this enables to draw less dependencies

Describe the solution you'd like
Add the net462 target framework

Describe alternatives you've considered
None

Additional context
See also the common dependency management.

[Bug] Unable to send a POST request using the low level CallApiForUserAsync

Which version of Microsoft Identity Abstractions for dotnet are you using?
Note that to get help, you need to run the latest version.
Microsoft Identity Abstractions 7.0.2

Is this a new or an existing app?
This is a new app using IDownstreamApi from a client to communicate with a downstream api

            var downstreamApiOptions = new Action<DownstreamApiOptions>(
                options =>
                {
                    options.HttpMethod = HttpMethod.Post;
                    options.BaseUrl = baseUrl;
                    options.RelativePath = relativePath;
                });
           
            // This is a Stream passed to the client
            var inputContent = new StreamContent(fileToUpload);

            inputContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                DispositionType = "form-data",
                FileName = fileName,
                Size = fileToUpload.Length
            };

            inputContent.Headers.ContentType =
                MediaTypeHeaderValue.Parse(SharePointFileManagementConstants.MimeResponseApplicationOctetStream);
            inputContent.Headers.ContentLength = fileToUpload.Length;

            var multipartFormDataContent = new MultipartFormDataContent {{inputContent, fileName, fileName}};

            var responseMessage = await _downstreamApi.CallApiForUserAsync(SiteServiceName,
                downstreamApiOptions,
                null,
                multipartFormDataContent
            );

Expected behavior
There should be a call to the downstream api using the POST HTTP method

Actual behavior
An exception is thrown when the client tries to send the request downstream:
Method not found: 'Void Microsoft.Identity.Abstractions.AuthorizationHeaderProviderOptions.set_HttpMethod(System.Net.Http.HttpMethod)'.

[Feature Request] Support a credential description for auto decrypt keys

Be able to support the following configuration:

            {
                "TokenDecryptionCredentials": [
                {
                    "SourceType": "AutoDecryptKeys",
                    "DecryptKeysApplicationTenant": "mytenant.onmicrosoftonline.com"
                    "DecryptKeysProtocol" : "bearer"
                }]
            }

This credential does not affect the container or ReferenceOrValue properties which should not be set and should return null for the soruce type "AutoDecryptKeys".

[Bug] [DownstreamApiOptions should be readable entierely from the configuration

Which version of Microsoft Identity Abstractions for dotnet are you using?
4.1.0

Repro

DownstreamApiOptions downstreamApiOptions = new DownstreamApiOptions();
builder.Configuration.GetSection("DownstreamApi").Bind(downstreamApiOptions);

Expected behavior
no exception thrown, and the properties can be read from the configuration.

Actual behavior

  1. Exceptions are thrown if the "ProtocolScheme" is not set in the configuration
  2. The HttpMethod property cannot be read from the configuration (there is no converter from string to HttpMethod)

Possible solution

  1. Change the HttpMethod property to be a string, instead of an HttpMethod (same for the backing field _httpMethod). This will be a breaking change (people will have to change their code to use httpMethod.ToString(), for instance HttpMethod.Post.ToString(). This impacts the public API:

    • AuthorizationHeaderProviderOptions.HttpMethod, AuthorizationHeaderProviderOptions._httpMethod which need to move to be a string
    • DownstreamApiOptionsReadOnlyHttpMethod(DownstreamApiOptions options, HttpMethod httpMethod) (the last parameter needs to be a string)
    • DownstreamApiOptionsReadOnlyHttpMethod.HttpMethod that needs to be a string too.
    • the tests (lines such as options.HttpMethod = HttpMethod.Patch; becomes options.HttpMethod = HttpMethod.Patch.ToString();)
  2. Remove the throw new ArgumentNullException in the properties that have a default value (ProtocolScheme that should return "Get", HttpMethod, that should return "Get"). Setting them to null (that is not setting them in the configuration), sets them to their default value.

    DefaultValue("Bearer")]
    public string ProtocolScheme
    {
     get
     {
      return _protocolScheme;
     }
     set
     {
    -  _protocolScheme = string.IsNullOrEmpty(value) ? throw new ArgumentNullException(_protocolScheme) : value;
    + _protocolScheme = string.IsNullOrEmpty(value) ? "Bearer" : value;
      }
    }

    This impacts tests as assigning null to these properties won't throw any longer (they will get a default value)

[Documentation] Release notes for 3.x releases

Documentation related to component

General

Please check all that apply

  • typo
  • documentation doesn't exist
  • documentation needs clarification
  • error(s) in the example
  • needs an example

Description of the issue

New 3.x releases are created but it's hard to understand what breaking changes it include and how to migrate.

Additionally, no new GitHub releases are created after 2.1.0

[Feature Request] Address API review discussion for IDownstreamRestApi

Is your feature request related to a problem? Please describe.

Level to make the API easier to understand.

DownstreamRestApiOptions

  • repetition of scopes
  • repetition of HttpVerb
  • Generic for Apps
  • delete
  • update

Serialization:

  • delegate for serialization
  • delegate for de-serialization

[Bug] Cannot resolve scoped service when Debug via Visual Studio on Windows - Works using Linux Container

Which version of Microsoft Identity Abstractions for dotnet are you using?
Microsoft Identity Abstractions version 5.3.0 via Microsoft.Identity.Web.DownstreamApi version 2.18.1

Is this a new or an existing app?
New app

Repro

Debug an ASP.NET 8.0 application using multiple IDP's and Azure Web PubSub.

// IDP 1
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("EntraExternalID"))
                .EnableTokenAcquisitionToCallDownstreamApi()
                .AddDownstreamApi("ServiceA", builder.Configuration.GetSection("ServiceA"))
                .AddDownstreamApi("ServiceB", builder.Configuration.GetSection("ServiceB"))
                .AddInMemoryTokenCaches();

// IDP 2
builder.Services.AddAuthentication().AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("EntraID"), "EntraID");

// Add Web PubSub Service Client
builder.Services.AddWebPubSub(options =>
{
    var config = builder.Configuration.GetSection("Config").Get<Configuration<Config>>();
    options.ServiceEndpoint = new WebPubSubServiceEndpoint(config.ConnectionString);
}).AddWebPubSubServiceClient<webpubsub>();

// standard init in between e.g. var app = builder.Build();

// Further down map web pubsub event handler
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapWebPubSubHub<webpubsub>("/eventhandler/{*path}");
app.Run();

Expected behavior
Error is not observed when debugging on Windows via Visual Studio.

Actual behavior
The call to app.MapWebPubSubHub<webpubsub>("/eventhandler/{*path}"); triggers System.InvalidOperationException: 'Cannot resolve scoped service 'Microsoft.Identity.Abstractions.IDownstreamApi' from root provider.' only when debugging via Visual Studio (latest version - 17.9.6) on Windows. When run in a Linux Container the app runs fine.

Possible solution
N/A

[Feature Request] AcquireTokenResult should have a property TokenType.

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...].
The OAuth 2.0 specification requires TokenType (https://www.rfc-editor.org/rfc/rfc6749#section-7.1) this should be a first class property.

see:

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

[Feature Request] Replace 'JwtClaim' with 'PopClaim' on AquireTokenOptions

Is your feature request related to a problem? Please describe.
Property name JwtClaim is specific to Json Web Tokens (JWT).

Describe the solution you'd like
The intent of the claim is providing proof-of-possession. By renaming the property to PopClaim, it can also be applied to other token types.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.