Coder Social home page Coder Social logo

microsoftgraph / aspnet-connect-sample Goto Github PK

View Code? Open in Web Editor NEW
54.0 15.0 44.0 295 KB

[ARCHIVED] This walkthrough shows you how to use the Office 365 Connected Services in Visual Studio 2017.

License: MIT License

C# 98.04% CSS 1.30% ASP 0.42% JavaScript 0.23%
devxsample

aspnet-connect-sample's Introduction

[ARCHIVED] Microsoft Graph Connect Sample for ASP.NET 4.6

IMPORTANT

This project is being archived and replaced with the Build MVC apps with the Microsoft Graph .NET SDK training. As part of the archival process, we're closing all open issues and pull requests.

You can continue to use this sample "as-is", but it won't be maintained moving forward. We apologize for any inconvenience.

Table of contents

This sample shows how to connect an ASP.NET 4.6 MVC web app to a Microsoft work or school (Azure Active Directory) or personal (Microsoft) account using the Microsoft Graph API to retrieve a user's profile picture, upload the picture to OneDrive, and send an email that contains the photo as an attachment and the sharing link in its text. It uses the Microsoft Graph .NET Client Library to work with data returned by Microsoft Graph.

In addition, the sample uses the Microsoft Authentication Library (MSAL) for authentication. The MSAL SDK provides features for working with the Azure AD v2.0 endpoint, which enables developers to write a single code flow that handles authentication for both work or school (Azure Active Directory) and personal (Microsoft) accounts.

Important Note about the MSAL Preview

This library is suitable for use in a production environment. We provide the same production level support for this library as we do our current production libraries. During the preview we may make changes to the API, internal cache format, and other mechanisms of this library, which you will be required to take along with bug fixes or feature improvements. This may impact your application. For instance, a change to the cache format may impact your users, such as requiring them to sign in again. An API change may require you to update your code. When we provide the General Availability release we will require you to update to the General Availability version within six months, as applications written using a preview version of library may no longer work.

Prerequisites

This sample requires the following:

Register the application

  1. Sign into the App Registration Portal using either your personal or work or school account.

  2. Choose Add an app.

  3. Enter a name for the app, and choose Create application.

    The registration page displays, listing the properties of your app.

  4. Copy the Application Id. This is the unique identifier for your app.

  5. Under Application Secrets, choose Generate New Password. Copy the password from the New password generated dialog.

    You'll use the application ID and password to configure the sample app in the next section.

  6. Under Platforms, choose Add platform.

  7. Choose Web.

  8. Make sure the Allow Implicit Flow check box is selected, and enter http://localhost:55065/ as the Redirect URI.

    The Allow Implicit Flow option enables the hybrid flow. During authentication, this enables the app to receive both sign-in info (the id_token) and artifacts (in this case, an authorization code) that the app can use to obtain an access token.

  9. Choose Save.

Build and run the sample

  1. Download or clone the Microsoft Graph Connect Sample for ASP.NET 4.6.

  2. Open the sample solution in Visual Studio.

  3. In the Web.config file in the root directory, replace the ida:AppId and ida:AppSecret placeholder values with the application ID and password that you copied during app registration.

  4. Press F5 to build and run the sample. This will restore NuGet package dependencies and open the app.

    If you see any errors while installing packages, make sure the local path where you placed the solution is not too long/deep. Moving the solution closer to the root of your drive resolves this issue.

  5. Sign in with your personal or work or school account and grant the requested permissions.

  6. Choose the Get email address button. When the operation completes, the email address of the signed-in user is displayed on the page.

  7. Optionally edit the recipient list and email subject, and then choose the Send email button. When the mail is sent, a Success message is displayed below the button.

  8. Next steps: Check out the Microsoft Graph Snippets Sample for ASP.NET 4.6 to see examples of common Microsoft Graph operations.

Code of note

Note: To understand the code for calling the Microsoft Graph API in an ASP.NET MVC app, see Get started with Microsoft Graph in an ASP.NET 4.6 MVC app.

  • Startup.Auth.cs. Authenticates the current user and initializes the sample's token cache.

  • SessionTokenCache.cs. Stores the user's token information. You can replace this with your own custom token cache. Learn more in Caching access tokens in a multitenant application.

  • SampleAuthProvider.cs. Implements the local IAuthProvider interface, and gets an access token by using the MSAL AcquireTokenSilentAsync method. You can replace this with your own authentication provider.

  • SDKHelper.cs. Initializes the GraphServiceClient from the Microsoft Graph .NET Client Library that's used to interact with the Microsoft Graph.

  • HomeController.cs. Contains methods that use the GraphServiceClient to build and send calls to the Microsoft Graph service and to process the response.

    • The GetMyEmailAddress action gets the email address of the current user from the mail or userPrincipalName property.
    • The SendMail action sends an email on behalf of the current user.
  • Graph.cshtml. Contains the sample's UI.

Questions and comments

