Coder Social home page Coder Social logo

microsoftgraph / aspnet-connect-rest-sample Goto Github PK

View Code? Open in Web Editor NEW
63.0 44.0 57.0 723 KB

[ARCHIVED] This ASP.NET MVC sample shows how to connect to Microsoft Graph and use the API to send an email.

License: MIT License

C# 98.53% CSS 0.98% ASP 0.32% JavaScript 0.17%
devxsample

aspnet-connect-rest-sample's Introduction

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

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

Introduction

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 REST calls to interact with the Microsoft Graph API.

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 Application 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 (secret) 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.

Deploy the sample to Azure

If you have an Azure subscription, you can publish the sample app to an Azure website. These instructions assume you've already registered the sample app in the Application Registration Portal.

Create a web app (website) in the Azure Portal

  1. Sign into the Azure Portal with your Azure credentials.

  2. Choose New > Web + Mobile > Web App.

  3. Give the website a unique name. Choose a resource group, and click Create.

  4. Select the new web app in your list of resources.

  5. Choose Overview in the left-hand pane, and then choose Get publish profile (or More > Get publish profile) from the menu above the web app's Essentials pane.

  6. Save the profile locally.

Publish the sample app from Visual Studio

  1. In Visual Studio, open the sample app. Right-click the Microsoft Graph REST ASPNET Connect project node and choose Publish.

  2. In the Publish dialog, choose Import, and choose the publish profile file you just downloaded.

  3. On the Connection tab of the Publish dialog, change the http protocol to https in the Destination URL of your new web app.

  4. Copy the Destination URL, and and then click Publish. Close the browser window that opens.

  5. In the Web.config file, replace the ida:RedirectUri value to the Destination URL that you just copied.

  6. Choose View > Other Windows > Web Publish Activity.

  7. In the Web Publish Activity window, click the Publish Web button (looks like a globe) on the toolbar. This is how you can update the published project after you make changes.

Update the redirect URI in the Application Registration Portal

  1. In the Application Registration Portal, open the application that you registered for the sample (as described in Register the application).

  2. In the Web platform section, replace the http://localhost:55065/ Redirect URI with the Destination URL of your new web app. (Alternatively, you can click Add Url and add the Destination URL.)

  3. Click Save.

The new Azure web app should now be ready to use.

Code of note

  • 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.

  • GraphService.cs. Contains methods (called by HomeController) that build and send REST calls to the Microsoft Graph API, and 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-rest-sample's People

Contributors

andrewjmay avatar davidchesnut avatar jasonjoh avatar o365devx avatar ricalo avatar tadaomachida 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

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

aspnet-connect-rest-sample's Issues

An error occurred while processing your request. unsupported_response_type

Hi,

I got an error "unsupported_response_type". I already put the appId and appSecret on the Web.config. When the "Sign in with Microsoft" clicked, it redirected to Microsoft login page https://login.microsoftonline.com/common/oauth2/v2.0/. However, after e-mail field was filled, it redirected to the app home page with unsupported_response_type error. As suggested by other source, I already tried to add "/signin-microsoft" on the redirect URL, but doesn't work.

Thank you very much.

Get email address fails with "AADSTS70001: Application '<client_id>' is not supported for this API version"

I have a working web app in Azure and I would like it to be able to make Graph API calls.

I followed the instructions at https://github.com/microsoftgraph/aspnet-connect-rest-sample#build-and-run-the-sample and got the site running on localhost. However when I click the "Get email address" button, the sign-in fails and I'm redirected to the error page with this message: "AADSTS70001: Application '<my app's client id>' is not supported for this API version."

In Startup.Auth.cs I can see the AuthorizationCodeReceived handler being called. The cca.AcquireTokenByAuthorizationCodeAsync call throws a MsalServiceException which is caught and then handled by the AuthenticationFailed handler.

I suppose something is misconfigured in my web app, but I have no idea what it could be. Which "API version" is the message referring to? Is it the authentication API or the graph API? How do I determine which API version IS supported and how to call it?

Thanks,
:-DK

Sign in does not work.

I followed the instructions in the Readme. When I click the sign in link, it asks me to sign in but when I get to the home page, my userID is not listed in the nav bar. When I debug, It tells me that the Request.IsAuthenticated is false.

Any suggestions?

VB.Net version?

Hi,

Is there a VB.Net version of this somehwere?

Thanks in advance.

Rejected emails

Why would sending to myself at my onmicrosoft.com email address work, but sending to my GMail address gets rejected as "spam abuse detected"? When I use Office 365 Outlook to send to my GMail account, it goes through with no problem.

Forbidden 403: Retrieving all Planner Tasks using beta version of Microsoft Graph

Using this sample code I am trying to retrieve my planner tasks but I am getting the 403 forbidden error. I have checked all the permissions and have added the required permissions in application registration page and web config.
Is it a problem because I am using Beta version or should I give some additional permissions inside the code apart from ida:GraphScopes in web config.

