Coder Social home page Coder Social logo

microsoftgraph / msgraph-sample-aspnet-core Goto Github PK

View Code? Open in Web Editor NEW
61.0 8.0 43.0 2.51 MB

This sample demonstrates how to use the Microsoft Graph .NET SDK to access data in Office 365 from ASP.NET Core apps.

License: MIT License

C# 74.28% HTML 22.12% CSS 3.15% JavaScript 0.45%
asp-net-core microsoft-graph devxsample

msgraph-sample-aspnet-core's Introduction

page_type description products languages
sample
This sample demonstrates how to use the Microsoft Graph .NET SDK to access data in Office 365 from ASP.NET Core apps.
ms-graph
office-exchange-online
csharp
aspx-csharp

Microsoft Graph sample ASP.NET Core app

.NET License.

This sample demonstrates how to use the Microsoft Graph .NET SDK to access data in Office 365 from ASP.NET Core apps.

Note

This sample was originally built from a tutorial published on the Microsoft Graph tutorials page. That tutorial has been removed.

Prerequisites

To run the completed project in this folder, you need the following:

  • The .NET Core SDK installed on your development machine.
  • Either a personal Microsoft account with a mailbox on Outlook.com, or a Microsoft work or school account.

If you don't have a Microsoft account, there are a couple of options to get a free account:

Register a web application with the Azure Active Directory admin center

  1. Open a browser and navigate to the Azure Active Directory admin center. Login using a personal account (aka: Microsoft Account) or Work or School Account.

  2. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

  3. Select New registration. On the Register an application page, set the values as follows.

    • Set Name to ASP.NET Core Graph Tutorial.
    • Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
    • Under Redirect URI, set the first drop-down to Web and set the value to https://localhost:5001/.
  4. Select Register. On the ASP.NET Core Graph Tutorial page, copy the value of the Application (client) ID and save it, you will need it in the next step.

  5. Select Authentication under Manage. Under Redirect URIs add a URI with the value https://localhost:5001/signin-oidc.

  6. Set the Logout URL to https://localhost:5001/signout-oidc.

  7. Locate the Implicit grant section and enable ID tokens. Select Save.

  8. Select Certificates & secrets under Manage. Select the New client secret button. Enter a value in Description and select one of the options for Expires and select Add.

  9. Copy the client secret value before you leave this page. You will need it in the next step.

    [!IMPORTANT] This client secret is never shown again, so make sure you copy it now.

Configure the sample

  1. Open your command line interface (CLI) in the directory where GraphTutorial.csproj is located, and run the following commands, substituting YOUR_APP_ID with your application ID from the Azure portal, and YOUR_APP_SECRET with your application secret.

    dotnet user-secrets init
    dotnet user-secrets set "AzureAd:ClientId" "YOUR_APP_ID"
    dotnet user-secrets set "AzureAd:ClientSecret" "YOUR_APP_SECRET"

Run the sample

In your CLI, run the following command to start the application.

dotnet run

Code of conduct

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.

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-sample-aspnet-core's People

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

msgraph-sample-aspnet-core's Issues

Limit access to AD (guest) users only

Currently, any user can authenticate against the app, whether they are in my AD or not. How do I limit access to only the users that are in my AD? It doesn't matter if they are guest users or my own AD users.

Recent dependency bumps causes MsalUiRequiredException, breaks functionality