We'd love to get your feedback about this sample. You can send us your questions and suggestions in the Issues section of this repository.

Your feedback is important to us. Connect with us on Stack Overflow. Tag your questions with [MicrosoftGraph].

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.

Additional resources

Copyright

Copyright (c) 2016 Microsoft. All rights reserved.

aspnet-connect-sample's People

Contributors

jasonjoh avatar o365devx avatar officegsx avatar ricalo avatar v-dobr 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

Watchers

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

aspnet-connect-sample's Issues

Resource not found issue

I am able to get the Email Address form active directory. When i am trying send the mail to recipient it is throwing ServiceException.
Code: ResourceNotFound
Message: Resource could not be discovered.

Inner error null
Method:
await graphService.SendEmail(graphClient, message);

Users without organization email are rejected on sign in.

I am trying to create a B2B Management portal. But for some reason this sample does not let me sign in with any email adress. For example [email protected] does not work. Following error after sign-in:

AADSTS50020: User account '[email protected]' from external identity provider 'live.com' is not supported for api version '2.0'. Microsoft account pass-thru users and guests are not supported by the tenant-independent endpoint. Trace ID: 2ad8bee0-d00a-4896-9907-b5271a113300 Correlation ID: 0ea84617-4aa1-4830-859f-6f418252765e Timestamp: 2017-10-03 15:35:22Z

I changed the authority to only allow users from my tenant (requirement):
https://login.microsoftonline.com/tenant.onmicrosoft.com/v2.0

This is the only change I made. Using "common" will not work since that lets anyone in.

Invalid_Request Error

Dear Team

Firstly, I'd like to thank you for the great guide.

How to reproduce:

  1. Instead of registering the app in the link provided - I registered the app in the Azure Portal. I made a Key and made that my app secret. I also changed the manifest to allow multi tenant log in.
  2. All the rest I followed like in the guide.

I'm trying to learn how to use the Microsoft Graph API in order to manage users on multiple azure subscriptions. I'll be developing a small ASP.NET web application which will help me have a better sight on things.

Below is a screenshot of the error:
image

Thank you in advance

Exception thrown: 'Microsoft.Graph.ServiceException' in mscorlib.dll

how to reproduce

  1. I have setup a new application https://developer.microsoft.com/en-us/graph/quick-start?appID=[APP_ID]&appName=My%20ASP.NET%20App&redirectUrl=http://localhost:55065&platform=option-dotnet
  2. I have downloaded, unzipped and built the "aspnet-connect-sample-master.zip"
  3. I run the app
  4. I fill my credentials
  5. I hit 'send'

output

  1. "Success your email is sent " - see the screenshot
  2. on VS2017: Exception thrown: 'Microsoft.Graph.ServiceException' in mscorlib.dll

screenshot

emailnotsent

Group membership

Hi, I have tried to alter some of your and a lot of others code samples to be able to get back a list of group displayName's the user is a member of, but with no luck.

I know this is not a part of your sample application but still i need to ask you for guidance to get user group membership. I have tried since Build Conference to find out a way to get a list of Group names the user is member of and this sample has been one of the few found that is working querying the Graph API's. Hope you could share some solution or point me in the right direction

Just altering the endpoint in, for instance a copy of, the GetMyEmailAdress() function with

string endpoint = "https://graph.microsoft.com/v1.0/me/memberOf";
string queryParameter = "?$select=displayName";
and added Group.Read.All in the application settings in the Application Registration Portal.

does not do the trick!

the responce is instead of a successfull one
"
{StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
request-id: {Erased by me}
client-request-id: {Erased by me}
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"West Europe","Slice":"SliceB","ScaleUnit":"000","Host":"AGSFE_IN_6","ADSiteName":"AMS"}}
Duration: 93.3856
Cache-Control: private
Date: Sun, 22 Oct 2017 14:49:59 GMT
Content-Type: application/json
}}
"
and the responce.IsSuccessStatusCode = false.

I expected to get some Json back, since this string works perfectly in Graph Explorer
https://graph.microsoft.com/v1.0/me/memberOf?$select=displayName

Any clarification on this matter would be appreciated
Best Regards
/Patrik

task.Result never makes call or returns value

I have integrated this example into my application and have followed the code line by line and everything seems to be equivalent however, in the example app you put the email into the ViewBag using the following code

ViewBag.Email = await graphService.GetMyEmailAddress(graphClient);

in my application I am using the following:

String email = graphService.GetMyEmailAddress(graphClient).Result;

but the callout to the service endpoint never happens and this code never resumes - it is like it just ends abruptly (thread abort)

I am fairly new to the async / await pattern so I am assuming it has something to do with this - but based on my reading this should work

What am I doing wrong?

Thanks in advance.

HttpContext Session is null

I've implemented this code exactly as provided and am successfully authenticating against Azure Active Directory. I'm able to access the claims of the logged in user and see no issues there.

However, I'm getting an object reference exception when trying to use Graph in the SessionTokenCache.cs file where the httpContext.Session is null.

