Giter Club home page Giter Club logo

active-directory-dotnet-graphapi-web's Introduction

This sample has been archived

For a more current ASP.NET MVC sample that uses Microsoft Graph, please see Microsoft Graph Snippets Sample for ASP.NET. Microsoft Graph is the recommended API for future development.

If you really wish to view the archived sample, please switch to the archived branch. This code is no longer maintained and functionality is not guaranteed.

active-directory-dotnet-graphapi-web's People

Contributors

acomsmpbot avatar azmirza avatar brandwe avatar calvli avatar danieldobalian avatar dstrockis avatar jackson-woods avatar jmprieur avatar pavankompelli avatar priyamohanram avatar ridemo avatar ronnieholm avatar shawntabrizi 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

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

active-directory-dotnet-graphapi-web's Issues

How to get authorization result with user assertion when second visiting?

Hi,
In the sample code, graph API needed authorization is got from Authorization cached when logging into AAD, but AAD will cache the user logging info, which means when I visit the restAPI in the second time, I don't need to log in again, so I won't have Authorization cached, authContext.AcquireTokenSilent(graphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
these code can not read the property authorization.

My question is, is there another way to read authorization with user assertion from context when user visit the API in second time?

Can I drop the token cache?

It looks like the token cache is running on session state. Can you provide some guidance for using the API with stateless apps (specifically when the session state mode is set to "Off" in Web.config)? I only need one-time access to AD for populating my app's membership; therefore, I don't need to cache tokens.

Can't I remove the statement for obtaining a NaiveSessionCache and take an AuthenticationContext with the method that only requires the authority parameter? I understand that if I need to perform any other Graph API work, I'll need to get a new token.

What about doing this when the request returns with a Request.QueryString["reauth"] == "True" and I need to send an OpenID Connect sign-in request to get a new set of tokens? Will having the session state (and the token cache) disabled cause a problem with that process?

"IDX10500 ..." Error

After I download code, and run the Step 2 . It shows "IDX10500 ..." Error

IDX10500: Signature validation failed. Unable to resolve SecurityKeyIdentifier: 'SecurityKeyIdentifier
(
IsReadOnly = False,
Count = 2,
Clause[0] = X509ThumbprintKeyIdentifierClause(Hash = 0x6152B1D25071BFE1A85DE2B0430918B74667AB44),
Clause[1] = System.IdentityModel.Tokens.NamedKeySecurityKeyIdentifierClause
)
',
token:....

Do you have any idea ?

Thanks,

Step 2: Run the sample in Visual Studio 2013

The sample app is preconfigured to read data from a Demonstration company (GraphDir1.onMicrosoft.com) in Azure AD. Run the sample application, and from the main page, authenticate using this demo user account: [email protected] graphDem0

SSL Connection Error

I configured the App to use my AAD tenant as you have mentioned but now I am getting : An error occurred during a connection to localhost:44322. SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

Please provide an example for Dotnet Core

The app works perfectly on right configuration. But I am currently working on a Dotnet core application and I was unsuccessful in doing the same code there. I do not find a single example on adding users to AD through Dotnet Core. Kindly help with a Dotnet Core version of this app.

Fail to add a new User/Group

I can Edit/Delete (Group or User) bur i can't Create a new one
someone has an idea of it?

same Exception Message : An error occurred while processing this request.

IUserFetcher.MemberOf.ExecuteAsync() is broken in Active Directory Client Library 2.0.8

Hi there,
I just want to report a blocker issue in IUserFetcher implementation in MemberOf.ExecuteAsync method.
It incorrectly refers to irectoryObjects path instead of directoryObjects and generates the following sample, but broken REST call:

GET https://graph.windows.net/tenant.domain.com/irectoryObjects/445b0662-8e08-4345-a4d2-bf59850d1802/memberOf?api-version=1.5 HTTP/1.1
DataServiceVersion: 1.0;NetFx
MaxDataServiceVersion: 3.0;NetFx
Accept: application/json;odata=minimalmetadata
Accept-Charset: UTF-8
DataServiceUrlConventions: KeyAsSegment
User-Agent: Microsoft Azure Graph Client Library 2.0.8
Authorization: Bearer xxx
X-ClientService-ClientTag: Office 365 API Tools 1.1.0612
Host: graph.windows.net

The README.MD file may confuse the beginner to Azure developing

index 10 of step 3 like below:

Configure Permissions for your application - in the Settings menu, choose the 'Required permissions' section, click on Add, then Select an API, and select 'Microsoft Graph' (this is the Graph API). Then, click on Select Permissions and select 'Access the directory as the signed-in user' and 'Sign in and read user profile'.

Actually, the code sample is using the Azure Graph instead of Microsoft Graph. It should select Windows Azure Active Directory instead of Microsoft Graph.

Web app fails to load System.IdentityModel.Tokens.Jwt.dll

The sample app compiles but doesn't run.

The browser displays the following Yellow Screen of Death exception:

Could not load file or assembly 'System.IdentityModel.Tokens.Jwt, Version=4.0.10708.1011,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system
cannot find the file specified.

Users mail and otheremails always null or empty

Hey, I am using graph api to perform operations on the company AD B2C tenant, and when I get the list of users, the user mail or othermails properties are null or empty, but in the token claims I can get the user mail without any problem. Any idea why I can't get mail information using graph api?

Cannot create new contact

I can see list of contact from given "Contact List" menu. I can not add new contact or update existing contact.

Can anyone help me to create new contact or update existing contact?

Thanks

'Constants' does not contain a definition for 'ResourceUrl'

'Constants' does not contain a definition for 'ResourceUrl' this happened in Utils.AuthenticationHelper.cs
as I was trying to copy it into my code. Cloning the repo does not work at all as it comes up with several hundred errors and warnings

AcquireTokenSilentAsync can't find Access Token

App can't execute Graph API call. It can be reproduced under the page localhost/UserProfile, where as a result app falls is into a loop. I found that it's because AuthenticationContext.AcquireTokenSilentAsync can't acquire Access Token.
Don't know if this issue persist only in my environment ?

This project does not open with Visual Studio 2015

I am trying to open this project in Visual Studio 2013 and it doesn't open without issues. First it complaints about missing .nuget folder and the contents. Now that I cannot find them on the online sources as well, I chose to remove them from the solution file manually. Then it leaves me with only the WebAppGraphAPI project which opens but fails to compile because it cannot find any of the referenced assemblies.

To overcome this, I have to open the .csproj file and remove all the HintPaths with the CxCache condition in them and then it allows me to compile the project.

I know it is marked to be working with VS2013. But should it be so difficult to get it working with VS2015?

TokenCache should not be static

I've had a couple of instances where token cache of one user was being received by other users, this obviously is something that shouldn't happen :D

AcquireTokenSilent fails if the sample is converted to multi tenant app

I converted this to a multitenant app by changing ida:Tenant in web.config to Common, flipping the is mutlittenant option to Yes in Azure portal and setting ValidateIssuer to false.
The login works but when trying to see the user profile, the AcquireTokenSilent call results in no token.
It works fine if I change ida:Tenant to tenant name.

Cannot get sample building in my own project

I have copied over the files that are mentioned in the steps but even those classes rely on others in the sample project so I had to copy over pretty much everything and now that that is done my GraphClient.Constants does not have the definition for ResourceUrl or TenantId that are referenced in the AuthenticationHelper class.

Does anyone know how I can get this resolved??

Thank you!

Stuck on step 12 to build my own custom webappgraphapi

The type or namespace name tokencache could not be found
tokencacheitem
tokencachenotificationargs

theses all appear to be missing even after I've added
Install-Package System.IdentityModel.Tokens.Jwt -Pre
here are my usings
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.IdentityModel.SecurityTokenService;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Web;

I also have this issue when I just clone the existing repo to my workstation.

Saving token / token lifetime

Hi,

for me it's not clear if I can save the token, e.g. for using it later in a background process, and what is the lifetime of the token in this case - or if I can get something like a refresh token. It seems like in the Startup.Auth.cs there is a Bearer-Token received, but I don't know how to change this to provide a refresh token?

Thanks & best regards,
Compu

Fail to read/write thumbnailPhoto

This sample uses a property called photofile to update photos but it doesn't exist on AAD. The ThumbnailPhoto property (which returns an IStreamFetcher do download/upload files) isn't working too (Insufficient Privileges for upload, 404 no property with name thumbnailPhoto for download)

Tested with the default tenant and also with a directory created by myself. I think the problem is in the client... if you release the code somewhere I can take a look by myself. I suspect that the problem is only in client side because older versions of the API still work.

[]s,

X

Async fails sometimes when there is paging

controllers -> groups
line 43
pagedCollection = pagedCollection.GetNextPageAsync().Result;
does not always work properly. It is better to use line 260 syntax:
pagedCollection = await pagedCollection.GetNextPageAsync();

Cannot resolve symbol ActiveDirectoryClient

After creating the AuthenticationHelper.cs file, I was getting the error below and was unable to build the project. I did not find anyone else talking about this issue so I went ahead and just tried updating the Microsoft.Azure.ActiveDirectory.GraphClient package and that seems to have fixed the problem.

Error:
Cannot resolve symbol ActiveDirectoryClient

My Info:
Windows 7 x64
Visual Studio 2013
.NET Framework 4.5

If this is indeed the correct way to fix the issue, then the part in the README that tells you to install version 1.0.3, should be changed. Thank you.

README has not been updated - Missing the setting of TenantId

Firstly it is great that you have updated this sample to use version 2 of the GraphClient, which now makes it work. I am trying to understand this example as there isn't currently any information on the version 2 interface of the GraphClient.

I don't think the README file has been updated to fully reflect the update. The main thing is you now hold the TenantId as an app setting. My question is: how do I find the TenantId?

I know I can create an Azure MVC web site with Active Directory authentication and look in the database, but that seems a bit crude, especially as I plan to remove that small database. Can I get the TenantId from the Azure Portal?

Thanks for your help on this.

Admin Consent version?

Does anyone know what a modified version of this would look like that would do the Admin consent prompt from Azure for Restricted Scopes? That would be incredibly valuable in this sample.

IUserFetcher.ExecuteAsync().Expand() not working correctly in v. 2.0.8 of the NuGet package for ADCL

Hi There, just reporting issue with implementation of Expand() of IUserFetcher.
The following command generates wrong REST call:

User user = (User) await this.activeDirectoryClient.Users.GetByObjectId(id).Expand(m=>m.MemberOf).ExecuteAsync();

The resulted REST call is:

GET https://graph.windows.net/tenant.domain.com/users/74e038a4-a619-48d2-a64b-3c6d45f0621a()?$expand=memberOf&api-version=1.5 HTTP/1.1

(note the braces after object GUID, which should be forward slash instead)

which should be instead:

GET https://graph.windows.net/officestaykov.onmicrosoft.com/users/74e038a4-a619-48d2-a64b-3c6d45f0621a/?$expand=memberOf&api-version=1.5 HTTP/1.1

ASP.NET Core?

Any chance that you can make an example on how to connect and query Graph using .Net Core?

Issue Getting Stuff

Hello,

here is my problem :
I have create the Azure website, and publish everything on it. Now when I go on the site and I sign in with my account it work great. I can see the message in the top right corner "Hello, [email protected] !"

If I go in the User profile section everything work great and I see my info. The issue is when I want to see another section. Let say "UserList"

If I click on the UserList link I see the page but the table is empty (And my AAD is full of users) and I see the message "You have to sign-in to see Users. Click here to sign-in."

If I click on the link the re-sign-in then I have an infinite loop that is starting.

Can you guide me on what could I have done wrong ?

Thanks !

How to obtain a directory extension

Hello,
I'm trying to query a custom directory extension that was added to our user object in Azure AD. I'm able to get the property using the UserProfileController and updating the Model to have our custom extension property (see the two code snippets below).

Models/UserProfile.cs
public class UserProfile { public string DisplayName { get; set; } public string GivenName { get; set; } public string Surname { get; set; } public string extension_ExtId_ExtName { get; set; } }

View/UserProfile.cshtml

@model App.Models.UserProfile
<h2>@ViewBag.Title.</h2>
<table class="table table-bordered table-striped">
    <tr>
        <td>Display Name</td>
        <td>@Model.DisplayName</td>
    </tr>
    <tr>

        <td>First Name</td>
        <td>@Model.GivenName</td>
    </tr>
    <tr>
        <td>Last Name</td>
        <td>@Model.Surname</td>
    </tr>
    <tr>
        <td>Employee Id</td>
        <td>@Model.extension_ExtId_ExtName</td>
    </tr>
</table>
@if (ViewBag.ErrorMessage == "AuthorizationRequired")
{
    <p>You have to sign-in to see your profile. Click @Html.ActionLink("here", "Index", "UserProfile", new { reauth = true }, null) to sign-in.</p>
}
@if (ViewBag.ErrorMessage == "UnexpectedError")
{
    <p>An unexpected error occurred while retrieving your profile.  Please try again.  You may need to sign-in.</p>
}

My goal is to have the extension extension_ExtId_ExtName appear on a list of users. I am trying to use the solution's UsersController and view to obtain this information, but it appears that the MS Graph API User model cannot be modified. The model is set to be of an IEnumerable for which the MS Graph Client contro. How do I add my custom extension so that I can retrieve it from the User object as well?

I've confirmed that I can obtain it via the user object by going to the Graph Explorer and setting my request URL to: https://graph.microsoft.com/beta/users('{[email protected]}')?select=extension_EXTENSION-ID_extensionName

Thanks

I cannot get this sample to work with VS2017

I have both cloned this repository and downloaded it as a zip file. When I open the solution in Visual Studio 2017, it tells me that all of the NuGet packages have been restored, but then I get a list of assemblies in the References folder that were not found. The only way I can get this to build is to remove and re-add some of the NuGet packages.

Once I do that, I can get the solution to build, but the sample doesn't work. I successfully log into my tenant, but even though it shows my account name in the toolbar, all of the pages relating to AAD information come up blank and it tells me that I still need to sign-in.

Any ideas how to make this sample work in VS2017?

Thanks.

Rob

AAD: app to app-permissions is not created properly

Hi,

I'm using this library to register 2 applications (a web api, and a windows10-UWP client app) into my AAD.

I first create the web api as followed:

        Application appObject = new Application { DisplayName = displayName };
        appObject.IdentifierUris.Add(identifierUri);
        appObject.ReplyUrls.Add(replyURL);
        appObject.Homepage = replyURL;
        appObject.AvailableToOtherTenants = false;

        appObject.GroupMembershipClaims = "All";
        appObject.ObjectType = "Application";

        // created Keycredential object for the new App object
        PasswordCredential pwdCredential = new PasswordCredential
        {
            StartDate = DateTime.UtcNow,
            EndDate = DateTime.UtcNow.AddYears(2),
            Value = secret,
        };
        appObject.PasswordCredentials.Add(pwdCredential);

        var AADAccess = new RequiredResourceAccess();
        AADAccess.ResourceAppId = "00000002-0000-0000-c000-000000000000";

        AADAccess.ResourceAccess.Add(new ResourceAccess()
        {
            //"Read directory data"
            Id = Guid.Parse("5778995a-e1bf-45b8-affa-663a9f3f4d04"),
            Type = "Role,Scope",
        });
        AADAccess.ResourceAccess.Add(new ResourceAccess()
        {
            //"Sign in and read user profile"
            Id = Guid.Parse("311a71cc-e848-46a1-bdf8-97ff7156d8e6"),
            Type = "Scope",
        });
        AADAccess.ResourceAccess.Add(new ResourceAccess()
        {
            //"Access the directory as the signed-in user"
            Id = Guid.Parse("a42657d6-7f20-40e3-b6f0-cee03008a62a"),
            Type = "Scope",
        });
        appObject.RequiredResourceAccess.Add(AADAccess);

        activeDirectoryClient.Applications.AddApplicationAsync(appObject).Wait();

This creates the application just fine, it also implicitly creates an "user_impersonation"-claim.

I then retrieve this user_impersonation-claim's Id (and the app id) as followed:

var webapiClientId = tenantWebApp.AppId;
var webapiUserAccessClaimId = tenantWebApp.Oauth2Permissions.Where(s => s.Value == "user_impersonation").Select(s => s.Id).FirstOrDefault();

This application is now visible in the management portal in the AAD. Everything in the "Configuration"-tab looks fine.

Then I create the client application as followed:

        Application appObject = new Application { DisplayName = displayName };
        appObject.ReplyUrls.Add("ms-app://TEMP/");
        appObject.ObjectType = "Application";
        appObject.PublicClient = true; //"Native Client App"
        appObject.AvailableToOtherTenants = true;
        //  Add the proper rights to the AAD
        var AADAccess = new RequiredResourceAccess();
        AADAccess.ResourceAppId = "00000002-0000-0000-c000-000000000000";

        AADAccess.ResourceAccess.Add(new ResourceAccess()
        {
            //"Sign in and read user profile"
            Id = Guid.Parse("311a71cc-e848-46a1-bdf8-97ff7156d8e6"),
            Type = "Scope",
        });
        appObject.RequiredResourceAccess.Add(AADAccess);

        //  Add the proper rights to the Tenant Web API
        var AADAccess2 = new RequiredResourceAccess();
        AADAccess2.ResourceAppId = webapiClientId;

        AADAccess2.ResourceAccess.Add(new ResourceAccess()
        {
            //Our "user_impersonation"-claim.
            Id = webapiUserAccessClaimId,
            Type = "Scope",
        });
        appObject.RequiredResourceAccess.Add(AADAccess2);

        activeDirectoryClient.Applications.AddApplicationAsync(appObject).Wait();

As you can see, the client application is given access to the web api by the "user_impersonation"-claim.

Now, when verifying this in the management portal, the application is present. HOWEVER, in the "configuration"-tab, near the bottom with "permissions to other applications", I see this:
" Delegated Permissions: 0"
instead of " Delegated Permissions: 1"

I can't open the dropdown at "Delegated Permissions" and can't select the user_impersonation-claim.

Now, the funny thing is, when I go to the web api's configuration in the AAD and change anything (e.g. add a reply url "http://tmp") and press "Save". The client's permissions are now OK !

Is there anything I'm missing or am I doing something in the wrong order?

Unit testing the Client library

Any samples we can use to unit test the client library?
I'm having a hard time mocking the client.Users etc objects
They are of type IUserCollection and I'm not sure how to create and mock that object.

Nevermind, I figured out how to test this...
But in any case a sample Unit test would be nice to have

NaiveSessionCache NullReferenceException

Hey,

if i run the Application on localhost the start page is fine but if i go to Users or something else i get a NullReferenceException. The Problem is in the NaiveSessionCache at Deserializing the web sessions cache id. The Poblem is that my HttpContext.Current.Session is null.

unbenannt

Library can't fetch expanded properties, doesn't handle 404 errors as well.

This is ridiculous, library literally can't do anything I need from it.

I need to get 1 user's properties including his memberOf array.
My code:

var currentUser = client.Users.GetByObjectId(currentUserObjectId).Expand(x => x.MemberOf).ExecuteAsync().Result;

First of all, this code makes a request like this one:

https://graph.windows.net/TENANTID/users/a7669d7c-2320-4d16-a0e8-b0b414b3a7bf()?$expand=memberOf&api-version=1.6

Notice the () at the end of the user id. This request results in 404 of course, because it's not a valid GUID.
What's event worse is that the library can't handle it, task never finishes.

When I run the demo I get

Line 1: <%@ Application Codebehind="Global.asax.cs" Inherits="WebAppGraphAPI.MvcApplication" Language="C#" %>

Working with Microsoft accounts

Thank you for putting this sample together. I am finding it very helpful. I am using it as a basis for an app to manage applications I am using AAD for authentication for, as per:

https://azure.microsoft.com/en-us/documentation/articles/active-directory-authentication-scenarios/

We use Microsoft accounts, now, and our users can do everything in https://manage.windowsazure.com/ we need: Adding and configuring applications, althought not as conveniently as we would like and also with a poka-yoke'd process.

As you have documented (excellent documentation and sample directions), "This sample will not work with a Microsoft account". Can you please give some hints or pointers on getting support for Microsoft accounts as it would be a significant improvement for to deliver that support.

thank you

User+App delegated Access token is stored in static variable which could be shared by users

Please correct me if I am wrong but it looks like a User+App delegated Access token is acquired in Startup.cs and it is stored in a static variable. Will this static variable be shared by all users.

AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
AuthenticationHelper.token = result.AccessToken;

So will usersA's access token be used by UserB?

I see that the UserProfileController uses the user's token from NaiveCache but other controllers like ContactsController use the static token in GetActiveDirectoryClient(). Is there a reason why the token is not obtained from NaiveCache?

'How To Run This Sample' fails with access denied

Following steps 1 and 2 on how to run the web app launches the web site in the browser. Clicking any of the links (Profile, UserList, GroupList, ContactList, RoleList) results in a yellow error page:

OpenIdConnectMessage.Error was not null, indicating a possible error: 'access_denied'
Error_Description (may be empty): 'AADSTS50034: User account is not registered
for the account. 
Trace ID: 2c8b724a-d6a9-45f0-897d-41ab099961e2
Correlation ID: fa68e2a1-f466-4660-aa54-c2b2c8448912
Timestamp: 2014-08-06 10:20:21Z

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.