Describe the bug
The version bumps in the following packages seem to have breaking changes unaccounted for in this repo (I'm not familiar enough to understand what, exactly):

  • Microsoft.Identity.Web
  • Microsoft.Identity.Web.MicrosoftGraph
  • Microsoft.Identity.Web.Ui

Maybe it's something with our Azure App but I consistently get the following exceptions when signing in, and the site is broken after that:

MsalUiRequiredException:
        ErrorCode: user_null
Microsoft.Identity.Client.MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call.

To Reproduce
Steps to reproduce the behavior:

  1. Make sure you've signed out of the application or use private browser
  2. Checkout 7aeeb9a (HEAD at main branch at time of writing)
  3. Try to sign in
  4. Site is broken:
    • Dropdown menu in upper right is incomplete
    • Welcome message for user on home page missing
    • TimeZoneNotSupportedException displayed in calendar (screenshot below)

Expected behavior
Checking out 9b6b9c9 (prior to the version bumps above) seems to solve the issue. I can sign in and view my calendar events. No issues

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows 11
  • Browser: Edge
  • Version: 117.0.2045.60

Events 30 days

Hi,

Is it possible for me to catch the events of a period longer than 7 days?

Thank you.
Luciano

How to get sites for guest users?

I couldn't find this anywhere in the documentation. I'm using the dotnet core sdk, and I can get the sharepoint sites for an AD member with var sites = await _graphClient.Sites.Request().GetAsync();.

However, this same code does not return anything for a guest AD user (added as guest to the AD). The guest user (an outlook.com user) has been invited (and can access) the sharepoint site, but the site is not returned in the query above.

I made sure that the tenant ID has been switched from common to the specific ID in Azure. I was following the tutorial published here: https://docs.microsoft.com/en-us/graph/tutorials/aspnet-core and expanded on that. The tutorial itself is actually pretty good. It would be nice to have some advanced stuff covered as well.

Tutorial Uses Out of Date Microsoft.Identity.Web Package

When going through this tutorial, it uses a version of Microsoft.Identity.Web that is several revisions behind the current package. Running the tutorial with updated packages is not working. Can this be updated to have instructions for the latest packages?

Using Microsoft Graph Beta Endpoint

Hi,
I'm working on a project that needs to use the Microsoft Graph Beta Endpoint (for Workspaces in EXO). Using this sample, I implemented the base code and found a problem:

When I switch the package from Microsoft.Identity.Web.MicrosoftGraph to Microsoft.Identity.Web.MicrosoftGraphBeta the Beta endpoint and code should be used, correct?

Unfortunately the Base URL is changing between Startup code and controller code.

To reproduce: Switch the mentioned package. When you inspect the _graphClient object in Startup.cs, the baseUrl says "https://graph.microsoft.com/beta". When you inspect the _graphClient object in the Calendar Controller (e.g. in the constructor), the baseUrl property is "https://graph.microsoft.com/v1.0".

Can someone explain this to me and give me a workaround?

Thanks in advance,

Uwe

The packages specified are different in the command and description.

Where did you get the code?

Describe the bug
The packages specified in "Add NuGet packages" are different in the command and description.

To Reproduce
Steps to reproduce the behavior:
https://docs.microsoft.com/en-us/graph/tutorials/aspnet-core?tutorial-step=1
The packages specified in "Add NuGet packages" are different in the command and description.

Expected behavior
❌dotnet add package Microsoft.Identity.MicrosoftGraph --version 1.1.0
⭕dotnet add package Microsoft.Identity.Web.MicrosoftGraph --version 1.1.0

Screenshots
image

Desktop (please complete the following information):

  • OS Windows10(2004)
  • Browser Edge
  • Version 86.0.622.56(64bit)

Dependency versions

Additional context

Events with previous week start date and this week end date displayed incorrectly

Where did you get the code?

Describe the bug
If the event starts previous week and ends this week - it will be displayed incorrectly (under the wrong day of week).

To Reproduce
Steps to reproduce the behavior:

  1. Create an event in calendar that starts previous week and ends this week
  2. Go to the Calendar in the menu.

Expected behavior
An event is not displayed or displayed under the day it ends.

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows 10 Pro N build 19041
  • Browser: Chrome
  • Version: 85

** Suspected cause and proposed solution **
suspected cause:

        private IEnumerable<CalendarViewEvent> GetEventsForDay(System.DayOfWeek day)
        {
            return _events.Where(e => e.Start.DayOfWeek.Equals(day));
        }

proposed solution:

       private IEnumerable<CalendarViewEvent> GetEventsForDay(System.DayOfWeek day)
        {
            return _events.Where(e => ((e.Start.DayOfWeek.Equals(day)) & (e.Start.Date >= _startOfWeek)) | ((e.End.DayOfWeek.Equals(day)) & (e.Start.Date < _startOfWeek)));
        }
 

image

MS Graph not pulling expected data

Describe the bug
I have a strange bug with this tutorial. I followed it directly, but the ability to actually grab the Graph data appears to not be working properly. There's no error message, it just doesn't grab my name or other information.

image

To Reproduce
Steps to reproduce the behavior:

  1. Follow steps in tutorial README.md
  2. Execute
  3. See screenshot

Expected behavior
My name should be in there.

Screenshots
See above.

Desktop (please complete the following information):

  • Windows 10; using Edge InPrivate; Azure AD tenant is a client of mine.

Dependency versions
I changed the package to .NET 6 for this particular example, but the behavior is identicial in .NET 7.

Additional context
I noted this in the stack trace, and it concerned me. According to one of my employees, this worked as-is a week and a half ago, too.

The stack trace:

my specific concerning line:

Microsoft.Identity.Web.TokenAcquisition: Information: [MsIdWeb] An error occured during token acquisition: No account or login hint was passed to the AcquireTokenSilent call. 

Original:

Microsoft.Identity.Web.TokenAcquisition: Information: False MSAL 4.56.0.0 MSAL.NetCore .NET 6.0.23 Microsoft Windows 10.0.19045 [2023-10-16 15:37:27Z - 61ffc6a0-e115-4ff6-acd6-f76f604bc411] TokenEndpoint: ****
Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: Microsoft.IdentityModel Version: 6.33.0.0. Date 10/16/2023 15:37:27. PII logging is OFF. See https://aka.ms/IdentityModel/PII for details. 
IDX10242: Security token: '[PII of type 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' has a valid signature.
Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10239: Lifetime of the token is valid.
Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10234: Audience Validated.Audience: 'd3969ae9-085c-4938-b0cb-234ba4533f3f'
Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10245: Creating claims identity from the validated token: '[PII of type 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
Microsoft.IdentityModel.LoggingExtensions.IdentityLoggerAdapter: Information: IDX10241: Security token validated. token: '[PII of type 'System.IdentityModel.Tokens.Jwt.JwtSecurityToken' is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
Microsoft.Identity.Web.TokenAcquisition: Information: False MSAL 4.56.0.0 MSAL.NetCore .NET 6.0.23 Microsoft Windows 10.0.19045 [2023-10-16 15:37:27Z - 43f2aab0-3f31-42a6-ad4e-94622d556ac5] MSAL MSAL.NetCore with assembly version '4.56.0.0'. CorrelationId(43f2aab0-3f31-42a6-ad4e-94622d556ac5)
Microsoft.Identity.Web.TokenAcquisition: Information: False MSAL 4.56.0.0 MSAL.NetCore .NET 6.0.23 Microsoft Windows 10.0.19045 [2023-10-16 15:37:27Z - 43f2aab0-3f31-42a6-ad4e-94622d556ac5] === AcquireTokenSilent Parameters ===
Microsoft.Identity.Web.TokenAcquisition: Information: False MSAL 4.56.0.0 MSAL.NetCore .NET 6.0.23 Microsoft Windows 10.0.19045 [2023-10-16 15:37:27Z - 43f2aab0-3f31-42a6-ad4e-94622d556ac5] LoginHint provided: False
Microsoft.Identity.Web.TokenAcquisition: Information: False MSAL 4.56.0.0 MSAL.NetCore .NET 6.0.23 Microsoft Windows 10.0.19045 [2023-10-16 15:37:27Z - 43f2aab0-3f31-42a6-ad4e-94622d556ac5] Account provided: False
Microsoft.Identity.Web.TokenAcquisition: Information: False MSAL 4.56.0.0 MSAL.NetCore .NET 6.0.23 Microsoft Windows 10.0.19045 [2023-10-16 15:37:27Z - 43f2aab0-3f31-42a6-ad4e-94622d556ac5] ForceRefresh: False
Microsoft.Identity.Web.TokenAcquisition: Information: False MSAL 4.56.0.0 MSAL.NetCore .NET 6.0.23 Microsoft Windows 10.0.19045 [2023-10-16 15:37:27Z - 43f2aab0-3f31-42a6-ad4e-94622d556ac5] 
=== Request Data ===
Authority Provided? - True
Scopes - User.Read MailboxSettings.Read Calendars.ReadWrite
Extra Query Params Keys (space separated) - 
ApiId - AcquireTokenSilent
IsConfidentialClient - True
SendX5C - False
LoginHint ? False
IsBrokerConfigured - False
HomeAccountId - False
CorrelationId - 43f2aab0-3f31-42a6-ad4e-94622d556ac5
UserAssertion set: False
LongRunningOboCacheKey set: False
Region configured: 

Microsoft.Identity.Web.TokenAcquisition: Information: False MSAL 4.56.0.0 MSAL.NetCore .NET 6.0.23 Microsoft Windows 10.0.19045 [2023-10-16 15:37:27Z - 43f2aab0-3f31-42a6-ad4e-94622d556ac5] === Token Acquisition (SilentRequest) started:
	 Scopes: User.Read MailboxSettings.Read Calendars.ReadWrite
	Authority Host: login.microsoftonline.com
Microsoft.Identity.Web.TokenAcquisition: Warning: False MSAL 4.56.0.0 MSAL.NetCore .NET 6.0.23 Microsoft Windows 10.0.19045 [2023-10-16 15:37:27Z - 43f2aab0-3f31-42a6-ad4e-94622d556ac5] Only in-memory caching is used. The cache is not persisted and will be lost if the machine is restarted. It also does not scale for a web app or web API, where the number of users can grow large. In production, web apps and web APIs should use distributed caching like Redis. See https://aka.ms/msal-net-cca-token-cache-serialization
Exception thrown: 'Microsoft.Identity.Client.MsalUiRequiredException' in Microsoft.Identity.Client.dll
Exception thrown: 'Microsoft.Identity.Client.MsalUiRequiredException' in Microsoft.Identity.Client.dll
Exception thrown: 'Microsoft.Identity.Client.MsalUiRequiredException' in System.Private.CoreLib.dll
'GraphTutorial.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.23\System.Diagnostics.StackTrace.dll'. 
'GraphTutorial.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.23\System.Reflection.Metadata.dll'. 
Microsoft.Identity.Web.TokenAcquisition: Error: False MSAL 4.56.0.0 MSAL.NetCore .NET 6.0.23 Microsoft Windows 10.0.19045 [2023-10-16 15:37:27Z - 43f2aab0-3f31-42a6-ad4e-94622d556ac5] Exception type: Microsoft.Identity.Client.MsalUiRequiredException
, ErrorCode: user_null
HTTP StatusCode 0
CorrelationId 

   at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
Exception thrown: 'Microsoft.Identity.Client.MsalUiRequiredException' in Microsoft.Identity.Client.dll
Exception thrown: 'Microsoft.Identity.Client.MsalUiRequiredException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Identity.Client.MsalUiRequiredException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Identity.Client.MsalUiRequiredException' in System.Private.CoreLib.dll
Microsoft.Identity.Web.TokenAcquisition: Information: [MsIdWeb] An error occured during token acquisition: No account or login hint was passed to the AcquireTokenSilent call. 

MSAL.NetCore.4.56.0.0.MsalUiRequiredException: 
	ErrorCode: user_null
Microsoft.Identity.Client.MsalUiRequiredException: No account or login hint was passed to the AcquireTokenSilent call. 
   at Microsoft.Identity.Client.Internal.Requests.Silent.SilentRequest.ExecuteAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.ApiConfig.Executors.ClientApplicationBaseExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenSilentParameters silentParameters, CancellationToken cancellationToken)
   at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForWebAppWithAccountFromCacheAsync(IConfidentialClientApplication application, ClaimsPrincipal claimsPrincipal, IEnumerable`1 scopes, String tenantId, MergedOptions mergedOptions, String userFlow, TokenAcquisitionOptions tokenAcquisitionOptions)
   at Microsoft.Identity.Web.TokenAcquisition.GetAuthenticationResultForUserAsync(IEnumerable`1 scopes, String authenticationScheme, String tenantId, String userFlow, ClaimsPrincipal user, TokenAcquisitionOptions tokenAcquisitionOptions)
	StatusCode: 0 
	ResponseBody:  
	Headers: 
