Coder Social home page Coder Social logo

msgraph-training-aspnetmvcapp's Introduction

Microsoft Graph Training Module - Build MVC apps with the Microsoft Graph .NET SDK

This module will introduce you to working with the Microsoft Graph .NET SDK in creating an ASP.NET MVC web application to access data in Office 365.

This module is based on the following Microsoft Learn module: Build ASP.NET MVC web applications with the Microsoft Graph .NET SDK

Lab - Build MVC apps with the Microsoft Graph .NET SDK

The lab for this module is available in multiple units within the associated Microsoft Learn module. Use the following links to jump to the specific unit. Each Microsoft Learn unit represents a different lab exercise and demo in the presentation.

  1. Exercise: Create ASP.NET MVC web app and register Azure AD app

    In this exercise, you'll create an ASP.NET MVC web application with Visual Studio and Azure AD application with the Azure Active Directory admin center. Once the application is created, you'll then add the necessary packages and libraries that support user authentication and requesting data from Microsoft Graph.

  2. Exercise: Incorporate the Microsoft Authentication Library into ASP.NET MVC web apps

    In this exercise, you'll extend the application from the previous exercise to support authentication with Azure AD. This is required to obtain the necessary OAuth access token to call the Microsoft Graph API. In this step, you'll integrate the OWIN middleware and the Microsoft Authentication Library library into the application.

  3. Exercise: Incorporate Microsoft Graph into ASP.NET MVC web apps

    In this exercise, you'll incorporate Microsoft Graph into the application. For this application, you'll use the Microsoft Graph Client Library for .NET to make calls to Microsoft Graph.

Demos

  1. Create an ASP.NET MVC web app
  2. Add Azure AD authentication
  3. Add Microsoft Graph

Watch the Module

This module has been recorded and is available in the Office Development YouTube channel: Build MVC apps with the Microsoft Graph .NET SDK

Contributors

Roles Author(s)
Lab / Slides / Demos Andrew Connell (Microsoft MVP, Voitanos) @andrewconnell
QA Rob Windsor (Microsoft MVP, PAIT Group) @rob-windsor
QA Julie Turner (Microsoft MVP, Sympraxis Consulting) @juliemturner
Sponsor / Support Yina Arenas (Microsoft) @yinaa

Version history

Version Date Comments
1.23 May 17, 2022 FY2022Q4 content refresh
1.22 March 1, 2022 FY2022Q3 content refresh
1.21 December 8, 2021 FY2022Q2 content refresh
1.20 September 13, 2021 FY2022Q1 content refresh
1.19 May 26, 2021 Refresh slides to new template
1.18 May 17, 2021 FY2021Q4 content refresh
1.17 March 6, 2021 FY2021Q3 content refresh
1.16 December 10, 2020 FY2021Q2 content refresh
1.15 September 10, 2020 FY2021Q1 content refresh
1.14 June 11, 2020 2020Q4 content refresh
1.13 March 10, 2020 2020Q3 content refresh
1.12 January 14, 2020 Port module to MS Learn
1.11 December 9, 2019 2020Q2 content refresh
1.10 September 9, 2019 2020Q1 content refresh
1.9 June 18, 2019 Updated readme to refreshed screencast recording
1.8 May 29, 2018 2019Q4 content refresh
1.7 April 4, 2018 2019Q3 content refresh
1.6 December 18, 2018 2019Q2 content refresh
1.5 November 27, 2018 Onboarded to docs.microsoft.com/graph
1.4 September 12, 2018 2019Q1 content refresh
1.3 August 24, 2018 Revised modules for consistency with other training.
1.2 June 28, 2018 Added screencast.
1.1 June 04, 2018 Rewritten to use latest guidance.
1.0 ~November 24, 2017 Add Microsoft Graph related product breakouts.

Disclaimer

THIS CODE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

msgraph-training-aspnetmvcapp's People

Contributors

andrewconnell avatar baywet avatar dependabot[bot] avatar jasonjoh avatar jthake avatar juliemturner avatar microsoft-github-policy-service[bot] avatar mumukichi avatar rob-windsor avatar yinaa 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

Watchers

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

msgraph-training-aspnetmvcapp's Issues

Visual Studio gives warning CS1998 on lambda function

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

This is the offending code:

var graphClient = new GraphServiceClient(
    new DelegateAuthenticationProvider(
        async (requestMessage) =>
        {
            requestMessage.Headers.Authorization =
                new AuthenticationHeaderValue("Bearer", accessToken);
        }));

After first login, GetAccountsAsync() returns no accounts

I'm using .Net Framework with this code, and I'm always able to sign in, retrieve the access token and query Graph on the first login when I run the solution locally using Chrome. If I stop debugging then start again, I'm already authenticated and the code in Startup.Auth doesn't run. When I try to get events, the call to GetAccountsAsync() (which is inside GetAuthenticatedClient) always returns 0 accounts, which causes and exception when calling AcquireTokenSilent.

Has anyone else experienced this behavior? It looks to me like the new browser start doesn't affect my request (still authenticated) but the token cache is cleared.

Fails to display SignIn page

