Giter VIP home page Giter VIP logo

active-directory-dotnetcore-daemon-v2's Introduction

page_type languages products description urlFragment
sample
csharp
powershell
microsoft-entra-id
Daemon or unattended application consuming Microsoft Graph or your own Web Apis using Microsoft Identity Platform to acquire tokens.
ms-identity-daemon

A .NET Core daemon console application using MSAL.NET to acquire tokens for resources

Build status

About this sample

This sample uses Microsoft.Identity.Web, which is a higher level API on top of MSAL.NET. If you are interested in the raw MSAL.NET code, see this archived branch

Scenario

In these scenarios we show how unattended daemon applications can authenticate as itself using the Microsoft Authentication Library for .NET (MSAL.NET) SDK and acquire Access Tokens for various web APIs like Microsoft Graph or any other API secured with the Microsoft Identity Platform

Structure of the repository

This repository contains a chapter-wise tutorial made of three parts:

Sub folder Description
1-Call-Graph This sample application shows how to use the Microsoft Authentication Library for .NET (MSAL.NET) to access the data of Microsoft business customers in a long-running, non-interactive process. It uses the OAuth 2 client credentials grantto acquire an access token, which can be used to call the Microsoft Graph and access organizational data

Topology
2-Call-OwnApi This sample application shows how to use the Microsoft Authentication Library for .NET (MSAL.NET) to access the data from a protected Web API, in a non-interactive process. It uses the OAuth 2 client credentials grant to acquire an access token, which is then used to call the Web API. Additionally, it lays down all the steps developers need to take to secure their Web APIs with the Microsoft identity platform.

Topology
3-Using-KeyVault This chapter explains how to integrate Azure Key Vault and Managed Identities for Azure Resources with a daemon application. Additionally, it has a code snippet on how to get an access token for Key Vault.

How to run this sample

To run this sample, you'll need:

  • Visual Studio and the .NET Core SDK
  • An Internet connection
  • A Windows machine (necessary if you want to run the app on Windows)
  • An OS X machine (necessary if you want to run the app on Mac)
  • A Linux machine (necessary if you want to run the app on Linux)
  • a Microsoft Entra tenant. For more information on how to get a Microsoft Entra tenant, see How to get a Microsoft Entra tenant
  • A user account in your Microsoft Entra tenant. This sample will not work with a Microsoft account (formerly Windows Live account). Therefore, if you signed in to the Microsoft Entra admin center with a Microsoft account and have never created a user account in your directory before, you need to do that now.

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2.git

or download and exact the repository .zip file.

Given that the name of the sample is pretty long, and so are the name of the referenced NuGet packages, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.

Community Help and Support

Use Stack Overflow to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [msal dotnet].

If you find a bug in the sample, please raise the issue on GitHub Issues.

If you find a bug in msal.Net, please raise the issue on MSAL.NET GitHub Issues.

To provide a recommendation, visit the following User Voice page.

Consider taking a moment to share your experience with us.

Contributing

If you'd like to contribute to this sample, see CONTRIBUTING.MD.

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.

More information

For more information, see MSAL.NET's conceptual documentation:

For more information about the underlying protocol:

For a more complex multi-tenant Web app daemon application, see active-directory-dotnet-daemon-v2

active-directory-dotnetcore-daemon-v2's People

Contributors

aiwangmicrosoft avatar andretms avatar archieag avatar aremo-ms avatar balcsok avatar bgavrilms avatar coxantohi avatar dependabot[bot] avatar didunayodeji avatar henrik-me avatar jennyf19 avatar jmprieur avatar joshlozensky avatar kalyankrishna1 avatar kellyyangsong avatar markzuber avatar microsoftopensource avatar mike-f50 avatar msftgits avatar pmaytak avatar pramodkumarhk89 avatar ramya25 avatar rwike77 avatar shama-k avatar supernova-eng avatar trwalke avatar v-hearya avatar v-michaelmi avatar vhellin avatar westin-m avatar

Stargazers

 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

active-directory-dotnetcore-daemon-v2's Issues

Usage of Todolist service without "roles" claim

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [x] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

In TodoList controller add another method, but without Policy or roles

I am following the instructions in 2-Call-OwnApi. If I want to register another client app in Azure, but do not grant any Application permissions (roles). The token that will be issued will not have roles claim - which is OK. When the client tries to access an endpoint (method) from TodoList service, that doesn't require roles or policy, the response is "Neither scope or roles claim was found in the bearer token.".