Exception thrown: 'Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException' in Microsoft.Identity.Web.TokenAcquisition.dll
Exception thrown: 'Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException' in System.Net.Http.dll
Exception thrown: 'Microsoft.Identity.Web.MicrosoftIdentityWebChallengeUserException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Graph.ServiceException' in Microsoft.Graph.Core.dll
Exception thrown: 'Microsoft.Graph.ServiceException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Graph.ServiceException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Graph.ServiceException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Graph.ServiceException' in System.Private.CoreLib.dll
Exception thrown: 'Microsoft.Graph.ServiceException' in System.Private.CoreLib.dll
GraphTutorial.Controllers.HomeController: Information: This just happened.
GraphTutorial.Controllers.HomeController: Information: User info: System.Security.Claims.ClaimsPrincipal
'GraphTutorial.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App\6.0.23\Microsoft.Extensions.Identity.Core.dll'. 

Not able to Signin to application using Personal(outlook) Account

Where did you get the code?

Describe the bug
First Of all thankyou for such great implementation. I am able to login to this application using my Company account ([email protected]) but unfortunately when I try using my personal account it gives me some error like "The size of the request headers is too long". I digged a little into this issue and found that during this process around 5 cookies are being created with a quiet large size and in various chunks. I tried increasing the request or header size using the web.config but the issue still persists. I am new to such things so a little help will be appreciated.

