Coder Social home page Coder Social logo

azure-samples / active-directory-dotnet-daemon Goto Github PK

View Code? Open in Web Editor NEW
107.0 63.0 53.0 1.23 MB

A Windows console application that calls a web API using its app identity (instead of a user's identity) to get access tokens in an unattended job or process.

C# 70.00% CSS 1.45% ASP 0.05% HTML 9.62% JavaScript 9.63% Roff 1.06% PowerShell 8.18%
aad desktop-app webapi asp-net-mvc

active-directory-dotnet-daemon's Introduction

Calling a Web API in a daemon app or long-running process

There's a newer version of this sample taking advantage of the Microsoft identity platform (formerly Azure AD v2.0)

Check it out: https://github.com/Azure-Samples/active-directory-dotnetcore-daemon-v2

If you really need to access this Azure AD v1.0, you can navigate to the master branch, but please know that it's no longer supported.

active-directory-dotnet-daemon's People

Contributors

acomsmpbot avatar danieldobalian avatar dstrockis avatar jennyf19 avatar jmprieur avatar kjyam98 avatar mikoleusz avatar priyamohanram avatar samirahmed avatar skwan avatar suneetnangia 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

active-directory-dotnet-daemon's Issues

Issue in 'How to run this sample' instructions

From https://github.com/Azure-Samples/active-directory-dotnet-daemon#register-the-client-app-todolistdaemon

Enter a friendly name for the application, for example 'TodoListDaemon' and select 'Web app / API' as the Application Type.

Even if this is a desktop application, this is a confidential client application hence the Application Type

For the Redirect URI, enter https://<your_tenant_name>/TodoListDaemon, replacing <your_tenant_name> with the name of your Azure AD tenant.

Azure Portal only shows 'Redirect URI' for a 'Native' type of application. If the 'Web app / API' type is selected, it shows 'Sign-on URL'.

Incorrect instructions to download the sample

This step to download the sample did not work:

Step 1: Clone or download this repository
From your shell or command line:

git clone [email protected]:AzureADSamples/Daemon-DotNet.git

I got this error:

D:\Projects\AADLibSamples> git clone [email protected]:AzureADSamples/Daemon-DotNet.git
Cloning into 'Daemon-DotNet'...
The authenticity of host 'github.com (192.30.252.128)' can't be established.
RSA key fingerprint is 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,192.30.252.128' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

The right step was:
git clone https://github.com/AzureADSamples/Daemon-DotNet

Thanks!

Are AppKeys deprecated?

The documentation on the main Code screen says:
Step 3: Register the sample with your Azure Active Directory tenant
Header: Register the TodoListDaemon app
11. Create a new key for the application. Save the configuration so you can view the key value. Save this aside for when you configure the project in Visual Studio.

I'm not seeing anywhere on my Azure "Configure" screen where generating (or viewing) a key is possible. My tenant comes from Office 365, in case that helps.

BTW - My goal (stymied so far) is simply to write a background service that pushes contacts from my system into a contact folder my customer will see in Outlook. I would really appreciate a heads-up if this sample project is NOT expected to handle the authentication needed for that scenario.

WebAPI Can't read user scope claims

I got this sample to work, but I'm trying to take it a step further by reading the daemon's permissions so I can decide if it has access to a particular WebAPI call. For instance, some Daemons might have access to the entire WebAPI- I would give those one Client ID and other Daemon clients might have access to just one or two of the WebAPI methods. Those would get a separate Client ID which would have a different permission assigned.

In this case, I simply delegated the "Have full access to the To Do List service" to the TodoListDaemon just like this "In the Permissions to Other Applications configuration section, select the TodoListService application, and add the full access delegated permission. Save the configuration."

I set a breakpoint in the TodoListController.Get method to examine the scope claims and they come back null.

  public IEnumerable<TodoItem> Get()
        {
            //
            // The Scope claim tells you what permissions the client application has in the service.
            // In this case we look for a scope value of user_impersonation, or full access to the service as the user.
            //
            Claim scopeClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope");

//THIS COMES BACK NULL EVEN THOUGH I ASSIGNED THE Daemon the user_impersonation in Azure portal

            if (scopeClaim != null)
            {
                if (scopeClaim.Value != "user_impersonation")
                {
                    throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.Unauthorized, ReasonPhrase = "The Scope claim does not contain 'user_impersonation' or scope claim not found" });
                }
            }

I would expect to see the user_impersonation claim here, not null. I've tried different variants, none of which I had any luck with.

What could I be missing?

ReadMe doesn't include step for provisioning access from the Daemon to the API

This step is missing from this ReadMe and is needed as step 12 under Register the TodoListDaemon app (Copied from another example):