The user or administrator has not consented to use the application with ID

Hello, I'm trying this example out to connect to my Azure AD App Registered account. I already have the necessary permissions granted by the administrator.

  1. When I try this example right out of the box I get the error: "Application ... is not supported over the /common or /consumers endpoints. Please use the /organizations or tenant-specific endpoint."
  2. So, to get around this I added the AADInstance value to the ConfidentialClientApplication constructor (2nd argument for Authority) that then gets me to the next error: "Message=AADSTS65001: The user or administrator has not consented to use the application with ID '...' named '...ToolSuite.Debug'. Send an interactive authorization request for this user and resource."

So, I understand that the user needs to consent to the usage but how do I do that through the code? I've read about using the parameter: "?prompt=admin_consent" but where do I put that? I've tried putting it on the Authority parameter but see that it get truncated before making the AcquireToken… call. How do I proceed?

Also, is the correct way to get access to Azure AD and Microsoft Graph API. I'm trying to get a list of the Azure AD Groups that the User belongs to. I see the GUIDs that return for the signed in user but that is all the information I get. Trying to get more information about the Groups. Thanks for you help.

Azure Web Application Microsoft Graph API Integration / Interoperation

The application works while in localhost - thank you for the notes and start with Microsoft Graph.
My next issue is getting this on Azure Web Application; of course, there are questions about this like the registration process, scope and authorization of the web application to the API. Can we add a "walkthrough" adding this application to Azure. I ask the question here because this is the only sample I've been able to get to work with Microsoft Graph on the localhost - so I want to publish it to Azure and see if I can get it to work there as an Azure Web Application. Thank you, Tim:

NuGet config causes project not to build

On a default installation of Visual Studio and NuGet, packages are downloaded to the CxCache folder. However, the csproj file in this repository references packages in a ..\packages folder. If you try to build this on a machine where you haven't redirected NuGet packages, you'll get an error:

This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props.

You can fix this by adding a Nuget.config file in the root that will ensure that for this solution packages are always downloaded into the ..\packages directory.

Getting Files returns empty list

I added a method to get the files from the root - and it returns an empty list. The same call in the Microsoft Graph Connect example site returns the full list of files.

public async Task GetFilesList(string accessToken)
{
string result = string.Empty;
string endpoint = "https://graph.microsoft.com/v1.0/me/drive/root/children";
string queryParameter = "";
using (var client = new HttpClient())
{
using (var request = new HttpRequestMessage(HttpMethod.Get, endpoint + queryParameter))
{
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove.
                request.Headers.Add("SampleID", "aspnet-connect-rest-sample");
                using (HttpResponseMessage response = await client.SendAsync(request))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        result = await response.Content.ReadAsStringAsync();
                    }
                    return result;
                }
            }
        }
    }

Send mail fails with "Forbidden"

I downloaded this sample code, registered it as an application in Azure Active Directory, gave it the required permissions - 'Sign in and read user profile' and 'Send mail as a user', and configured web.config with 'ClientID' and 'ClientSecret'. The application allows me to connect with Office 365, but returns "Forbidden" when I attempt to send email.

Using the VS2015 debugger I captured the AccessToken that I receive upon login, and decoded it with http://jwt.calebb.net/. It says the token provides "User.Read" permissions, and that's all.

Any thoughts on why I am not getting the permissions that I configured in AAD?

Multi-Tenant support

Hi,
how to make this application work with the multi tenant. I selected the Multitenant option in manage azure portal for this app, just as try but that did not worked. there are other sample application which demo about multi-tenant but i could not understood it properly..

how to make this app multitenant

exception handling

This happens sometimes, not all the time though.
When I run F5 with chrome and login and stop debugging and start again, sometimes the authentication is not successful. what I would like to see in the source code is a way to redirect the user to the login page instead so that I can eventually receive the accesstoken. Also I would like to see the code sample where something is done to the application so that the accesstoken stays alive while running. Curenlty it expires within an hour or so.

ASP.NET Core?

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

I haven't had much luck on converting these samples from MVC to .Net Core.

Unauthorized 401: Retrieving Inbox Mails using this project.

Using this sample code I am trying to retrieve my Inbox top 10 mail but I am getting the 401 Unauthorized error. I have added "Mail.Read" permission for Delegated Permissions and Application Permissions in registaration page and in web config I added "Mail.Read" in GraphScopes.
"Send Mail" and "Get Email Address" works fine with me , but not able to read Inbox mails.
Can anybody help me in this ?

No alerts

Hi
I deployed the application and all looks fine except whatever I do I don't get any alerts.
I noticed that it generates the Graph call so I tried to execute that directly on the graph explorer which also didn't return anything. However, when I tried to do it on the V2/Beta, it returned some info. So my question, why does the application shows the v1.0 query instead of the V2.0?

PS: Do I need to enter a fully qualified domain name?

Thanks

Jan

PS: I removed the username and the tenant id from the PNG file

graph

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.