// note that there is no [Roles or Policy] required.
[HttpGet("Categories")]
public IActionResult CategoriesForTodos()
{
    // Cannot access the endpoint if none of "scp", "scope", "role", "role" claims present in the token.
    // If all are missing - error.
    
    // related categories to that application in Azure.
    return Ok(new[] { "category1", "category2" });
}

Any log messages given by the failure

System.UnauthorizedAccessException: Neither scope or roles claim was found in the bearer token.
at Microsoft.Identity.Web.WebApiAuthenticationBuilderExtensions.<>c__DisplayClass1_1.<b__1>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Expected/desired behavior

Access the endpoint - 200 OK

OS and Version?

Windows 10.

Versions

VS2019

Mention any other details that might be useful

Is it necessary all tokens to have "roles" claim ? How to add a method that doesn't require role or polices.


Thanks! We'll be in touch soon.

AADSTS500011: Unable to acquire token in the console application

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Simply follow all configuration steps on both AD and the daemon application.

Any log messages given by the failure

AADSTS500011: The resource principal named api://abcdef-555-1111-2222-6666666 was not found in the tenant named {tenant name}. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.

Expected/desired behavior

This issue should not happen

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

AppCreationScript failed

This issue is for a: (mark with an x)

- [x ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

In Powershell run as admin:

Install-Module AzureAD

In Powershell:

Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
.\Configure.ps

Any log messages given by the failure

Connect-AzureAD: C:\Users\REDACTED\source\repos\active-directory-dotnetcore-daemon-v2-master\2-Call-OwnApi\AppCreationScripts\Configure.ps1:144
Line |
 144 |              $creds = Connect-AzureAD -Credential $Credential
     |                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | One or more errors occurred. (Could not load type 'System.Security.Cryptography.SHA256Cng' from assembly 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.): Could not load type 'System.Security.Cryptography.SHA256Cng' from assembly
     | 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

Expected/desired behavior

The app creation scripts succeeds in post-login behavior.

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

Windows 10

Versions

  • AzureAD 2.0.2.140

Mention any other details that might be useful

N/A

Project not working on .NET Core 3.1 and Microsoft.Identity.Web code seems outdated

Hello Azure-Samples Team,

Thanks for all the code samples provided.
I have used the code in this project for an an on-premise daemon app that needs to call a web api hosted in Azure and protected by Azure AD.

As .net core 2.2 is not supported anymore I have updated my project to Asp.Net Core 3.1 and it was broken afterwards. After searching I found that the project under https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2 hosts a quite different (and probably more up-to-date) version of the Microsoft.Identity.Web project.

Could you please confirm that the version under https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/master/Microsoft.Identity.Web is the one that should be used for any .net core project needing Azure Ad integration and that it is compatible with .net core 3.1?
Maybe this sample should also be updated for .NET Core 3.1?

I have also seen the request for providing Microsoft.Identity.Web as a nuget (Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2#69) : I think it is a very good idea and would prevent issues like this one.

Many thanks

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [ x] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Clone local project and upgrade web app https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2/tree/master/2-Call-OwnApi/TodoList-WebApi to asp.net core 3.1

Any log messages given by the failure

Error at runtime

Expected/desired behavior

N/A

OS and Version?

Windows 10

Versions

N/A

Is the PoP without server nonce still not recommended?

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [ x] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

I just have a question about the README on the daemon-console This sample corresponds to an implementation of PoP without server nonce that is no longer recommended

Any log messages given by the failure

Expected/desired behavior

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

Versions

Mention any other details that might be useful

I am wondering if this README which features this scary disclaimer at the top still accurate?

And if it is.. is it really bad for me to use this sample for my production scenario?


Thanks! We'll be in touch soon.

Token validation fails in the Web Api

Please provide us with the following information:

This issue is for a: (mark with an x)

- [X] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Have the daemon application generate a token and send it to the web API for validation. The reason for the failure is that AzureAd entry in the Web API's appsettings.json file lacks an Audience definition. Therefore it must be added to the appsettings.json file and the documentation updated accordingly.

Any log messages given by the failure

Authentication fails

Expected/desired behavior

This issue should not happen

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

HTTP Error 500.34 - ANCM Mixed Hosting Models Not Supported

Please provide us with the following information:

This issue is for a: (mark with an x)

- [x ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Trying to access the API from the Daemon results in a 500.34 error.

Any log messages given by the failure

Expected/desired behavior

OS and Version?

10

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

Reg: Creating GraphServiceClient with AuthenticationProvider

Hello Team,

We have developed windows based on ERP application, and Now we are integrating the one drive using the Graph SDK. Following is the way how the app works.

  1. Users can log in to the onedrive for the first time, then we are getting the access token and refresh tokens by calling the API endpoint.
  2. Once we have the access tokens, we are preparing the GraphServiceClient by passing the access token we have using code file attached in the data.
    Problem:
    Using the latest version of Graph SDK there are changed in the IPublicClientApplication, and it seems we need to pass the AuthenticationProviders to the GraphServiceClient. While calling the ".Me.Request().GetAsync().Result" application is getting struck. I am a little confused here to create the authentication providers so please help to get out of the issue.
    AuthenticationHelper.txt
    Thanks
    Chakradhar

Document Update - Own API manifest instructions to avoid HTTP 401 Unauthorized

Hello ๐Ÿ‘‹,I am requesting an update for 2-Call-OwnApi:

  • In the section Register the service app (TodoList-webapi-daemon-v2)
    • Step 7, Please indicate to update the value of accessTokenAcceptedVersion from null to 2:
    • image

Context

After following the current steps the daemon console gets an 401 Unauthorized error.

image

Output from console app:

image

Mismatch between the code and the documentation code snippets for the 2-Call-OwnApi solution

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [x] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

NA

Any log messages given by the failure

NA

Expected/desired behavior

NA

OS and Version?

NA

Versions

NA

Mention any other details that might be useful

The section TodoList Web API Code references code not being part of the project.
The Startup.cs file does not have calls made to AddAzureADBearer for example.
The documentation does not explain services.AddProtectedWebApi(Configuration).


Thanks! We'll be in touch soon.

Http GET returns 401 using the "2-Call-OwnApi" example

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [X ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

An exercise to understand MSAL flows (coming from ADAL).

Started with existing AAD app registrations (one for the c# console and one for the Web API that was created using ASP.NET last year) and modified them as needed as per the provided PowerShell setup script. Token is successfully obtained but Http GET returns 401 when calling the Web API.

I can use ADAL with a C# console App and it works fine. I can call the Web API (REST) via browser Url and interactive AAD login and it works fine.

Any log messages given by the failure

HttpResponseMessage response = await HttpClient.GetAsync(webApiUrl);
XXXXX to mask company specific values.
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
WWW-Authenticate: Bearer realm="XXXXXXX.azurewebsites.net" authorization_uri="https://login.microsoftonline.com/XXXXX/oauth2/authorize" resource_id="XXXXXXXX"
X-Powered-By: ASP.NET
Date: Thu, 07 May 2020 22:32:45 GMT
Content-Length: 58
Content-Type: text/html
}}

Expected/desired behavior

Successful GET to Web API.

OS and Version?

Windows 10 1903.

Versions

VS2019

Mention any other details that might be useful

Does Web API need to be refactored using NET Core for MSAL to work?


Thanks! We'll be in touch soon.

Possible to call Azure FHIR API using MSAL authentication process

I am using MSAL daemon server authentication mechanism to call FHIR API using example specified in below link,
https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2

I tried with sample application, able to retrieve access token using MSAL library but its giving forbidden error while calling FHIR API from daemon process, Is it possible to access FHIR API using daemon application?

image

Its mentioned in MSAL sample application that we need application permission in order to access API, let me know if it is possible to provide application permission for FHIR API from app registration, currently application permission for Azure Healthcare API is disabled and not able to add as shown in below image,

image

Code doesn't match documentation also not explained

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Any log messages given by the failure

Expected/desired behavior

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

Using tenantID and Secret fails with System.ArgumentException: 'authority' should be in URI format. (Parameter 'authority')

Please provide us with the following information:

This issue is for a: (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Set up azure portal for application enabled security
Build example, provide clientid, tenantid, secret in appsettings.json

Any log messages given by the failure

We could not retrieve the user's list: Status Code: 0
Microsoft.Graph.ServiceException: Code: generalException
Message: An error occurred sending the request.

---> System.ArgumentException: 'authority' should be in URI format. (Parameter 'authority')
at Microsoft.Identity.Client.AuthorityInfo.ValidateAndCreateAuthorityUri(String authority, Nullable1 authorityType) at Microsoft.Identity.Client.AuthorityInfo.FromAuthorityUri(String authorityUri, Boolean validateAuthority) at Microsoft.Identity.Client.Instance.Authority.CreateAuthority(String authority, Boolean validateAuthority) at Microsoft.Identity.Client.AbstractApplicationBuilder1.WithAuthority(String authorityUri, Boolean validateAuthority)
at Microsoft.Identity.Web.TokenAcquisition.BuildConfidentialClientApplication(MergedOptions mergedOptions)
at Microsoft.Identity.Web.TokenAcquisition.GetOrBuildConfidentialClientApplication(MergedOptions mergedOptions)
at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForAppAsync(String scope, String authenticationScheme, String tenant, TokenAcquisitionOptions tokenAcquisitionOptions)
at Microsoft.Identity.Web.DefaultAuthorizationHeaderProvider.CreateAuthorizationHeaderForAppAsync(String scopes, AuthorizationHeaderProviderOptions downstreamApiOptions, CancellationToken cancellationToken)
at Microsoft.Identity.Web.TokenAcquisitionAuthenticationProvider.AuthenticateRequestAsync(HttpRequestMessage request)
at Microsoft.Graph.AuthenticationHandler.SendAsync(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Microsoft.Graph.HttpProvider.SendRequestAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.Graph.HttpProvider.SendRequestAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.GraphServiceUsersCollectionRequest.GetAsync(CancellationToken cancellationToken)
at daemon_console.Program.Main(String[] _) in C:\Src\Calumet\active-directory-dotnetcore-daemon-v2-master\active-directory-dotnetcore-daemon-v2-master\1-Call-MSGraph\daemon-console\Program.cs:line 40

Expected/desired behavior

Connect and return a clean result

OS and Version?

Windows 10, VS 2022

Versions

Mention any other details that might be useful

Using another approach of POST to
"https://login.microsoftonline.com/XXXXXX-tenant-id-XXXX-XXXXXX/oauth2/v2.0/token";
works successfully, and i am able to query for groups using the token


Thanks! We'll be in touch soon.

use powershell RemoteSigned rather than Unrestricted

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [ X] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Following SDL the samples should not promote insecure configuration of Dev/Test systems.
in the provided sample powershell is configured for a rather insecure configuration.
While I do appreciate that the policy is scoped to the process, rather than the system , I would still like to argue that RemoteSigned is better suited, and unrestricted should be reserved for the cases where it is actually needed.
In those cases it should be explained why this is required.

Expected/desired behavior

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process

Mention any other details that might be useful


Thanks! We'll be in touch soon.

[6-Call-OwnApi - ManagedIdentity] Missing configuration issue with force to create app registration for deamon app

Hi I am trying to work with the 6-Call-OwnApi - ManagedIdentity example and implement something similar for our infrastructure. We have pipelined userAssigned managed identities and those Apis will be calling each other.

What I saw in the example there is no internal dependency for "AzureAD" configuration in appsetting.json file but when I investigated the internal code I saw that the TokenAcquirerFactory.GetDefaultInstance() functionality actually searches for that.

static public TokenAcquirerFactory GetDefaultInstance(string configSection = "AzureAd")
        {
            TokenAcquirerFactory instance;
            if (defaultInstance == null)
            {
                instance = new TokenAcquirerFactory();
                instance.ReadConfiguration();
                defaultInstance = instance;
                instance.Services.AddTokenAcquisition();
                instance.Services.AddHttpClient();
                instance.Services.Configure<MicrosoftIdentityApplicationOptions>(option =>
                {
                    instance.Configuration.GetSection(configSection).Bind(option);

                    // This is temporary and will be removed eventually.
                    CiamAuthorityHelper.BuildCiamAuthorityIfNeeded(option);
                });
                instance.Services.AddSingleton<ITokenAcquirerFactory, DefaultTokenAcquirerFactoryImplementation>();
                instance.Services.AddSingleton(defaultInstance.Configuration);
            }
            return defaultInstance!;
        }

When this configuration is missing I receive null exception from MergeOptions class. Because the instance is not set.

public void PrepareAuthorityInstanceForMsal()
        {
            if (IsB2C && Instance.EndsWith("/tfp/", StringComparison.OrdinalIgnoreCase))
            {
#if !NETSTANDARD2_0 && !NET462 && !NET472
                Instance = Instance.Replace("/tfp/", string.Empty, StringComparison.OrdinalIgnoreCase).TrimEnd('/') + "/";
#else
                Instance = Instance.Replace("/tfp/", string.Empty).TrimEnd('/') + "/";
#endif
            }
            else
            {
                Instance = Instance.TrimEnd('/') + "/";
            }
        }

Since I am using ManagedIdentity I tried to declare "AzureAD" without clientId but then I receive and error saying that there is no clientId. The problem is out clientIds are not registered in AppRegistration and created with a pipeline as user-assigned managed identities.

Is the example here outdated?

I tried different ways of registering this into the project but they are all failed.
I am preparing a public API with managed identity to call a secure API with AzureAD authentication. The configuration should be similar to this deamon example. Maybe requires different way of registering like below.

services.AddTokenAcquisition(isTokenAcquisitionSingleton: false)
 AddInMemoryTokenCaches()
 .AddHttpClient();
    
services.AddDownstreamApi("ManagedIdentityPocApi", configuration.GetSection("ManagedIdentityPocApi"));

The configuration above requires
services.Configure<MicrosoftIdentityApplicationOptions>(options => configuration.GetSection("AzureAd").Bind(options))
event if the managed identity is configured in appsettings.json

"ManagedIdentityPocApi": {
    "BaseUrl": "http://localhost:5226",
    "RequestAppToken": true,
    "Scopes": [
      "api://guid/.default"
    ],
    "AcquireTokenOptions": {
      "ManagedIdentity ": {
        "UserAssignedClientId ": "guid"
      }
    }
  }

I do not want to create app registration for the deamon app and do not want to create secret / certificate since I want to use managed identity to authenticate the app's access

Please demonstrate how to page through users on the daemon app that calls MS Graph sample

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ x] feature request
- [ x] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

run the code as is ( with your tenant and client information ).
If you have more than 100 users, it will not page. If you set the Top parameter to a small number, it will not page. Examples for paging ( and I have spent 3 hours trying all that I can find ) do not work. Thank you!

Any log messages given by the failure

Expected/desired behavior

OS and Version?

Windows 11

Versions

per the sample

Mention any other details that might be useful


Thanks! We'll be in touch soon.

AADSTS7000215: Invalid client secret is provided. For 1st party app

Hello team,
Thanks a lot for you excellent samples.
I want to use this sample that daemon app call MS Graph to test our 1st party app. But got invalid secret error.

How can I use my 1st party app to call MS graph?

Thanks a lot
Ashley

Please provide us with the following information:

This issue is for a: (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

The 1st party app was registered in this portal , and I provisioned it to my test tenant by creating service principal manually, and assign credentials to that that service principal via New-AzureADServicePrincipalPasswordCredential, and got something like this:
image
I used the 1st party app id and the value showed in the image to replace client id and secrets in appsettings.json.

Any log messages given by the failure

When run the code, got invalid secrets error:
image

Expected/desired behavior

Use 1st party app to call MS graph successfully.

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)
Win10

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

Error when running the sample

Please provide us with the following information:

This issue is for a: (mark with an x)

- [X ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Add settings and run example

Any log messages given by the failure

'authority' Uri should have at least one segment in the path (i.e. https:////...).

Expected/desired behavior

get a token

OS and Version?

Windows 10

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

What is the client secret??

I want to use the graph api to connect read/add to a users calendar in code with no user iteraction is this the right example????

System.InvalidOperationException : An invalid request URI was provided. Either the request URI must be an absolute URI or BaseAddress must be set.

System.InvalidOperationException : An invalid request URI was provided. Either the request URI must be an absolute URI or BaseAddress must be set.

This seems to be the default error message and it appears it gets thrown regardless of what error actually occurs.

For example I can shut down my api server and rather than get a 404 I get the error above.

I can also intentionally provide an invalid section name for the api config and I get the same error:

tokenAcquirerFactory.Configuration.GetSection("ThisDoesNotExist"); 

Now, I may be deserving of some error - but that error certainly seems like it is not the one I should be getting:

"MyApi": { 
	"BaseUrl": "https://localhost:5010/", 
	"RelativePath": "api/MyController/ThisMethod",
	"RequestAppToken": true,
	"Scopes": [ "api://yada-6e75f60a2ef7/.default" ] // . E.g. 'api://<API_APPLICATION_ID>/.default'
},

BaseUrl is provided and the RelativePath component is valid - even if it is invalid it is not malformed.

  IConfiguration appSettings = new ConfigurationBuilder().AddJsonFile(configFilePath, false).Build();
  var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
  tokenAcquirerFactory.Services.AddDownstreamApi("MyApi", appSettings);
  tokenAcquirerFactory.Configuration.GetSection("MyApi");
  var sp = tokenAcquirerFactory.Build();
  var api = sp.GetRequiredService<IDownstreamApi>();
  string result = await api.GetForAppAsync<string>("MyAPI");  

How can I troubleshoot this error?

Lower case 'bearer' vs. 'Bearer' raises exception

Below should be changed to be 'Bearer' and not 'bearer' as per https://tools.ietf.org/html/rfc6750:

defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

and

defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

Depending on the target you are calling, an exception such as below may be raised:
{"error":{"code":"InvalidHeaderValue","message":"Authorization header token does not start with 'Bearer ' scheme."}}

upgrade to v5, sample has apps.json with no explanation

1 could you please explain what the apps.json file is used for or generated from?
2 where has IGraphServiceUsersCollectionPage gone in v5?

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [X] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Documentation needs to be updated after upgrade to Id.Web 2.5.0

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [x] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

This documentation needs to be updated. It doesn't reflect the current status of the code:
https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2/tree/master/2-Call-OwnApi#about-the-code

config.Authority does not exist in appsetting json

Please provide us with the following information:

This issue is for a: (mark with an x)

- [X ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Look at appsettings.json and the the program.cs file where it is using config.Authority from the config file which doesn't exist

Any log messages given by the failure

Expected/desired behavior

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

"The identity of the calling application could not be established." when "Tenant" is set to "organizations" (multi-tenant 3rd party app)

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

I followed the sample and was able to call Graph/users with specifying a specific AAD tenant in the "Tenant" configuration. I provisioned the 3rd party app to two tenants A and B, and be able to call Graph/users successfully when specifying tenant A or tenant B; however, when I configure "Tenant" to "organizations", I got the below error message.

Any log messages given by the failure

Failed to call the Web Api: Unauthorized
Content: {
  "error": {
    "code": "Authorization_IdentityNotFound",
    "message": "The identity of the calling application could not be established.",
    "innerError": {
      "request-id": "069e1f34-ef65-4971-9436-644ad93d9543",
      "date": "2020-06-08T07:55:59"
    }
  }
}

Expected/desired behavior

Get all users from tenant A and tenant B since the third party app has been provisioned to both tenants.

Mention any other details that might be useful

The app is registered as multi-tenant app. Is there any extra configuration needs to be set to call multiple tenant at once?
The individual successful call's token:

{
  "aud": "https://graph.microsoft.com",
  "iss": "https://sts.windows.net/5a04bd72-1be4-41a7-8b11-786d03a588da/",
  "iat": 1591599854,
  "nbf": 1591599854,
  "exp": 1591603754,
  "aio": "42dgYPgT0rcq3vdH3f7/v+5XG8gtAwA=",
  "app_displayname": "TodoList-webapi-daemon-v2",
  "appid": "0fd05c80-ecc3-499f-a151-801ff7587786",
  "appidacr": "1",
  "idp": "https://sts.windows.net/5a04bd72-1be4-41a7-8b11-786d03a588da/",
  "oid": "0a4fa8a7-4f39-4564-9f4c-30d421f9cad1",
  "roles": [
    "User.Read.All",
    "Organization.Read.All"
  ],
  "sub": "0a4fa8a7-4f39-4564-9f4c-30d421f9cad1",
  "tenant_region_scope": "NA",
  "tid": "5a04bd72-1be4-41a7-8b11-786d03a588da",
  "uti": "tTN8PcA6zESxYnwy6WDAAA",
  "ver": "1.0",
  "xms_tcdt": 1587097936
}

The failed call's token:

{
  "aud": "https://graph.microsoft.com",
  "iss": "https://sts.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/",
  "iat": 1591602138,
  "nbf": 1591602138,
  "exp": 1591688838,
  "aio": "42dgYODgNK8s/8Z7tjJ5k5JLy0IHAA==",
  "app_displayname": "TodoList-webapi-daemon-v2",
  "appid": "0fd05c80-ecc3-499f-a151-801ff7587786",
  "appidacr": "1",
  "idp": "https://sts.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/",
  "tenant_region_scope": "WW",
  "tid": "72f988bf-86f1-41af-91ab-2d7cd011db47",
  "uti": "na-E2oVbOUmuZDVWAV0iAA",
  "ver": "1.0",
  "xms_tcdt": 1289241547
}

Thanks! We'll be in touch soon.

What is PoP?

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [x ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

N/A

Any log messages given by the failure

N/A

Expected/desired behavior

Thorough documentation of what PoP is and stands for especially in the README.md file.

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

N/A

Versions

N/A

Mention any other details that might be useful

N/A

Id Web sample for calling a devops api with managed identity

To promote usage of the new Managed Identity feature in Id Web, we need to create a new sample for it. Therefore, we will create a ch 5 sample for calling a Devops API using managed identity. We are choosing this scenario as it is not already covered by a specific Azure SDK.

Getting 'invalid audience' error on calling Web API from Daemon Console App

Please provide us with the following information:

This issue is for a: UnAuthorize Daemon App

- [ ] documentation issue or request

Minimal steps to reproduce

1: Run WEB API Service. 2: Run Client Daemon App

Any log messages given by the failure

Failed to call the Web Api: StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1,
WWW-Authenticate: Bearer error="invalid_token", error_description="The audience '4be05bf7-xxxx-xxxx-xxxc-xxxxxxx' is invalid"

Expected/desired behavior

Must Return API Response with 200 Status Code instead of 401

OS and Version?

Windows 10

Versions

.Net 6 or 3.1 core, and manifest oAuth v 2.0

Mention any other details that might be useful

1: First of all it does not mention which oAuth ver it uses, as per manifest '"accessTokenAcceptedVersion": null' means it is v1.0 and issuer is sts where what if we want oAuth 2.0 with value 2 instead of null as "accessTokenAcceptedVersion": 2 ? Does the code still runs?

Complete Error:
Failed to call the Web Api: StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers: { Transfer-Encoding: chunked Server: Microsoft-IIS/10.0 WWW-Authenticate: Bearer error="invalid_token", error_description="The audience 'xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx' is invalid" X-Powered-By: ASP.NET Date: Sun, 29 May 2022 16:25:03 GMT }

Token Issuer: https://login.microsoftonline.com/{MyTenantID}/v2.0 as per https://jwt.ms/

Thanks! We'll be in touch soon.

API calls to many methods

I have implemented this sample.

I need to make calls to many different methods on my api. Since the method I cam calling is defined in the config, do I need a configuration section for each method?
Can I put the code below in a base class and just use the api object like I would use an HttpClient?
How would I re-use the code below to make two or more consecutive calls to different methods on my api?

var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();
tokenAcquirerFactory.Services.AddDownstreamApi("MyApi",
tokenAcquirerFactory.Configuration.GetSection("MyWebApi"));

var sp = tokenAcquirerFactory.Build();
var api = sp.GetRequiredService<IDownstreamApi>();

var result = await api.GetForAppAsync<IEnumerable<TodoItem>>("MyApi");

Config:

"MyWebApi": {
"BaseUrl": "https://localhost:44372",
"RelativePath": "/api/TodoList",
"RequestAppToken": true,
"Scopes": [ "api://42eb19ec-cf89-4a7c-8566-42b8d4920bdb/.default" ] // . E.g. 'api://<API_APPLICATION_ID>/.default'
}

Insufficient privileges to complete the operation.

Please provide us with the following information:

This issue is for a: (mark with an x)

- [x ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Once you run the app creation script, we get the below mentioned error. Do we need to assign any specific roles to the user?

Any log messages given by the failure

Creating the AAD application (XXX)
Error occurred while executing NewApplication
Code: Authorization_RequestDenied
Message: Insufficient privileges to complete the operation.

Expected/desired behavior

OS and Version?

Windows Server 2012 R2

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

2-Call-OwnApi wiki documents no longer match the code

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [x] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

read directions, About the code section, TodoList Web API Code section refers to pre July 1st commit, as contents listed are no longer present in Startup.cs.

Any log messages given by the failure

Expected/desired behavior

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

[Question] How/where to pass resource to avoid InvalidAuthenticationTokenAudience

Please provide us with the following information:

Hello. Was able to successfully get auth token providing certificate. However, when using the token, I am getting InvalidAuthenticationTokenAudience error.

{
    "error": {
        "code": "InvalidAuthenticationTokenAudience",
        "message": "The access token has been obtained for wrong audience or resource 'api://<client_id>'. It should exactly match with one of the allowed audiences 'https://management.core.windows.net/','https://management.core.windows.net','https://management.azure.com/','https://management.azure.com'."
    }
}

The problem is when requesting auth token, the resource : "https://management.core.windows.net/" was not provided. Can you please where to pass the resource to generate the proper token?

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [x] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Any log messages given by the failure

Expected/desired behavior

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

Versions

Mention any other details that might be useful


Thanks! We'll be in touch soon.

Using KeyVault sample missing in the repo

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [x ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Solution file missing when navigated to https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2/tree/master/3-Using-KeyVault

Any log messages given by the failure

NA

Expected/desired behavior

Solution file be present as in #1, #2 and #4 sections

OS and Version?

Windows10.

Versions

NA

Thanks! We'll be in touch soon.

Sample is incomplete. Missing TodoListService Implementation.

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ x] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Any log messages given by the failure

Expected/desired behavior

Sample should include TodoListService like the old samples did.

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)

Versions

Mention any other details that might be useful

The following sample had links to this sample that says "There's a newer version of this sample! Check it out: https://github.com/azure-samples/ms-identity-dotnetcore-daemon-console" However this newer sample does not include the TodoListService.

Old Sample:
https://github.com/Azure-Samples/active-directory-dotnet-daemon


Thanks! We'll be in touch soon.

2-Call-OwnApi instructions missing info about the Scope for TodoList-webapi-daemon-v2

Following section explains how to replace configuration values: https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2/tree/master/2-Call-OwnApi#configure-the-service-project
It specifies:

Open the TodoList-WebApi\appsettings.json file
Find the app key Domain and replace the existing value with your Azure AD tenant name.
Find the app key TenantId and replace the existing value with your Azure AD tenant ID.
Find the app key ClientId and replace the existing value with the application ID (clientId) of the TodoList-webapi-daemon-v2 application copied from the Azure portal.

But the config also has Scopes key and document doesn't specify which value should be provided there:

{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "[Enter here the tenantID or domain name for your Azure AD tenant]",
"ClientId": "[Enter here the ClientId for your application]",
"Scopes": "[Enter here the scopes for your web API]",
"TokenDecryptionCredentials": [
]
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

Also, TokenDecryptionCredentials seems to be empty - is that correct?

Daemon-Console: No connection could be made because the target machine actively refused it!

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [ ] feature request
- [X] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Any log messages given by the failure

: No connection could be made because the target machine actively refused it. (localhost:44372)' on Daemon-Console\Program.cs line : 28

Expected/desired behavior

OS and Version?

Windows 11.

Versions

11 pro 64 bit

Mention any other details that might be useful

I disabled firewall but even that the issue persist and this is app.setting for console app :

apiissue

Thanks

AADSTS7000222: The provided client secret keys are expired.

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ x ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Register Azure AD app using Configure.ps1 script and immediately run the application that will use the client secret of newly registered app and acquire access token.

Any log messages given by the failure

Caused by: com.microsoft.aad.msal4j.MsalServiceException: AADSTS7000222: The provided client secret keys are expired. Visit the Azure Portal to create new keys for your app, or consider using certificate credentials for added security: https://docs.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials
Trace ID: 7fcf7cbe-ce35-44fa-93f8-b2c7b6221d00
Correlation ID: b1ea1fd6-59c2-4cb7-9baa-eecae5452848
Timestamp: 2020-08-18 11:19:27Z

Expected/desired behavior

As the app is newly registered and the client secret key is also valid, no such error should be thrown.

OS and Version?

Windows 2016

Versions

Mention any other details that might be useful

Below app manifest gets generated after app registration. We have modified the script to generate client secret key which is valid for a duration of 5 years.

"passwordCredentials": [
        {
            "customKeyIdentifier": null,
            "endDate": "2025-08-18T18:16:34.5569146Z",
            "keyId": "58f9fbad-1732-4d65-9d40-428891bbXXXX",
            "startDate": "2020-08-18T18:16:34.5569146Z",
            "value": null,
            "createdOn": null,
            "hint": null,
            "displayName": null
        }
    ],

The timestamp seen in the error log is 2020-08-18 11:19:27Z and password credentials start date(as seen in app manifest) is "2020-08-18T18:16:34.5569146Z".
Additionally, app created date is "createdDateTime": "2020-08-18T11:16:35Z" in the app manifest.


Thanks! We'll be in touch soon.

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.