To Reproduce
Just Login to the application using your personal Microsoft Account.

Expected behavior
It Should Login to application and get User Info.

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows
  • Browser chrome, Opera

Dependency versions

  • Authentication library (MSAL, etc.) version:
  • Graph library (Graph SDK, REST library, etc.) version:

GetUtcStartOfWeekInTimeZone issue

Hi, I found an issue on this function.
I'm in Italy - TimeZone UTC +1

`// Assumes Sunday as first day of week
int diff = System.DayOfWeek.Sunday - today.DayOfWeek; > result: -2 (now is 27/10/2020 14:50 Tue)
var unspecifiedStart = DateTime.SpecifyKind(today.AddDays(diff), DateTimeKind.Unspecified); > result 25/10/2020 00:00

// convert to UTC
return TimeZoneInfo.ConvertTimeToUtc(unspecifiedStart, timeZone); >result 24/10/2020 22:00`

I have 2 problem:

  1. First day of the week is Saturday
  2. The Date Column and the Time column mismatching

image

I copied the code from here
https://docs.microsoft.com/en-us/graph/tutorials/aspnet-core?tutorial-step=6

Thank you

Sample crashes with `TimeZoneNotFoundException ` when run on macOS from AU

Timezone string returned by User.GetUserGraphTimeZone() (see CalendarController.cs#L37) on macOS is "AUS Eastern Standard Time".

When this is passed to TimeZoneInfo.FindSystemTimeZoneById() (see CalendarController.cs#L36) the sample is throwing a TimeZoneNotFoundException.

If I set a breakpoint and manually set the string returned by User.GetUserGraphTimeZone() to "Australia/Sydney" and continue, the sample runs without issue and the calendar page is filled out correctly.

Happy to raise issue on dotnet/runtime or another repo, if you can point me to the right one.

Screen Shot 2020-07-28 at 19 49 28

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.