I followed the steps in the readme.md file included in the zip file that I downloaded. When I hit F5 in VS 2019 Preview to debug the app, the home page displays correctly. Then I click the "Click here to sign In" button, I get the following on the resulting page:

Hmmm… can't reach this page

It looks like the webpage at https://localhost:44375/Account/SignIn might be having issues, or it may have moved permanently to a new web address.

ERR_HTTP2_PROTOCOL_ERROR

Did I do something wrong?

Rob Bernstein

The collection type 'Microsoft.Graph.IUserEventsCollectionPage' is abstract, an interface, or is read only, and could not be instantiated and populated.

The Calendar code returns the following error. Any pointers greatly appreciated :-)

Exception Details: System.NotSupportedException: The collection type 'Microsoft.Graph.IUserEventsCollectionPage' is abstract, an interface, or is read only, and could not be instantiated and populated.

The error is on line 58 of the CalendarController: -

Line 56:             var graphClient = GetAuthenticatedClient(); 
Line 57:  
**Line 58:             var events = await graphClient.Me.Events.Request()** 
Line 59:                 .Select("subject,organizer,start,end") 
Line 60:                 .OrderBy("createdDateTime DESC")
--

changing to single tennant

i have my app registration as a single tennant ie only from the same organisation.

i have changed the authority to this
Authority = "https://login.microsoftonline.com/[mytennantid]/v2.0"

and i still get this error message even though i have not used common anywhere in the app.

the error gets thrown here at this line in the startup file:
var result = await idClient.AcquireTokenByAuthorizationCode(
scopes, notification.Code).ExecuteAsync()

error received:

ex.Message = "AADSTS50194: Application '[myappid]'(name) is not configured as a multi-tenant application. Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint o...

Calendar display is in UTC

I noticed my calendar appointments were all displayed in UTC. Might want to use .ToLocalTime() to mirror the user's calendar experience.

Learning

Hello I am learning the new Azure and Microsoft Graph programs. I recently received the following error message...
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Import-Module : File C:\Program Files\WindowsPowerShell\Modules\Azure\5.3.0\Azure.psm1 cannot be loaded because
running scripts is disabled on this system. For more information, see about_Execution_Policies at
https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1

  • Import-Module Azure
  •   + CategoryInfo          : SecurityError: (:) [Import-Module], PSSecurityException
      + FullyQualifiedErrorId : UnauthorizedAccess,Microsoft.PowerShell.Commands.ImportModuleCommand 
    
    

I was under impress since Graph was a open source products from learing program were usable. I am simply following instruction on site. Can anyone help?

Needs permission to access resources in your organization that only an admin can grant

"Need admin approval
graph-tutorial
graph-tutorial needs permission to access resources in your organization that only an admin can grant. Please ask an admin to grant permission to this app before you can use it.

Have an admin account? Sign in with that account
Return to the application without granting consent"

MSFT account

Please kindly help. I have followed the tutorial, I can get to the login page, when clicking on Sign-In, shows --> Need admin approval message as mentioned above. This happens for all samples with the Graph API when tried with the MSFT user account.

Even tried this example: https://docs.microsoft.com/en-gb/graph/office-365-connected-services, same issue

Need admin approval

Hi, thanks for the tutorial.
I followed all instructions but after I logged in to the app, I got a message saying:
"Need admin approval
My ASP.NET App
My ASP.NET App needs permission to access resources in your organization that only an admin can grant. Please ask an admin to grant permission to this app before you can use it.
Have an admin account? Sign in with that account
Return to the application without granting consent"
(And yes, I am a Microsoft employee.)
What do I need to do, at this point?
Thanks again.

Session null