In "Permissions to Other Applications", click "Add Application." Select "Other" in the "Show" dropdown, and click the upper check mark. Locate & click on the TodoListService, and click the bottom check mark to add the application. Select "Access TodoListService" from the "Delegated Permissions" dropdown, and save the configuration.

missing check on claim roles

Hello,
the service application (TodoListService) in StartUp Class is checking only the aud claim, which is not enough. Any Client App Registration in the same tenant can receive a valid bearer token with the Server's audience.
As the authorization security is implemented by creating a specific role ( access_as_application), the server shall check also check that the claim role access_as_application, has been granted to the client app registration

Or am I missing something here?

  public partial class Startup
    {
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
                    }
                });
        }
    }

Failed to Configure Permissions forDaemon app

Step 3:
8. Configure Permissions for your application - in the Settings menu, choose the 'Required permissions' section, click on Add, then Select an API, and type 'TodoListService' in the textbox. Then, click on Select Permissions and select 'Access TodoListService'.

From the following Portal, can't find 'TodoListService' app. After type 'TodoListService' in the textbox, Got "No result". So can't continue.

Issue with API hosted in Azure as App Service

First off, thank you for the great article and very easy instructions. I got your example to run when registered under my Active Directory in my subscription.

I then attempted the same exercise and steps with a API we developed that is being hosted in Azure being called by a Daemon/Client app. It is successfully passing a token in the header of the request but it does not authorize. Has anyone hosted their API in Azure and had to do anything in the App.config file or a configuration in the Azure Portal? My suspicion is that it is in Azure as it manually registers the App when you deploy from Visual Studio.

Doesn't seem to authorize as of late

Granted this code is a few years old - is there an update to it that works with ASP.NET Web API (not Core)? I am generating access token elsewhere for this Web API app in Azure AD (app registered properly with AD). The token I use (to be used with the web service endpoint) is in 'access_token' property (this is obtained by calling the OAuth v2 endpoints /authorize and /token of the code grant flow, as described in:

https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow

{
    "token_type": "Bearer",
    "scope": "profile openid email https://graph.microsoft.com/Directory.Read.All https://graph.microsoft.com/User.Read",
    "expires_in": 3599,
    "ext_expires_in": 3599,
    "access_token": "eyJ0eXAiOiJKV1QiLCJ...",
    "id_token": "eyJ0eXAiOiJKV1QiLCJ..."
}

The web api is configured with appropriate values:

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Tenant = tenantName,
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidAudience = audience
                    }
                });

However, sending a request to controller (which has the bearer token from 'access_token' above), I get back:

{
    "Message": "Authorization has been denied for this request."
}

Any suggestions/updates would be welcome. Thanks!

Can't get scopeClaim

Claim scopeClaim = ClaimsPrincipal.Current.FindFirst("roles");
When I merged the code in the sample into my service, scopeClaim is always null.

I created two applications: QueryProbeClient and QueryProbeService, And configured as instructed.

On the client,I get Access Token through the following code:
string tenant = "queryprobe.onmicrosoft.com"; string aadInstance = "https://login.microsoftonline.com/{0}"; string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant); string clientId = "19e4fe1c-d478-4a4b-928d-8122c17b5405"; string appKey = "****"; string todoListResourceId = "https://queryprobe.onmicrosoft.com/QueryProbeService"; AuthenticationContext authContext = new AuthenticationContext(authority); ClientCredential clientCredential = new ClientCredential(clientId, appKey); AuthenticationResult result = null; try { result = authContext.AcquireToken(todoListResourceId, clientCredential); } catch (Exception ex) { throw ex; } return result;
I got the Access Token and added it to the http header.

On the Service, I added the following code to the startup.cs file:
public void Configuration(IAppBuilder app) { try { app.UseWindowsAzureActiveDirectoryBearerAuthentication( new WindowsAzureActiveDirectoryBearerAuthenticationOptions { Tenant = "queryprobe.onmicrosoft.com", TokenValidationParameters = new TokenValidationParameters { SaveSigninToken = true, ValidAudience = "https://queryprobe.onmicrosoft.com/QueryProbeService" } }); } catch (Exception ex) { Logger.Info(ex.Message); throw ex; } }
However, I always get null when I get scopeClaim in the controller file.

Cannot complete manual steps at end. Error: AADSTS650056

At the end of the Configure script it asks you to navigate to the todoList_web_daemon_v1 API Permissions and to click on "Grant admin consent for (your tenant)."

I try that but get the following error:

Request Id: 26f0629a-b0f4-496e-9d64-79d1fbf25300
Correlation Id: 09bf39ee-14e0-452a-8c4d-2459f1fba730
Timestamp: 2019-06-06T14:48:29Z
Message: AADSTS650056: Misconfigured application. This could be due to one of the following: The client has not listed any permissions for 'AAD Graph' in the requested permissions in the client's application registration. Or, The admin has not consented in the tenant. Or, Check the application identifier in the request to ensure it matches the configured client application identifier. Please contact your admin to fix the configuration or consent on behalf of the tenant. Client app ID:

Tenant Name vs id

The instructions stated using the Tenant Name as ida:Tenant in the two config files.

"Find the app key ida:Tenant and replace the existing value with your Azure AD tenant name."

I found that I had to use the Tenant ID value in these two configuration elements for it to work.

Authorization has been denied for this request

After downloading the sample, we have tried to recreate this sample but we can't get it to work. We have double checked the configuration/steps needed for the client and the service, but still no success.

We have run the client in the debugger and we get a token when we call "AquireToken" on the AuthenticationContext. We get the following message when we call our service:
“Authorization has been denied for this request.”

We have tried anything that we can think of, with no success. Suggestions on how to solve/troubleshoot this problem, would be very much appreciated.

Can you clarify a step in the README.md?

Under the section "## How to deploy this sample to Azure" there is a subsection titled "### Update the Active Directory tenant application registration for TodoListService" at line 222. It states:

  1. Navigate to the Azure portal.
  2. On the top bar, click on your account and under the Directory list, choose the Active Directory tenant containing the TodoListService application.
  3. On the applications tab, select the TodoListService application.
  4. From the Settings -> Reply URLs menu, update the Sign-On URL, and Reply URL fields to the address of your service, for example https://TodoListService-contoso.azurewebsites.net. Save the configuration.

By "applications tab" in step 3 do you mean "Enterprise Applications" or "App Registrations" or some other section? If I look for "Sign-On URL" or "Reply URL" under either of those sections, I can't find them. The only thing I could find that was similar was "replyUrlsWithType" and "signInUrl" under the App Registrations/Manifest section.

Why ClaimScope Always Getting Null ?

Hello My Friend,

We are facing issue in below statement, Could you please help me.

Claim scopeClaim = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope");

by using above statement we always getting scopeClaim 'null'.
for the use of above statement any special kind of permission need to apply in Azure AD Account ?
If needed any kind of permission there then please specify.

Reply me ASAP.

Best Regards,
BhauMik Kanjiya

Project doesn't build from CLI, builds from VS, but Intellisense doesn't believe it (Microsoft.IdentityModel namespace issue)

I installed .NET Core 2.1.402, updated my Visual Studio 2017 Professional to 15.8.5 and cloned the repo as per the README.

The application builds successfully from Visual Studio .

However, everything related to Microsoft.IdentityModel is underlined by Intellisense, despite some restarts. (see screenshot)

image

I also tried to do dotnet restore in case it was some external package issue, but apparently no NuGet package are needed here.

It's a bit problematic to work correctly with a tool believing you are not using correct code.

I digged and tried to use dotnet build instead, and it seems I get a related error :

image

(sorry for the French in the screenshot, but basically a targeted project was not at all installed in the indicated directory in .NET SDK...)

What could be the cause / fix for this ?

NuGet Package restore failed for project

Hello

When I tried to build in VS2017 15.5.4 I got an error.
NuGet Package restore failed for project TodoListDaemon: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters..

Any ideas?

Add instructions on how to require role assignment

In the current instructions, it says to add a delegating permission. This does nothing! If you follow this example, ANY client ID in your tenant can make calls to the API ... extremely insecure.

Please add instructions on how to properly secure an API by turning on requiring role assignment:
image

add a role to the service through the manifest:

  "appRoles": [
    {
      "allowedMemberTypes": [ "Application" ],
      "description": "Allow the application to access TodoListService",
      "displayName": "Access TodoListService",
      "id": "0C65E07C-9D03-4617-83D3-09ADAE44C4E1",
      "isEnabled": true,
      "origin": "Application",
      "value": "api-access"
    }
  ],

and assign that role to the daemon:
image

Group Claim

Hi,

Not sure if i'm doing something wrong, but when using this sample and UserPasswordCredential i can't find a way to add a Group claim to the access token. I updated manifest file to read "groupMembershipClaims": "All". Is there something else i should be doing add the group claim?

Thanks

System.AggregateException

When the todo:TodoListBaseAddress value in app.config is changed to the web app address from default https://localhost:44321, the following error is thrown.

System.AggregateException
HResult=0x80131500
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at TodoListDaemon.Program.Main(String[] args) in C:\gitClones\active-directory-dotnet-daemon-master\TodoListDaemon\Program.cs:line 82
Inner Exception 1:
HttpRequestException: An error occurred while sending the request.
Inner Exception 2:
WebException: The underlying connection was closed: An unexpected error occurred on a send.
Inner Exception 3:
IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Inner Exception 4:
SocketException: An existing connection was forcibly closed by the remote host

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.