Why would this be? My web.config already contains runAllManagedModulesForAllRequests="true" in the modules section. I'm lost.

image

Get email address not working

Hello,

I'm having issues trying to get this sample to work.
I can login with my microsoft account, but when I click on "Get email address", I get a resource not found message.
The url the app is trying to call is /Home/GetMyEmailAddress.

Moreover, when I first tried to build the project, there was an error saying that "SDK Helper was not found", so I found a SDK Helper file somewhere else but the AccountController.cs file needed the SignOutClient() function to work properly. I just commented this line to test the other features without testing the signing out, but it would be nice to figure out how to get this to work.

Thanks

Stuck on login screen

I got stuck on login screen. Even after log in, when I press get email, I get redirected to login screen again, and it loops few times before I receive error in app:

Microsoft Graph Connect sample for ASP.NET 4.6
An error occurred while processing your request.
unsupported_response_type

Register application - Allow Implicit Flow - Can't Set

The documented steps under "Register the application" could not be followed through with success. At step 3, clicking on the ONLY active button, 'Edit in the Azure Portal', takes me to Azure portal for the newly created application (under Azure Active Directory), which is fine. There I could generate a key (and record the secret), but nowhere I could find UI controls/links/buttons to do steps 6-8 (Platform, Allow Implicit Flow).

Without that (and I did manually grant Microsoft Graph API explicit rights for app and user), the application simply returned 'unauthorized_client' after going through 'Sign in with Microsoft'.

Problem in authentication: change authentication URL

We have registered 2 different app one for development and one for production. We use only the authentication and send mail functionality.
In my test application I have some trouble in logon (we have received some "response_type 'token' is not supported for the application" and "unsupported_response_type".
Like explained in this article
https://docs.microsoft.com/en-gb/azure/active-directory/develop/active-directory-v2-protocols-oauth-code
we have:
1 - Add in web config the appsettings "ida:AppTenancy" with value as our tenancy domain
2 - Changed the the "Authority" property of the "OpenIdConnectAuthenticationOptions" in the method public void ConfigureAuth(IAppBuilder app) with the code:
Authority = string.Format("https://login.microsoftonline.com/{0}/v2.0",appTenancy),

For now its work.
LSo

Support for multiple IDP(s)

I have the example application integrated into my application, however, I need to be able to support multiple Identity Providers, the example pretty much intercepts all requests and assumes that it needs to authenticate with Graph

How can I layer in support for multiple providers (Graph, Google and forms authentication - fallback for internal admin users that do not have either)

Ideally I should be able to let the user decide what identity provider to use - therefore the application should be able to handle that situation.

Permissions Error When Hosted on Azure

Hello, I'm trying to wrap my head around using Microsoft Graph for an app that will need to be hosted on Azure. I took the sample app and published it to an Azure app I own. I will be using Azure AD so I set up an AD app as well (putting the app id and secret in my web app's web.config using your instructions). I can launch the app fine. I click on "Get email address" and I get sent to a login page. When I log in via my (Microsoft) account I am presented with the following:
You do not have permission to view this directory or page.

Any idea what I might be doing wrong?

My end goal is to simply check to see if a user is a member of a specific group and if not, kick them out. I'm thinking I can use GraphServiceClient.Me.CheckMemberGroups. Am I right here? Any help you can offer would be wonderful.

Integration with ASP.Net WebForms app

I am trying to integrate the example into an existing ASP.Net WebPages.

The example APP works fine, however, when I try and integrate it into my application I can't get the API controller method to get called and based on my debugging so far the routes are null. I am fairly positive it is because the ASP handler / modules are interfering with the MVC controller handlers / modules but can't figure out how to effectively debug this - it is not a routing problem per se, but the fact that the routes are null

Any hints on how to trouble-shoot this or does anyone have a working example that includes integration with aspx pages based application.

Thanks in advance.

Whatty

Cannot signin to app

After downloading this app through the Graph Quick Start page, the sign in experience fails. After granting consent, it redirects to a page not found error.

The problem seems to be that the app runs locally on port 21942, but the app is registered in the app portal to use port 55065 (and that's set in the web.config as well).

Multiple redirect url's

At first, I dont know if this is the place to ask this question, so I hope it is.

If I create an app only the first redirect url works.

For example; if I add https://google.com/ first this url works but if I add https://localhost/ it does not.
When I add https://localhost/ first and https://google.com/ second, only the localhost url works.

The only way to make everything work is to create two separate applications in the "Application registration portal". One for the development environment and one for production.

It feels like some cache issue, but I could also be a stupid mistake of me of course.

(I change the "PostLogoutRedirectUri" in my web.config to the right one when I switch to another environment)

The SDKHelper graph client cache does not

Note that the graph client instance is being generated new every time - the private static "graphClient" variable is never used. As a consequence, the SignOutClient method does nothing.

ASP.NET Core?

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

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.