I try do adopt the code to ASP.NET Webforms
run in error on authentication, reason is Session is null (nothing). Here in sample ctx.session. The same code as C# in this MVC sample works. Any idea where to investigate?

    Private Async Function OnAuthorizationCodeReceivedAsync(ByVal notification As AuthorizationCodeReceivedNotification) As Task
    Dim signedInUserId As String = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value

    Dim ctx = TryCast(notification.OwinContext.Environment("System.Web.HttpContextBase"), HttpContextBase)
    Dim tokenStore As SessionTokenStore = New SessionTokenStore(signedInUserId, ctx)`

"Trouble signing you in"

I followed all the steps and I got the below message after signing in with my account.

"Sorry, but we’re having trouble signing you in.
AADSTS700016: Application with identifier '{appID}' was not found in the directory '53fe2caa-607b-41c9-bdd6-cebd25cece19'. 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 may have sent your authentication request to the wrong tenant. "

There are no instructions in the tutorial about consenting. I went to the applications API permissions and Azure and granted content for Microsoft Graph User.Read and Calendar.Read.
Are there other places to set consent? I am in Azure.gov.

Incomplete user profile data

When retrieving data via the 'User.Read' scope, I am only seeing data for the 'businessPhones', 'displayName', 'givenName', 'id', 'jobTitle', 'mail', 'mobilePhone', 'officeLocation', 'preferredLanguage', 'surname' and 'userPrincipalName' properties.

Is there a way to modify this tutorial to include ALL of the properties of the Microsoft.Graph.User object? I have seen this accomplished in a couple of .Net Core demos but I'm not ready for .Net Core just yet. As always, any assistance is greatly appreciated.

Cache Sign Out & Sign In Error

Apparently once the user session is closed, the token does not expire and lets you enter the application URL again without asking for the credentials, I believe that the cache remains heavy on the instruction.
The same thing happens in the video that I noticed;

https://youtu.be/a2teHZ5WuNc?t=2537 Min 42:17

Issue with SessionTokenStore, httpContext is null

This issue is not exactly with this sample code but when I extend the code with additional methods, thats when I am seeing the issue with the token store.

I added a new method to upload files to SPO using Microsoft Graph, using the ChunkedUploadProvider which maintains an upload session until the whole file is uploaded. I pasted the method below for your reference.

The code always fails in the method BeforeAccessNotification of SessionTokenStore class with the error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'

Here is the line that fails:
args.TokenCache.DeserializeMsalV3((byte[])httpContext.Session[tokenCacheKey]);

The httpContext object is null.

It appears since the file upload is done asynchronously in separate thread, the httpContext is null. What is the best way to fix this issue? Can we make the SessionTokenStore more robust to handle such scenario?

Here is the file upload method:

    public static async Task<DriveItem> UploadFileAsync(Stream fileStream, string fileName)
    {
        var graphClient = GetAuthenticatedClient();
        DriveItem uploadedFile = null;
        //uploadedFile = await graphClient.Sites["root"].Drive.Root.ItemWithPath(fileName).Content.Request().PutAsync<DriveItem>(fileStream);
        UploadSession uploadSession = null;
        uploadSession = await graphClient.Sites["root"].Drive.Root.ItemWithPath(fileName).CreateUploadSession().Request().PostAsync();

        if (uploadSession != null)
        {
            // Chunk size must be divisible by 320KiB, our chunk size will be slightly more than 1MB
            int maxSizeChunk = (320 * 1024) * 4;
            ChunkedUploadProvider uploadProvider = new ChunkedUploadProvider(uploadSession, graphClient, fileStream, maxSizeChunk);
            var chunkRequests = uploadProvider.GetUploadChunkRequests();
            var exceptions = new List<Exception>();
            var readBuffer = new byte[maxSizeChunk];
            foreach (var request in chunkRequests)
            {
                var result = await uploadProvider.GetChunkRequestResponseAsync(request, readBuffer, exceptions);

                if (result.UploadSucceeded)
                {
                    uploadedFile = result.ItemResponse;
                }
            }
        }         
        return uploadedFile;
    }

MSAL.NET 4.0 update breaks this tutorial

I had used this tutorial as a basis for a web app that I am working on, running on C# with all packages up-to-date as of this post. However, I needed access to the GetSchedule() method for Microsoft Graph, and thus needed to switch to MSAL 4.0 in order to do so. This switch creates an issue with the SessionsTokenStore.cs file.

Line 57 marks the first of two methods that are causing the problem:
private void Load()
{
sessionLock.EnterReadLock();
tokenCache.DeserializeMsalV3((byte[])httpContext.Session[cacheId]);
sessionLock.ExitReadLock();
}

private void Persist()
{
sessionLock.EnterReadLock();
httpContext.Session[cacheId] = tockenCache.SerializeMsalV3();
sessionLock.ExitReadLock();}`

These two methods now give the following errors:
ITokenCache.DeserializeMsalV3(byte[], bool) is now obsolete. Use ITokenCacheSerializer.DeserializeMsalV3 on the TokenCacheNotificationArgs in the cache callback.

and

ITokenCache.SerializeMsalV3() is obsolete. Use ITokenCacheSerializer.SerializerMsalV3 on the TokenCacheNotificationArgs in the cache callback.

From what I've seen, these are the only things impacted by the MSAL 4.0 update. How should I go about fixing this?

Calendar data for multiple users

I have built the example and thats all fantastic....

But i need to expand the idea to allow users to login and then their calendar data to be displayed along with all other users who have logged in.

This is to create a common calendar across multiple accounts.

So - could this be updated so the TOKEN which are stored in a DB are looped through to then call the GetEventsAsync....
But would there be limit to number of calls which can be made to the GRAPH API service???

thanks

Error: Too many redirects.

I used your example to authenticate a local web app in Visual Studio 2017 with Azure and it works fine, I integrated your code in my application, however, when I try to move the app to a Azure Web App, I made the changes in the App registration (Azure) and in the privatesetting.config file, to use the Azure URL, but it send me a error: ERR_TOO_MANY_REDIRECTS. Of course I delete the cookies but it does not work. I can access some pages of the site in Azure withour problems, but when I tra to used the authentication id does not work. Please I need help to solve this issue. I added the images where I changed to Azure URL, in fact I added the "...Home/Index" to be sure it goes to the root page but it does not work.
image

image
image

How to get Logged in user's AD group

Hi,
We are trying to user Microsoft Graph instead of Azure AD Graph.
We need to get logged in user's Azure AD group in our MVC web application.
Please provide the sample code to get user's AD group.
Thank you.

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.