├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── Microsoft Graph SDK ASPNET Connect ├── Microsoft Graph SDK ASPNET Connect.sln └── Microsoft Graph SDK ASPNET Connect │ ├── App_GlobalResources │ ├── Resource.Designer.cs │ └── Resource.resx │ ├── App_Start │ ├── BundleConfig.cs │ ├── FilterConfig.cs │ ├── RouteConfig.cs │ └── Startup.Auth.cs │ ├── Content │ ├── Site.css │ └── test.jpg │ ├── Controllers │ ├── AccountController.cs │ ├── ErrorController.cs │ └── HomeController.cs │ ├── Global.asax │ ├── Global.asax.cs │ ├── Helpers │ ├── IAuthProvider.cs │ ├── SDKHelper.cs │ └── SampleAuthProvider.cs │ ├── Microsoft Graph SDK ASPNET Connect.csproj │ ├── Models │ └── GraphService.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── Scripts │ └── _references.js │ ├── Startup.cs │ ├── TokenStorage │ └── SessionTokenCache.cs │ ├── Views │ ├── Home │ │ ├── About.cshtml │ │ └── Graph.cshtml │ ├── Shared │ │ ├── Error.cshtml │ │ ├── _Layout.cshtml │ │ └── _LoginPartial.cshtml │ ├── Web.config │ └── _ViewStart.cshtml │ ├── Web.Debug.config │ ├── Web.Release.config │ ├── Web.config │ ├── favicon.ico │ ├── fonts │ ├── glyphicons-halflings-regular.eot │ ├── glyphicons-halflings-regular.svg │ ├── glyphicons-halflings-regular.ttf │ ├── glyphicons-halflings-regular.woff │ └── glyphicons-halflings-regular.woff2 │ └── packages.config ├── README-Localized ├── README-de-de.md ├── README-es-es.md ├── README-fr-fr.md ├── README-ja-jp.md ├── README-pt-br.md ├── README-ru-ru.md ├── README-zh-cn.md └── README-zh-tw.md ├── README.md ├── aspnet-connect-sample.yml └── starter-project ├── Microsoft Graph SDK ASPNET Connect.sln ├── Microsoft Graph SDK ASPNET Connect ├── App_GlobalResources │ ├── Resource.Designer.cs │ └── Resource.resx ├── App_Start │ ├── BundleConfig.cs │ ├── FilterConfig.cs │ ├── RouteConfig.cs │ └── Startup.Auth.cs ├── Content │ ├── Site.css │ └── test.jpg ├── Controllers │ ├── AccountController.cs │ ├── ErrorController.cs │ └── HomeController.cs ├── Global.asax ├── Global.asax.cs ├── Helpers │ ├── IAuthProvider.cs │ └── SampleAuthProvider.cs ├── Microsoft Graph SDK ASPNET Connect.csproj ├── Models │ └── GraphService.cs ├── Properties │ └── AssemblyInfo.cs ├── Scripts │ └── _references.js ├── Startup.cs ├── TokenStorage │ └── SessionTokenCache.cs ├── Views │ ├── Home │ │ ├── About.cshtml │ │ └── Graph.cshtml │ ├── Shared │ │ ├── Error.cshtml │ │ ├── _Layout.cshtml │ │ └── _LoginPartial.cshtml │ ├── Web.config │ └── _ViewStart.cshtml ├── Web.config ├── favicon.ico ├── fonts │ ├── glyphicons-halflings-regular.eot │ ├── glyphicons-halflings-regular.svg │ ├── glyphicons-halflings-regular.ttf │ ├── glyphicons-halflings-regular.woff │ └── glyphicons-halflings-regular.woff2 └── packages.config └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | 24 | # Visual Studio 2015 cache/options directory 25 | .vs/ 26 | # Uncomment if you have tasks that create the project's static files in wwwroot 27 | #wwwroot/ 28 | 29 | # MSTest test Results 30 | [Tt]est[Rr]esult*/ 31 | [Bb]uild[Ll]og.* 32 | 33 | # NUNIT 34 | *.VisualState.xml 35 | TestResult.xml 36 | 37 | # Build Results of an ATL Project 38 | [Dd]ebugPS/ 39 | [Rr]eleasePS/ 40 | dlldata.c 41 | 42 | # DNX 43 | project.lock.json 44 | artifacts/ 45 | 46 | *_i.c 47 | *_p.c 48 | *_i.h 49 | *.ilk 50 | *.meta 51 | *.obj 52 | *.pch 53 | *.pdb 54 | *.pgc 55 | *.pgd 56 | *.rsp 57 | *.sbr 58 | *.tlb 59 | *.tli 60 | *.tlh 61 | *.tmp 62 | *.tmp_proj 63 | *.log 64 | *.vspscc 65 | *.vssscc 66 | .builds 67 | *.pidb 68 | *.svclog 69 | *.scc 70 | 71 | # Chutzpah Test files 72 | _Chutzpah* 73 | 74 | # Visual C++ cache files 75 | ipch/ 76 | *.aps 77 | *.ncb 78 | *.opendb 79 | *.opensdf 80 | *.sdf 81 | *.cachefile 82 | 83 | # Visual Studio profiler 84 | *.psess 85 | *.vsp 86 | *.vspx 87 | *.sap 88 | 89 | # TFS 2012 Local Workspace 90 | $tf/ 91 | 92 | # Guidance Automation Toolkit 93 | *.gpState 94 | 95 | # ReSharper is a .NET coding add-in 96 | _ReSharper*/ 97 | *.[Rr]e[Ss]harper 98 | *.DotSettings.user 99 | 100 | # JustCode is a .NET coding add-in 101 | .JustCode 102 | 103 | # TeamCity is a build add-in 104 | _TeamCity* 105 | 106 | # DotCover is a Code Coverage Tool 107 | *.dotCover 108 | 109 | # NCrunch 110 | _NCrunch_* 111 | .*crunch*.local.xml 112 | nCrunchTemp_* 113 | 114 | # MightyMoose 115 | *.mm.* 116 | AutoTest.Net/ 117 | 118 | # Web workbench (sass) 119 | .sass-cache/ 120 | 121 | # Installshield output folder 122 | [Ee]xpress/ 123 | 124 | # DocProject is a documentation generator add-in 125 | DocProject/buildhelp/ 126 | DocProject/Help/*.HxT 127 | DocProject/Help/*.HxC 128 | DocProject/Help/*.hhc 129 | DocProject/Help/*.hhk 130 | DocProject/Help/*.hhp 131 | DocProject/Help/Html2 132 | DocProject/Help/html 133 | 134 | # Click-Once directory 135 | publish/ 136 | 137 | # Publish Web Output 138 | *.[Pp]ublish.xml 139 | *.azurePubxml 140 | # TODO: Comment the next line if you want to checkin your web deploy settings 141 | # but database connection strings (with potential passwords) will be unencrypted 142 | *.pubxml 143 | *.publishproj 144 | 145 | # NuGet Packages 146 | *.nupkg 147 | # The packages folder can be ignored because of Package Restore 148 | **/packages/* 149 | # except build/, which is used as an MSBuild target. 150 | !**/packages/build/ 151 | # Uncomment if necessary however generally it will be regenerated when needed 152 | #!**/packages/repositories.config 153 | # NuGet v3's project.json files produces more ignoreable files 154 | *.nuget.props 155 | *.nuget.targets 156 | 157 | # Microsoft Azure Build Output 158 | csx/ 159 | *.build.csdef 160 | 161 | # Microsoft Azure Emulator 162 | ecf/ 163 | rcf/ 164 | 165 | # Microsoft Azure ApplicationInsights config file 166 | ApplicationInsights.config 167 | 168 | # Windows Store app package directory 169 | AppPackages/ 170 | BundleArtifacts/ 171 | 172 | # Visual Studio cache files 173 | # files ending in .cache can be ignored 174 | *.[Cc]ache 175 | # but keep track of directories ending in .cache 176 | !*.[Cc]ache/ 177 | 178 | # Others 179 | ClientBin/ 180 | ~$* 181 | *~ 182 | *.dbmdl 183 | *.dbproj.schemaview 184 | *.pfx 185 | *.publishsettings 186 | node_modules/ 187 | orleans.codegen.cs 188 | 189 | # RIA/Silverlight projects 190 | Generated_Code/ 191 | 192 | # Backup & report files from converting an old project file 193 | # to a newer Visual Studio version. Backup files are not needed, 194 | # because we have git ;-) 195 | _UpgradeReport_Files/ 196 | Backup*/ 197 | UpgradeLog*.XML 198 | UpgradeLog*.htm 199 | 200 | # SQL Server files 201 | *.mdf 202 | *.ldf 203 | 204 | # Business Intelligence projects 205 | *.rdl.data 206 | *.bim.layout 207 | *.bim_*.settings 208 | 209 | # Microsoft Fakes 210 | FakesAssemblies/ 211 | 212 | # GhostDoc plugin setting file 213 | *.GhostDoc.xml 214 | 215 | # Node.js Tools for Visual Studio 216 | .ntvs_analysis.dat 217 | 218 | # Visual Studio 6 build log 219 | *.plg 220 | 221 | # Visual Studio 6 workspace options file 222 | *.opt 223 | 224 | # Visual Studio LightSwitch build output 225 | **/*.HTMLClient/GeneratedArtifacts 226 | **/*.DesktopClient/GeneratedArtifacts 227 | **/*.DesktopClient/ModelManifest.xml 228 | **/*.Server/GeneratedArtifacts 229 | **/*.Server/ModelManifest.xml 230 | _Pvt_Extensions 231 | 232 | # Paket dependency manager 233 | .paket/paket.exe 234 | 235 | # FAKE - F# Make 236 | .fake/ 237 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/CONTRIBUTING.md -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Microsoft Corporation 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26730.16 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft Graph SDK ASPNET Connect", "Microsoft Graph SDK ASPNET Connect\Microsoft Graph SDK ASPNET Connect.csproj", "{26148A63-47CC-4A3E-896D-12992A40A89A}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {26148A63-47CC-4A3E-896D-12992A40A89A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {26148A63-47CC-4A3E-896D-12992A40A89A}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {26148A63-47CC-4A3E-896D-12992A40A89A}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {26148A63-47CC-4A3E-896D-12992A40A89A}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {91A39FAA-4FDD-4813-A3A3-F659F9CA34A3} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/App_GlobalResources/Resource.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace Resources { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option or rebuild the Visual Studio project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Web.Application.StronglyTypedResourceProxyBuilder", "15.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resource { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resource() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Resources.Resource", global::System.Reflection.Assembly.Load("App_GlobalResources")); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | 63 | /// 64 | /// Looks up a localized string similar to About. 65 | /// 66 | internal static string About { 67 | get { 68 | return ResourceManager.GetString("About", resourceCulture); 69 | } 70 | } 71 | 72 | /// 73 | /// Looks up a localized string similar to Your application description page.. 74 | /// 75 | internal static string About_Description { 76 | get { 77 | return ResourceManager.GetString("About_Description", resourceCulture); 78 | } 79 | } 80 | 81 | /// 82 | /// Looks up a localized string similar to Microsoft Graph Connect sample for ASP.NET 4.6. 83 | /// 84 | internal static string App_Name { 85 | get { 86 | return ResourceManager.GetString("App_Name", resourceCulture); 87 | } 88 | } 89 | 90 | /// 91 | /// Looks up a localized string similar to Microsoft Graph Connect sample. 92 | /// 93 | internal static string App_Name_Short { 94 | get { 95 | return ResourceManager.GetString("App_Name_Short", resourceCulture); 96 | } 97 | } 98 | 99 | /// 100 | /// Looks up a localized string similar to Caller needs to authenticate.. 101 | /// 102 | internal static string Error_AuthChallengeNeeded { 103 | get { 104 | return ResourceManager.GetString("Error_AuthChallengeNeeded", resourceCulture); 105 | } 106 | } 107 | 108 | /// 109 | /// Looks up a localized string similar to An error occurred while processing your request.. 110 | /// 111 | internal static string Error_Introduction { 112 | get { 113 | return ResourceManager.GetString("Error_Introduction", resourceCulture); 114 | } 115 | } 116 | 117 | /// 118 | /// Looks up a localized string similar to Error in . 119 | /// 120 | internal static string Error_Message { 121 | get { 122 | return ResourceManager.GetString("Error_Message", resourceCulture); 123 | } 124 | } 125 | 126 | /// 127 | /// Looks up a localized string similar to Get email address. 128 | /// 129 | internal static string Graph_GetEmailAddress_Button { 130 | get { 131 | return ResourceManager.GetString("Graph_GetEmailAddress_Button", resourceCulture); 132 | } 133 | } 134 | 135 | /// 136 | /// Looks up a localized string similar to Get email address. 137 | /// 138 | internal static string Graph_GetEmailAddress_Heading { 139 | get { 140 | return ResourceManager.GetString("Graph_GetEmailAddress_Heading", resourceCulture); 141 | } 142 | } 143 | 144 | /// 145 | /// Looks up a localized string similar to Choose the <b>Get email address</b> button to get the current user's email address:. 146 | /// 147 | internal static string Graph_GetEmailAddress_Instruction { 148 | get { 149 | return ResourceManager.GetString("Graph_GetEmailAddress_Instruction", resourceCulture); 150 | } 151 | } 152 | 153 | /// 154 | /// Looks up a localized string similar to Current user's email address. 155 | /// 156 | internal static string Graph_GetEmailAddress_Results_Label { 157 | get { 158 | return ResourceManager.GetString("Graph_GetEmailAddress_Results_Label", resourceCulture); 159 | } 160 | } 161 | 162 | /// 163 | /// Looks up a localized string similar to <html><head> 164 | ///<meta http-equiv='Content-Type' content='text/html; charset=us-ascii'> 165 | ///<title></title> 166 | ///</head> 167 | ///<body style='font-family:calibri'> 168 | ///<h2>Congratulations!</h2> 169 | ///<p>This is a message from the Microsoft Graph Connect Sample. You are well on your way to incorporating Microsoft Graph endpoints in your apps.</p><a href='{0}'>See the photo you just uploaded!</a> 170 | ///<h3>What's next?</h3><ul> 171 | ///<li>Check out <a href='https://developer.microsoft.com/graph'>developer.microsoft.com/graph</a> to start buildi [rest of string was truncated]";. 172 | /// 173 | internal static string Graph_SendMail_Body_Content { 174 | get { 175 | return ResourceManager.GetString("Graph_SendMail_Body_Content", resourceCulture); 176 | } 177 | } 178 | 179 | /// 180 | /// Looks up a localized string similar to Send email. 181 | /// 182 | internal static string Graph_SendMail_Button { 183 | get { 184 | return ResourceManager.GetString("Graph_SendMail_Button", resourceCulture); 185 | } 186 | } 187 | 188 | /// 189 | /// Looks up a localized string similar to Send an email. 190 | /// 191 | internal static string Graph_SendMail_Heading { 192 | get { 193 | return ResourceManager.GetString("Graph_SendMail_Heading", resourceCulture); 194 | } 195 | } 196 | 197 | /// 198 | /// Looks up a localized string similar to After you get the email address, optionally change the following fields and then choose the <b>Send email</b> button:. 199 | /// 200 | internal static string Graph_SendMail_Instruction { 201 | get { 202 | return ResourceManager.GetString("Graph_SendMail_Instruction", resourceCulture); 203 | } 204 | } 205 | 206 | /// 207 | /// Looks up a localized string similar to Please choose the <b>Get email address</b> button first.. 208 | /// 209 | internal static string Graph_SendMail_Message_GetEmailFirst { 210 | get { 211 | return ResourceManager.GetString("Graph_SendMail_Message_GetEmailFirst", resourceCulture); 212 | } 213 | } 214 | 215 | /// 216 | /// Looks up a localized string similar to Recipient email addresses, separated by a semicolon. 217 | /// 218 | internal static string Graph_SendMail_Recipients_Label { 219 | get { 220 | return ResourceManager.GetString("Graph_SendMail_Recipients_Label", resourceCulture); 221 | } 222 | } 223 | 224 | /// 225 | /// Looks up a localized string similar to Subject of email. 226 | /// 227 | internal static string Graph_SendMail_Subject_Label { 228 | get { 229 | return ResourceManager.GetString("Graph_SendMail_Subject_Label", resourceCulture); 230 | } 231 | } 232 | 233 | /// 234 | /// Looks up a localized string similar to Sent from the. 235 | /// 236 | internal static string Graph_SendMail_Subject_Text { 237 | get { 238 | return ResourceManager.GetString("Graph_SendMail_Subject_Text", resourceCulture); 239 | } 240 | } 241 | 242 | /// 243 | /// Looks up a localized string similar to Success! Your mail was sent.. 244 | /// 245 | internal static string Graph_SendMail_Success_Result { 246 | get { 247 | return ResourceManager.GetString("Graph_SendMail_Success_Result", resourceCulture); 248 | } 249 | } 250 | 251 | /// 252 | /// Looks up a localized string similar to Home. 253 | /// 254 | internal static string Home { 255 | get { 256 | return ResourceManager.GetString("Home", resourceCulture); 257 | } 258 | } 259 | 260 | /// 261 | /// Looks up a localized string similar to Sign in with Microsoft. 262 | /// 263 | internal static string SignIn { 264 | get { 265 | return ResourceManager.GetString("SignIn", resourceCulture); 266 | } 267 | } 268 | 269 | /// 270 | /// Looks up a localized string similar to Sign out. 271 | /// 272 | internal static string SignOut { 273 | get { 274 | return ResourceManager.GetString("SignOut", resourceCulture); 275 | } 276 | } 277 | } 278 | } 279 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/App_Start/BundleConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Optimization; 3 | 4 | namespace Microsoft_Graph_SDK_ASPNET_Connect 5 | { 6 | public class BundleConfig 7 | { 8 | // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 9 | public static void RegisterBundles(BundleCollection bundles) 10 | { 11 | bundles.Add(new StyleBundle("~/Content/css").Include( 12 | "~/Content/site.css")); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/App_Start/FilterConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Mvc; 3 | 4 | namespace Microsoft_Graph_SDK_ASPNET_Connect 5 | { 6 | public class FilterConfig 7 | { 8 | public static void RegisterGlobalFilters(GlobalFilterCollection filters) 9 | { 10 | filters.Add(new HandleErrorAttribute()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/App_Start/RouteConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | using System.Web.Routing; 7 | 8 | namespace Microsoft_Graph_SDK_ASPNET_Connect 9 | { 10 | public class RouteConfig 11 | { 12 | public static void RegisterRoutes(RouteCollection routes) 13 | { 14 | routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 15 | 16 | routes.MapRoute( 17 | name: "Default", 18 | url: "{controller}/{action}/{id}", 19 | defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 20 | ); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/App_Start/Startup.Auth.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System.Web; 7 | using Owin; 8 | using Microsoft.Owin.Security; 9 | using Microsoft.Owin.Security.Cookies; 10 | using Microsoft.Owin.Security.OpenIdConnect; 11 | using System.Configuration; 12 | using System.Threading.Tasks; 13 | using Microsoft_Graph_SDK_ASPNET_Connect.TokenStorage; 14 | using System.IdentityModel.Tokens; 15 | using System.IdentityModel.Claims; 16 | using Microsoft.Identity.Client; 17 | 18 | namespace Microsoft_Graph_SDK_ASPNET_Connect 19 | { 20 | public partial class Startup 21 | { 22 | 23 | // The appId is used by the application to uniquely identify itself to Azure AD. 24 | // The appSecret is the application's password. 25 | // The redirectUri is where users are redirected after sign in and consent. 26 | // The graphScopes are the Microsoft Graph permission scopes that are used by this sample: User.Read Mail.Send 27 | private static string appId = ConfigurationManager.AppSettings["ida:AppId"]; 28 | private static string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"]; 29 | private static string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"]; 30 | private static string graphScopes = ConfigurationManager.AppSettings["ida:GraphScopes"]; 31 | 32 | public void ConfigureAuth(IAppBuilder app) 33 | { 34 | app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); 35 | 36 | app.UseCookieAuthentication(new CookieAuthenticationOptions()); 37 | 38 | app.UseOpenIdConnectAuthentication( 39 | new OpenIdConnectAuthenticationOptions 40 | { 41 | 42 | // The `Authority` represents the Microsoft v2.0 authentication and authorization service. 43 | // The `Scope` describes the permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/ 44 | ClientId = appId, 45 | Authority = "https://login.microsoftonline.com/common/v2.0", 46 | PostLogoutRedirectUri = redirectUri, 47 | RedirectUri = redirectUri, 48 | Scope = "openid email profile offline_access " + graphScopes, 49 | TokenValidationParameters = new TokenValidationParameters 50 | { 51 | ValidateIssuer = false, 52 | // In a real application you would use IssuerValidator for additional checks, 53 | // like making sure the user's organization has signed up for your app. 54 | // IssuerValidator = (issuer, token, tvp) => 55 | // { 56 | // if (MyCustomTenantValidation(issuer)) 57 | // return issuer; 58 | // else 59 | // throw new SecurityTokenInvalidIssuerException("Invalid issuer"); 60 | // }, 61 | }, 62 | Notifications = new OpenIdConnectAuthenticationNotifications 63 | { 64 | AuthorizationCodeReceived = async (context) => 65 | { 66 | var code = context.Code; 67 | string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; 68 | 69 | TokenCache userTokenCache = new SessionTokenCache(signedInUserID, 70 | context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); 71 | ConfidentialClientApplication cca = new ConfidentialClientApplication( 72 | appId, 73 | redirectUri, 74 | new ClientCredential(appSecret), 75 | userTokenCache, 76 | null); 77 | string[] scopes = graphScopes.Split(new char[] { ' ' }); 78 | 79 | AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes); 80 | }, 81 | AuthenticationFailed = (context) => 82 | { 83 | context.HandleResponse(); 84 | context.Response.Redirect("/Error?message=" + context.Exception.Message); 85 | return Task.FromResult(0); 86 | } 87 | } 88 | }); 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Content/Site.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 50px; 3 | padding-bottom: 20px; 4 | } 5 | 6 | /* Set padding to keep content from hitting the edges */ 7 | .body-content { 8 | padding-left: 15px; 9 | padding-right: 15px; 10 | } 11 | 12 | /* Override the default bootstrap behavior where horizontal description lists 13 | will truncate terms that are too long to fit in the left column 14 | */ 15 | .dl-horizontal dt { 16 | white-space: normal; 17 | } 18 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Content/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Content/test.jpg -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System.Web; 7 | using System.Web.Mvc; 8 | using Microsoft.Owin.Security; 9 | using Microsoft.Owin.Security.Cookies; 10 | using Microsoft.Owin.Security.OpenIdConnect; 11 | using Microsoft_Graph_SDK_ASPNET_Connect.TokenStorage; 12 | using Microsoft_Graph_SDK_ASPNET_Connect.Helpers; 13 | using System.Security.Claims; 14 | 15 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Controllers 16 | { 17 | public class AccountController : Controller 18 | { 19 | public void SignIn() 20 | { 21 | if (!Request.IsAuthenticated) 22 | { 23 | // Signal OWIN to send an authorization request to Azure. 24 | HttpContext.GetOwinContext().Authentication.Challenge( 25 | new AuthenticationProperties { RedirectUri = "/" }, 26 | OpenIdConnectAuthenticationDefaults.AuthenticationType); 27 | } 28 | } 29 | 30 | // Here we just clear the token cache, sign out the GraphServiceClient, and end the session with the web app. 31 | public void SignOut() 32 | { 33 | if (Request.IsAuthenticated) 34 | { 35 | // Get the user's token cache and clear it. 36 | string userObjectId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; 37 | 38 | SessionTokenCache tokenCache = new SessionTokenCache(userObjectId, HttpContext); 39 | HttpContext.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); 40 | } 41 | 42 | // Send an OpenID Connect sign-out request. 43 | HttpContext.GetOwinContext().Authentication.SignOut( 44 | CookieAuthenticationDefaults.AuthenticationType); 45 | Response.Redirect("/"); 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Controllers/ErrorController.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System.Web.Mvc; 7 | 8 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Controllers 9 | { 10 | public class ErrorController : Controller 11 | { 12 | // GET: Error 13 | public ActionResult Index(string message) 14 | { 15 | ViewBag.Message = message; 16 | return View("Error"); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System.Threading.Tasks; 7 | using System.Web.Mvc; 8 | using Microsoft.Graph; 9 | using Microsoft_Graph_SDK_ASPNET_Connect.Helpers; 10 | using Microsoft_Graph_SDK_ASPNET_Connect.Models; 11 | using Resources; 12 | 13 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Controllers 14 | { 15 | public class HomeController : Controller 16 | { 17 | GraphService graphService = new GraphService(); 18 | 19 | public ActionResult Index() 20 | { 21 | return View("Graph"); 22 | } 23 | 24 | [Authorize] 25 | // Get the current user's email address from their profile. 26 | public async Task GetMyEmailAddress() 27 | { 28 | try 29 | { 30 | 31 | // Initialize the GraphServiceClient. 32 | GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient(); 33 | 34 | // Get the current user's email address. 35 | ViewBag.Email = await graphService.GetMyEmailAddress(graphClient); 36 | return View("Graph"); 37 | } 38 | catch (ServiceException se) 39 | { 40 | if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult(); 41 | return RedirectToAction("Index", "Error", new { message = Resource.Error_Message + Request.RawUrl + ": " + se.Error.Message }); 42 | } 43 | } 44 | 45 | [Authorize] 46 | // Send mail on behalf of the current user. 47 | public async Task SendEmail() 48 | { 49 | if (string.IsNullOrEmpty(Request.Form["email-address"])) 50 | { 51 | ViewBag.Message = Resource.Graph_SendMail_Message_GetEmailFirst; 52 | return View("Graph"); 53 | } 54 | 55 | try 56 | { 57 | 58 | // Initialize the GraphServiceClient. 59 | GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient(); 60 | 61 | // Build the email message. 62 | Message message = await graphService.BuildEmailMessage(graphClient, Request.Form["recipients"], Request.Form["subject"]); 63 | 64 | // Send the email. 65 | await graphService.SendEmail(graphClient, message); 66 | 67 | // Reset the current user's email address and the status to display when the page reloads. 68 | ViewBag.Email = Request.Form["email-address"]; 69 | ViewBag.Message = Resource.Graph_SendMail_Success_Result; 70 | return View("Graph"); 71 | } 72 | catch (ServiceException se) 73 | { 74 | if (se.Error.Code == Resource.Error_AuthChallengeNeeded) return new EmptyResult(); 75 | return RedirectToAction("Index", "Error", new { message = Resource.Error_Message + Request.RawUrl + ": " + se.Error.Message }); 76 | } 77 | } 78 | 79 | public ActionResult About() 80 | { 81 | return View(); 82 | } 83 | } 84 | } -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Global.asax: -------------------------------------------------------------------------------- 1 | <%@ Application Codebehind="Global.asax.cs" Inherits="Microsoft_Graph_SDK_ASPNET_Connect.MvcApplication" Language="C#" %> 2 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Global.asax.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | using System.Web.Optimization; 7 | using System.Web.Routing; 8 | 9 | namespace Microsoft_Graph_SDK_ASPNET_Connect 10 | { 11 | public class MvcApplication : System.Web.HttpApplication 12 | { 13 | protected void Application_Start() 14 | { 15 | AreaRegistration.RegisterAllAreas(); 16 | FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 17 | RouteConfig.RegisterRoutes(RouteTable.Routes); 18 | BundleConfig.RegisterBundles(BundleTable.Bundles); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Helpers/IAuthProvider.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Helpers 9 | { 10 | public interface IAuthProvider 11 | { 12 | Task GetUserAccessTokenAsync(); 13 | } 14 | } -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Helpers/SDKHelper.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System.Net.Http.Headers; 7 | using Microsoft.Graph; 8 | 9 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Helpers 10 | { 11 | public class SDKHelper 12 | { 13 | 14 | // Get an authenticated Microsoft Graph Service client. 15 | public static GraphServiceClient GetAuthenticatedClient() 16 | { 17 | GraphServiceClient graphClient = new GraphServiceClient( 18 | new DelegateAuthenticationProvider( 19 | async (requestMessage) => 20 | { 21 | string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync(); 22 | 23 | // Append the access token to the request. 24 | requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken); 25 | 26 | // This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove. 27 | requestMessage.Headers.Add("SampleID", "aspnet-connect-sample"); 28 | })); 29 | return graphClient; 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Helpers/SampleAuthProvider.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using Microsoft.Identity.Client; 7 | using Microsoft.Owin.Security; 8 | using Microsoft.Owin.Security.OpenIdConnect; 9 | using Microsoft_Graph_SDK_ASPNET_Connect.TokenStorage; 10 | using System.Collections.Generic; 11 | using System.Configuration; 12 | using System.Linq; 13 | using System.Security.Claims; 14 | using System.Threading.Tasks; 15 | using System.Web; 16 | using Microsoft.Graph; 17 | using Resources; 18 | using System; 19 | 20 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Helpers 21 | { 22 | public sealed class SampleAuthProvider : IAuthProvider 23 | { 24 | 25 | // Properties used to get and manage an access token. 26 | private string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"]; 27 | private string appId = ConfigurationManager.AppSettings["ida:AppId"]; 28 | private string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"]; 29 | private string scopes = ConfigurationManager.AppSettings["ida:GraphScopes"]; 30 | private SessionTokenCache tokenCache { get; set; } 31 | 32 | private static readonly SampleAuthProvider instance = new SampleAuthProvider(); 33 | private SampleAuthProvider() { } 34 | 35 | public static SampleAuthProvider Instance 36 | { 37 | get 38 | { 39 | return instance; 40 | } 41 | } 42 | 43 | // Gets an access token. First tries to get the token from the token cache. 44 | public async Task GetUserAccessTokenAsync() 45 | { 46 | string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; 47 | HttpContextWrapper httpContext = new HttpContextWrapper(HttpContext.Current); 48 | TokenCache userTokenCache = new SessionTokenCache(signedInUserID, httpContext).GetMsalCacheInstance(); 49 | //var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache 50 | 51 | ConfidentialClientApplication cca = new ConfidentialClientApplication( 52 | appId, 53 | redirectUri, 54 | new ClientCredential(appSecret), 55 | userTokenCache, 56 | null); 57 | 58 | try 59 | { 60 | AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }), cca.Users.First()); 61 | return result.AccessToken; 62 | } 63 | 64 | // Unable to retrieve the access token silently. 65 | catch (Exception) 66 | { 67 | HttpContext.Current.Request.GetOwinContext().Authentication.Challenge( 68 | new AuthenticationProperties() { RedirectUri = "/" }, 69 | OpenIdConnectAuthenticationDefaults.AuthenticationType); 70 | 71 | throw new ServiceException( 72 | new Error 73 | { 74 | Code = GraphErrorCode.AuthenticationFailure.ToString(), 75 | Message = Resource.Error_AuthChallengeNeeded, 76 | }); 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Models/GraphService.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using Microsoft.Graph; 7 | using Resources; 8 | using System; 9 | using System.Collections.Generic; 10 | using System.IO; 11 | using System.Threading.Tasks; 12 | 13 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Models 14 | { 15 | public class GraphService 16 | { 17 | 18 | // Get the current user's email address from their profile. 19 | public async Task GetMyEmailAddress(GraphServiceClient graphClient) 20 | { 21 | 22 | // Get the current user. 23 | // This sample only needs the user's email address, so select the mail and userPrincipalName properties. 24 | // If the mail property isn't defined, userPrincipalName should map to the email for all account types. 25 | User me = await graphClient.Me.Request().Select("mail,userPrincipalName").GetAsync(); 26 | return me.Mail ?? me.UserPrincipalName; 27 | } 28 | 29 | // Send an email message from the current user. 30 | public async Task SendEmail(GraphServiceClient graphClient, Message message) 31 | { 32 | await graphClient.Me.SendMail(message, true).Request().PostAsync(); 33 | } 34 | 35 | // Create the email message. 36 | public async Task BuildEmailMessage(GraphServiceClient graphClient, string recipients, string subject) 37 | { 38 | 39 | // Get current user photo 40 | Stream photoStream = await GetCurrentUserPhotoStreamAsync(graphClient); 41 | 42 | 43 | // If the user doesn't have a photo, or if the user account is MSA, we use a default photo 44 | 45 | if ( photoStream == null) 46 | { 47 | photoStream = System.IO.File.OpenRead(System.Web.Hosting.HostingEnvironment.MapPath("/Content/test.jpg")); 48 | } 49 | 50 | MemoryStream photoStreamMS = new MemoryStream(); 51 | // Copy stream to MemoryStream object so that it can be converted to byte array. 52 | photoStream.CopyTo(photoStreamMS); 53 | 54 | DriveItem photoFile = await UploadFileToOneDrive(graphClient, photoStreamMS.ToArray()); 55 | 56 | MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage(); 57 | attachments.Add(new FileAttachment 58 | { 59 | ODataType = "#microsoft.graph.fileAttachment", 60 | ContentBytes = photoStreamMS.ToArray(), 61 | ContentType = "image/png", 62 | Name = "me.png" 63 | }); 64 | 65 | Permission sharingLink = await GetSharingLinkAsync(graphClient, photoFile.Id); 66 | 67 | // Add the sharing link to the email body. 68 | string bodyContent = string.Format(Resource.Graph_SendMail_Body_Content, sharingLink.Link.WebUrl); 69 | 70 | // Prepare the recipient list. 71 | string[] splitter = { ";" }; 72 | string[] splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries); 73 | List recipientList = new List(); 74 | foreach (string recipient in splitRecipientsString) 75 | { 76 | recipientList.Add(new Recipient 77 | { 78 | EmailAddress = new EmailAddress 79 | { 80 | Address = recipient.Trim() 81 | } 82 | }); 83 | } 84 | 85 | // Build the email message. 86 | Message email = new Message 87 | { 88 | Body = new ItemBody 89 | { 90 | Content = bodyContent, 91 | ContentType = BodyType.Html, 92 | }, 93 | Subject = subject, 94 | ToRecipients = recipientList, 95 | Attachments = attachments 96 | }; 97 | return email; 98 | } 99 | 100 | // Gets the stream content of the signed-in user's photo. 101 | // This snippet doesn't work with consumer accounts. 102 | public async Task GetCurrentUserPhotoStreamAsync(GraphServiceClient graphClient) 103 | { 104 | Stream currentUserPhotoStream = null; 105 | 106 | try 107 | { 108 | currentUserPhotoStream = await graphClient.Me.Photo.Content.Request().GetAsync(); 109 | 110 | } 111 | 112 | // If the user account is MSA (not work or school), the service will throw an exception. 113 | catch (ServiceException) 114 | { 115 | return null; 116 | } 117 | 118 | return currentUserPhotoStream; 119 | 120 | } 121 | 122 | // Uploads the specified file to the user's root OneDrive directory. 123 | public async Task UploadFileToOneDrive(GraphServiceClient graphClient, byte[] file) 124 | { 125 | DriveItem uploadedFile = null; 126 | 127 | try 128 | { 129 | MemoryStream fileStream = new MemoryStream(file); 130 | uploadedFile = await graphClient.Me.Drive.Root.ItemWithPath("me.png").Content.Request().PutAsync(fileStream); 131 | 132 | } 133 | 134 | 135 | catch (ServiceException) 136 | { 137 | return null; 138 | } 139 | 140 | return uploadedFile; 141 | } 142 | 143 | public static async Task GetSharingLinkAsync(GraphServiceClient graphClient, string Id) 144 | { 145 | Permission permission = null; 146 | 147 | try 148 | { 149 | permission = await graphClient.Me.Drive.Items[Id].CreateLink("view").Request().PostAsync(); 150 | } 151 | 152 | catch (ServiceException) 153 | { 154 | return null; 155 | } 156 | 157 | return permission; 158 | } 159 | 160 | } 161 | } -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Microsoft_Graph_SDK_ASPNET_Connect")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Microsoft_Graph_SDK_ASPNET_Connect")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("e0acf779-6715-46c4-a159-31a4cde3c9c1")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Revision and Build Numbers 33 | // by using the '*' as shown below: 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Scripts/_references.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Scripts/_references.js -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Startup.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using Owin; 7 | using Microsoft.Owin; 8 | 9 | [assembly: OwinStartup(typeof(Microsoft_Graph_SDK_ASPNET_Connect.Startup))] 10 | 11 | namespace Microsoft_Graph_SDK_ASPNET_Connect 12 | { 13 | public partial class Startup 14 | { 15 | public void Configuration(IAppBuilder app) 16 | { 17 | ConfigureAuth(app); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/TokenStorage/SessionTokenCache.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using Microsoft.Identity.Client; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Threading; 11 | using System.Web; 12 | 13 | namespace Microsoft_Graph_SDK_ASPNET_Connect.TokenStorage 14 | { 15 | 16 | // Store the user's token information. 17 | public class SessionTokenCache 18 | { 19 | private static ReaderWriterLockSlim SessionLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); 20 | string UserId = string.Empty; 21 | string CacheId = string.Empty; 22 | HttpContextBase httpContext = null; 23 | 24 | TokenCache cache = new TokenCache(); 25 | 26 | public SessionTokenCache(string userId, HttpContextBase httpcontext) 27 | { 28 | // not object, we want the SUB 29 | UserId = userId; 30 | CacheId = UserId + "_TokenCache"; 31 | httpContext = httpcontext; 32 | Load(); 33 | } 34 | 35 | public TokenCache GetMsalCacheInstance() 36 | { 37 | cache.SetBeforeAccess(BeforeAccessNotification); 38 | cache.SetAfterAccess(AfterAccessNotification); 39 | Load(); 40 | return cache; 41 | } 42 | 43 | public void SaveUserStateValue(string state) 44 | { 45 | SessionLock.EnterWriteLock(); 46 | httpContext.Session[CacheId + "_state"] = state; 47 | SessionLock.ExitWriteLock(); 48 | } 49 | public string ReadUserStateValue() 50 | { 51 | string state = string.Empty; 52 | SessionLock.EnterReadLock(); 53 | state = (string)httpContext.Session[CacheId + "_state"]; 54 | SessionLock.ExitReadLock(); 55 | return state; 56 | } 57 | public void Load() 58 | { 59 | SessionLock.EnterReadLock(); 60 | cache.Deserialize((byte[])httpContext.Session[CacheId]); 61 | SessionLock.ExitReadLock(); 62 | } 63 | 64 | public void Persist() 65 | { 66 | SessionLock.EnterWriteLock(); 67 | 68 | // Optimistically set HasStateChanged to false. We need to do it early to avoid losing changes made by a concurrent thread. 69 | cache.HasStateChanged = false; 70 | 71 | // Reflect changes in the persistent store 72 | httpContext.Session[CacheId] = cache.Serialize(); 73 | SessionLock.ExitWriteLock(); 74 | } 75 | 76 | // Triggered right before MSAL needs to access the cache. 77 | // Reload the cache from the persistent store in case it changed since the last access. 78 | void BeforeAccessNotification(TokenCacheNotificationArgs args) 79 | { 80 | Load(); 81 | } 82 | 83 | // Triggered right after MSAL accessed the cache. 84 | void AfterAccessNotification(TokenCacheNotificationArgs args) 85 | { 86 | // if the access operation resulted in a cache update 87 | if (cache.HasStateChanged) 88 | { 89 | Persist(); 90 | } 91 | } 92 | 93 | } 94 | } -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Views/Home/About.cshtml: -------------------------------------------------------------------------------- 1 |  3 | 4 | @using Resources 5 | 6 | @{ 7 | ViewBag.Title = Resource.About; 8 | } 9 |

@ViewBag.Title

10 | 11 |

@Resource.About_Description

-------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Views/Home/Graph.cshtml: -------------------------------------------------------------------------------- 1 |  3 | 4 | @using Resources 5 | 6 | @{ 7 | ViewBag.Title = Resource.App_Name; 8 | } 9 | 10 |

@ViewBag.Title

11 |

@Resource.Graph_GetEmailAddress_Heading

12 |

@Html.Raw(Resource.Graph_GetEmailAddress_Instruction)

13 | @using (Html.BeginForm("GetMyEmailAddress", "Home")) 14 | { 15 |
16 |
17 | 18 |
19 |
20 | } 21 |
22 | 23 |
@ViewBag.Email
24 |
25 | 26 |

@Resource.Graph_SendMail_Heading

27 |

@Html.Raw(Resource.Graph_SendMail_Instruction)

28 | @using (Html.BeginForm("SendEmail", "Home")) 29 | { 30 |
31 |
32 | 33 | 34 |
35 |
36 | 37 | 38 |
39 |
40 | 41 | 42 |
43 |
44 | } 45 |
46 |

@Html.Raw(ViewBag.Message)

47 |
48 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Views/Shared/Error.cshtml: -------------------------------------------------------------------------------- 1 |  3 | 4 | @using Resources 5 | 6 | @{ 7 | ViewBag.Title = Resource.App_Name; 8 | } 9 | 10 |

@ViewBag.Title

11 |

@Resource.Error_Introduction

12 | 13 |
@ViewBag.Message
-------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 |  3 | 4 | @using Resources 5 | 6 | 7 | 8 | 9 | 10 | 11 | @ViewBag.Title 12 | @Styles.Render("~/Content/css") 13 | @Styles.Render("https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css") 14 | @Styles.Render("https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap-theme.min.css") 15 | @Scripts.Render("https://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.6.2.js") 16 | 17 | 18 | 37 |
38 | @RenderBody() 39 |
40 |
41 |

© @DateTime.Now.Year - @ViewBag.Title

42 |
43 |
44 | @Scripts.Render("https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.3.min.js") 45 | @Scripts.Render("https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js") 46 | @RenderSection("scripts", required: false) 47 | 48 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Views/Shared/_LoginPartial.cshtml: -------------------------------------------------------------------------------- 1 |  3 | 4 | @using Resources 5 | 6 | @if (Request.IsAuthenticated) 7 | { 8 | 9 | 18 | 19 | } 20 | else 21 | { 22 | 40 | 41 | 48 | } 49 | 50 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Views/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 |
7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "~/Views/Shared/_Layout.cshtml"; 3 | } 4 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Web.Debug.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Web.Release.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 17 | 18 | 19 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/favicon.ico -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /Microsoft Graph SDK ASPNET Connect/Microsoft Graph SDK ASPNET Connect/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /README-Localized/README-de-de.md: -------------------------------------------------------------------------------- 1 | # Microsoft Graph Connect-Beispiel für ASP.NET 4.6 2 | 3 | ## Inhalt 4 | 5 | * [Voraussetzungen](#prerequisites) 6 | * [Registrieren der App](#register-the-application) 7 | * [Erstellen und Ausführen des Beispiels](#build-and-run-the-sample) 8 | * [Relevanter Code](#code-of-note) 9 | * [Fragen und Kommentare](#questions-and-comments) 10 | * [Mitwirkung](#contributing) 11 | * [Zusätzliche Ressourcen](#additional-resources) 12 | 13 | Dieses Beispiel zeigt, wie Sie eine ASP.NET 4.6 MVC-Web-App mit einem Microsoft-Geschäfts-, Schul- oder Unikonto (Azure Active Directory) oder einem persönlichen (Microsoft) Konto anhand der Microsoft Graph API verbinden, um das Profilbild eines Benutzers abzurufen, das Bild in OneDrive hochzuladen und eine E-Mail zu senden, das das Foto als Anhang und den Freigabelink als Text enthält. Es verwendet die [Microsoft Graph .NET-Clientbibliothek](https://github.com/microsoftgraph/msgraph-sdk-dotnet), um mit Daten zu arbeiten, die von Microsoft Graph zurückgegeben werden. 14 | 15 | Das Beispiel verwendet außerdem die [Microsoft-Authentifizierungsbibliothek (MSAL)](https://www.nuget.org/packages/Microsoft.Identity.Client/) für die Authentifizierung. Das MSAL-SDK bietet Features für die Arbeit mit dem [Azure AD v2.0-Endpunkt](https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview), der es Entwicklern ermöglicht, einen einzelnen Codefluss zu schreiben, der die Authentifizierung sowohl für Geschäfts- oder Schulkonten (Azure Active Directory) als auch für persönliche Konten (Microsoft) verarbeitet. 16 | 17 | ## Wichtiger Hinweis zur MSAL-Vorschau 18 | 19 | Diese Bibliothek eignet sich für die Verwendung in einer Produktionsumgebung. Wir bieten für diese Bibliothek den gleichen Support auf Produktionsebene wie für alle anderen aktuellen Produktionsbibliotheken. Während der Vorschau nehmen wir möglicherweise Änderungen an der API, dem internen Cacheformat und anderen Mechanismen dieser Bibliothek vor, die Sie zusammen mit Fehlerbehebungen oder Funktionsverbesserungen übernehmen müssen. Dies kann sich auf Ihre Anwendung auswirken. So kann sich eine Änderung des Cacheformats beispielsweise auf die Benutzer auswirken, indem sie sich z. B. erneut anmelden müssen. Eine Änderung der API kann dazu führen, dass Sie den Code aktualisieren müssen. Wenn wir das allgemein verfügbare Release bereitstellen, müssen Sie innerhalb von sechs Monaten auf die allgemein verfügbare Version aktualisieren, da Anwendungen, die mit einer Vorschauversion der Bibliothek erstellt wurden, möglicherweise nicht mehr funktionieren. 20 | 21 | ## Voraussetzungen 22 | 23 | Für dieses Beispiel ist Folgendes erforderlich: 24 | 25 | * [Visual Studio 2015](https://www.visualstudio.com/en-us/downloads) 26 | * Entweder ein [Microsoft-Konto](https://www.outlook.com) oder ein [Office 365 for Business-Konto](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). Sie können sich für [ein Office 365-Entwicklerabonnement](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account) registrieren. Dieses umfasst die Ressourcen, die Sie zum Erstellen von Office 365-Apps benötigen. 27 | 28 | ## Registrieren der App 29 | 30 | 1. Melden Sie sich beim [App-Registrierungsportal](https://apps.dev.microsoft.com/) entweder mit Ihrem persönlichen oder geschäftlichen Konto oder mit Ihrem Schulkonto an. 31 | 32 | 2. Klicken Sie auf **App hinzufügen**. 33 | 34 | 3. Geben Sie einen Namen für die App ein, und wählen Sie **Anwendung erstellen** aus. 35 | 36 | Die Registrierungsseite wird angezeigt wird, und die Eigenschaften der App werden aufgeführt. 37 | 38 | 4. Kopieren Sie die Anwendungs-ID: Dies ist der eindeutige Bezeichner für Ihre App. 39 | 40 | 5. Wählen Sie unter **Anwendungsgeheimnisse** die Option **Neues Kennwort generieren** aus. Kopieren Sie das Kennwort aus dem Dialogfeld **Neues Kennwort wurde generiert**. 41 | 42 | Verwenden Sie die Anwendungs-ID und das Kennwort zur Konfiguration der Beispiel-App im nächsten Abschnitt. 43 | 44 | 6. Wählen Sie unter **Plattformen** die Option **Plattform hinzufügen** aus. 45 | 46 | 7. Wählen Sie **Web** aus. 47 | 48 | 8. Stellen Sie sicher, dass das Kontrollkästchen **Impliziten Fluss zulassen** aktiviert ist, und geben Sie *http://localhost:55065/* als Umleitungs-URI ein. 49 | 50 | Die Option **Impliziten Fluss zulassen** ermöglicht den Hybridfluss. Während der Authentifizierung ermöglicht dies der App, sowohl Anmeldeinformationen (das id_token) als auch Artefakte (in diesem Fall ein Autorisierungscode) abzurufen, den die App zum Abrufen eines Zugriffstokens verwenden kann. 51 | 52 | 9. Wählen Sie **Speichern** aus. 53 | 54 | ## Erstellen und Ausführen des Beispiels 55 | 56 | 1. Laden Sie das Microsoft Graph Connect-Beispiel für ASP.NET 4.6 herunter. 57 | 58 | 2. Öffnen Sie die Projektmappe in Visual Studio. 59 | 60 | 3. Ersetzen Sie in der Datei „Web.config“ im Stammverzeichnis die Platzhalterwerte **ida: AppId** und **ida: AppSecret** durch die Anwendungs-ID und das Kennwort, die bzw. das Sie während der App-Registrierung kopiert haben. 61 | 62 | 4. Drücken Sie zum Erstellen und Ausführen des Beispiels F5. Dadurch werden NuGet-Paketabhängigkeiten wiederhergestellt, und die App wird geöffnet. 63 | 64 | >Wenn beim Installieren der Pakete Fehler angezeigt werden, müssen Sie sicherstellen, dass der lokale Pfad, unter dem Sie die Projektmappe abgelegt haben, weder zu lang noch zu tief ist. Dieses Problem lässt sich beheben, indem Sie den Pfad auf Ihrem Laufwerk verkürzen. 65 | 66 | 5. Melden Sie sich mit Ihrem persönlichen Konto oder mit Ihrem Geschäfts- oder Schulkonto an, und gewähren Sie die erforderlichen Berechtigungen. 67 | 68 | 6. Klicken Sie auf die Schaltfläche **E-Mail-Adresse abrufen**. Wenn der Vorgang abgeschlossen ist, wird die E-Mail-Adresse des angemeldeten Benutzers auf der Seite angezeigt. 69 | 70 | 7. Optional können Sie die Empfängerliste und den Betreff der E-Mail bearbeiten. Klicken Sie dann auf die Schaltfläche **E-Mail senden**. Nachdem die E-Mail gesendet wurde, wird unter der Schaltfläche eine Erfolgsmeldung angezeigt. 71 | 72 | 8. Nächste Schritte: Schauen Sie sich das [Microsoft Graph-Codeausschnittbeispiel für ASP.NET 4.6 ](https://github.com/microsoftgraph/aspnet-snippets-sample) an, um Beispiele für allgemeine Microsoft Graph-Vorgänge anzuzeigen. 73 | 74 | ## Relevanter Code 75 | 76 | > Hinweis: Informationen für das Verständnis des Codes für den Aufruf der Microsoft Graph-API in einer ASP.NET MVC-App finden Sie im Thema über das [Erste Schritte mit Microsoft Graph in einer ASP.NET 4.6 MVC-App](https://graph.microsoft.io/en-us/docs/platform/aspnetmvc). 77 | 78 | - [Startup.Auth.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/App_Start/Startup.Auth.cs). Authentifiziert den aktuellen Benutzer und initialisiert den Tokencache des Beispiels. 79 | 80 | - [SessionTokenCache.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/TokenStorage/SessionTokenCache.cs). Speichert die Tokeninformationen des Benutzers. Sie können dies durch Ihren eigenen benutzerdefinierten Tokencache ersetzen. Weitere Informationen finden Sie unter [Zwischenspeichern von Zugriffstoken in einer Anwendung für mehrere Mandanten](https://azure.microsoft.com/en-us/documentation/articles/guidance-multitenant-identity-token-cache/). 81 | 82 | - [SampleAuthProvider.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SampleAuthProvider.cs). Implementiert die lokale IAuthProvider-Schnittstelle und ruft ein Zugriffstoken mithilfe der MSAL-Methode **AcquireTokenSilentAsync** ab. Sie können dies durch Ihren eigenen Authentifizierungsanbieter ersetzen. 83 | 84 | - [SDKHelper.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SDKHelper.cs). Initialisiert den **GraphServiceClient** aus der [Microsoft Graph .NET-Clientbibliothek](https://github.com/microsoftgraph/msgraph-sdk-dotnet), die für die Interaktion mit dem Microsoft Graph verwendet wird. 85 | 86 | - [HomeController.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Controllers/HomeController.cs). Enthält Methoden, die den **GraphServiceClient** zum Erstellen und Senden von Aufrufen des Microsoft Graph-Diensts und zum Verarbeiten der Antwort verwendet. 87 | - Die **GetMyEmailAddress**-Aktion ruft die E-Mail-Adresse des aktuellen Benutzers aus der **Mail**- oder der **userPrincipalName**-Eigenschaft ab. 88 | - Die **SendMail**-Aktion sendet eine E-Mail im Auftrag des aktuellen Benutzers. 89 | 90 | - [Graph.cshtml](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Views/Home/Graph.cshtml). Enthält die Benutzeroberfläche des Beispiels. 91 | 92 | ## Fragen und Kommentare 93 | 94 | Wir schätzen Ihr Feedback hinsichtlich dieses Beispiels. Sie können uns Ihre Fragen und Vorschläge über den Abschnitt [Probleme](https://github.com/microsoftgraph/aspnet-connect-sample/issues) dieses Repositorys senden. 95 | 96 | Ihr Feedback ist uns wichtig. Nehmen Sie unter [Stack Overflow](http://stackoverflow.com/questions/tagged/microsoftgraph) Kontakt mit uns auf. Taggen Sie Ihre Fragen mit [MicrosoftGraph]. 97 | 98 | ## Mitwirkung ## 99 | 100 | Wenn Sie einen Beitrag zu diesem Beispiel leisten möchten, finden Sie unter [CONTRIBUTING.md](CONTRIBUTING.md) weitere Informationen. 101 | 102 | In diesem Projekt wurden die [Microsoft Open Source-Verhaltensregeln](https://opensource.microsoft.com/codeofconduct/) übernommen. Weitere Informationen finden Sie unter [Häufig gestellte Fragen zu Verhaltensregeln](https://opensource.microsoft.com/codeofconduct/faq/), oder richten Sie Ihre Fragen oder Kommentare an [opencode@microsoft.com](mailto:opencode@microsoft.com). 103 | 104 | ## Zusätzliche Ressourcen 105 | 106 | - [Weitere Microsoft Graph Connect-Beispiele](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 107 | - [Microsoft Graph-Übersicht](http://graph.microsoft.io) 108 | - [Office-Entwicklercodebeispiele](http://dev.office.com/code-samples) 109 | - [Office Dev Center](http://dev.office.com/) 110 | 111 | ## Copyright 112 | Copyright (c) 2016 Microsoft. Alle Rechte vorbehalten. 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /README-Localized/README-es-es.md: -------------------------------------------------------------------------------- 1 | # Ejemplo Connect de Microsoft Graph para ASP.NET 4.6 2 | 3 | ## Tabla de contenido 4 | 5 | * [Requisitos previos](#prerequisites) 6 | * [Registrar la aplicación](#register-the-application) 7 | * [Compilar y ejecutar el ejemplo](#build-and-run-the-sample) 8 | * [Código de nota](#code-of-note) 9 | * [Preguntas y comentarios](#questions-and-comments) 10 | * [Colaboradores](#contributing) 11 | * [Recursos adicionales](#additional-resources) 12 | 13 | Este ejemplo muestra cómo conectar una aplicación web de ASP.NET 4.6 MVC a una cuenta profesional o educativa de Microsoft (Azure Active Directory) o a una cuenta personal (Microsoft) usando la API de Microsoft Graph para recuperar la imagen del perfil de un usuario, cargar la imagen en OneDrive y enviar un correo electrónico que contiene la foto como un archivo adjunto y el vínculo para compartir en su texto. Usa la [biblioteca del cliente .NET de Microsoft Graph](https://github.com/microsoftgraph/msgraph-sdk-dotnet) para trabajar con los datos devueltos por Microsoft Graph. 14 | 15 | Además, el ejemplo usa la [biblioteca de autenticación de Microsoft (MSAL)](https://www.nuget.org/packages/Microsoft.Identity.Client/) para la autenticación. El SDK de MSAL ofrece características para trabajar con el [punto de conexión v2.0 de Azure AD](https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview), lo que permite a los desarrolladores escribir un flujo de código único que controla la autenticación para las cuentas profesionales, educativas (Azure Active Directory) o las cuentas personales (Microsoft). 16 | 17 | ## Nota importante acerca de la vista previa MSAL 18 | 19 | Esta biblioteca es apta para utilizarla en un entorno de producción. Ofrecemos la misma compatibilidad de nivel de producción de esta biblioteca que la de las bibliotecas de producción actual. Durante la vista previa podemos realizar cambios en la API, el formato de caché interna y otros mecanismos de esta biblioteca, que deberá tomar junto con correcciones o mejoras. Esto puede afectar a la aplicación. Por ejemplo, un cambio en el formato de caché puede afectar a los usuarios, como que se les pida que vuelvan a iniciar sesión. Un cambio de API puede requerir que actualice su código. Cuando ofrecemos la versión de disponibilidad General, deberá actualizar a la versión de disponibilidad General dentro de seis meses, ya que las aplicaciones escritas mediante una versión de vista previa de biblioteca puede que ya no funcionen. 20 | 21 | ## Requisitos previos 22 | 23 | Este ejemplo necesita lo siguiente: 24 | 25 | * [Visual Studio 2015](https://www.visualstudio.com/en-us/downloads) 26 | * Ya sea una [cuenta de Microsoft](https://www.outlook.com) u [Office 365 para una cuenta empresarial](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account) Puede registrarse para [una suscripción de Office 365 Developer](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account), que incluye los recursos que necesita para comenzar a crear aplicaciones de Office 365. 27 | 28 | ## Registrar la aplicación 29 | 30 | 1. Inicie sesión en el [Portal de registro de la aplicación](https://apps.dev.microsoft.com/) mediante su cuenta personal, profesional o educativa. 31 | 32 | 2. Seleccione **Agregar una aplicación**. 33 | 34 | 3. Escriba un nombre para la aplicación y seleccione **Crear aplicación**. 35 | 36 | Se muestra la página de registro, indicando las propiedades de la aplicación. 37 | 38 | 4. Copie el Id. de aplicación. Se trata del identificador único para su aplicación. 39 | 40 | 5. En **Secretos de aplicación**, seleccione **Generar nueva contraseña**. Copie la contraseña del cuadro de diálogo de **Nueva contraseña generada**. 41 | 42 | Usará el identificador de la aplicación y la contraseña para configurar la aplicación de ejemplo en la sección siguiente. 43 | 44 | 6. En **Plataformas**, seleccione **Agregar plataforma**. 45 | 46 | 7. Seleccione **Web**. 47 | 48 | 8. Asegúrese de que la casilla **Permitir flujo implícito** esté seleccionada y escriba *http://localhost:55065/* como URI de redireccionamiento. 49 | 50 | La opción **Permitir flujo implícito** permite el flujo híbrido. Durante la autenticación, esto permite que la aplicación reciba la información de inicio de sesión (id_token) y artefactos (en este caso, un código de autorización) que la aplicación puede usar para obtener un token de acceso. 51 | 52 | 9. Elija **Guardar**. 53 | 54 | ## Compilar y ejecutar el ejemplo 55 | 56 | 1. Descargue o clone el ejemplo de Microsoft Graph Connect para ASP.NET 4.6 57 | 58 | 2. Abra la solución del ejemplo en Visual Studio. 59 | 60 | 3. En el archivo Web.config en el directorio raíz, reemplace los valores de los marcadores de posición **ida:AppId** e **ida:AppSecret** por los valores que ha copiado durante el registro de la aplicación. 61 | 62 | 4. Pulse F5 para compilar y ejecutar el ejemplo. Esto restaurará las dependencias de paquetes de NuGet y abrirá la aplicación. 63 | 64 | >Si observa algún error durante la instalación de los paquetes, asegúrese de que la ruta de acceso local donde colocó la solución no es demasiado larga o profunda. Para resolver este problema, mueva la solución más cerca de la raíz de la unidad. 65 | 66 | 5. Inicie sesión con su cuenta personal, profesional o educativa y conceda los permisos solicitados. 67 | 68 | 6. Seleccione el botón **Obtener la dirección de correo electrónico**. Cuando finaliza la operación, la dirección de correo electrónico del usuario con sesión iniciada se muestra en la página. 69 | 70 | 7. De forma opcional, modifique la lista de destinatarios y el asunto del correo electrónico y, después, seleccione el botón **Enviar correo electrónico**. Cuando se envía el correo, se muestra un mensaje de Operación correcta debajo del botón. 71 | 72 | 8. Pasos siguientes: Consulte el [Ejemplo de fragmentos de código de muestra de Microsoft Graph para ASP.NET 4.6](https://github.com/microsoftgraph/aspnet-snippets-sample) para ver ejemplos de operaciones habituales con Microsoft Graph. 73 | 74 | ## Código de nota 75 | 76 | > Nota: Para entender el código para llamar a la API de Microsoft Graph en una aplicación ASP.NET MVC, consulte [Empezar a usar Microsoft Graph en una aplicación ASP.NET 4.6 MVC](https://graph.microsoft.io/en-us/docs/platform/aspnetmvc). 77 | 78 | - [Startup.Auth.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/App_Start/Startup.Auth.cs). Autentica al usuario actual e inicializa la memoria caché de token del ejemplo. 79 | 80 | - [SessionTokenCache.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/TokenStorage/SessionTokenCache.cs). Almacena información de token del usuario. Se puede reemplazar por su memoria caché de token personalizada. Más información en [Almacenamiento en la memoria caché de los tokens de acceso en una aplicación de varios inquilinos](https://azure.microsoft.com/en-us/documentation/articles/guidance-multitenant-identity-token-cache/). 81 | 82 | - [SampleAuthProvider.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SampleAuthProvider.cs). Implementa la interfaz local de IAuthProvider, y obtiene un token de acceso usando el método **AcquireTokenSilentAsync** de MSAL. Se puede reemplazar por su propio proveedor de autenticación. 83 | 84 | - [SDKHelper.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SDKHelper.cs). Inicializa **GraphServiceClient** de la [biblioteca de cliente de Microsoft Graph .NET](https://github.com/microsoftgraph/msgraph-sdk-dotnet) que se usa para interactuar con Microsoft Graph. 85 | 86 | - [HomeController.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Controllers/HomeController.cs). Contiene métodos que usan **GraphServiceClient** para crear y enviar llamadas al servicio Microsoft Graph y procesar la respuesta. 87 | - La acción **GetMyEmailAddress** obtiene la dirección de correo electrónico del usuario actual de la propiedad **mail** o **userPrincipalName**. 88 | - La acción **SendMail** envía un correo electrónico en nombre del usuario actual. 89 | 90 | - [Graph.cshtml](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Views/Home/Graph.cshtml). Contiene la interfaz de usuario de ejemplo. 91 | 92 | ## Preguntas y comentarios 93 | 94 | Nos encantaría recibir sus comentarios acerca de este ejemplo. Puede enviarnos sus preguntas y sugerencias a través de la sección [Problemas](https://github.com/microsoftgraph/aspnet-connect-sample/issues) de este repositorio. 95 | 96 | Su opinión es importante para nosotros. Conecte con nosotros en [Desbordamiento de pila](http://stackoverflow.com/questions/tagged/microsoftgraph). Etiquete sus preguntas con [MicrosoftGraph]. 97 | 98 | ## Colaboradores ## 99 | 100 | Si le gustaría contribuir a este ejemplo, consulte [CONTRIBUTING.md](CONTRIBUTING.md). 101 | 102 | Este proyecto ha adoptado el [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) (Código de conducta de código abierto de Microsoft). Para obtener más información, consulte las [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) (Preguntas más frecuentes del código de conducta) o póngase en contacto con [opencode@microsoft.com](mailto:opencode@microsoft.com) con otras preguntas o comentarios. 103 | 104 | ## Recursos adicionales 105 | 106 | - [Otros ejemplos de Connect de Microsoft Graph](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 107 | - [Información general de Microsoft Graph](http://graph.microsoft.io) 108 | - [Ejemplos de código de Office Developer](http://dev.office.com/code-samples) 109 | - [Centro de desarrollo de Office](http://dev.office.com/) 110 | 111 | ## Copyright 112 | Copyright (c) 2016 Microsoft. Todos los derechos reservados. 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /README-Localized/README-fr-fr.md: -------------------------------------------------------------------------------- 1 | # Exemple de connexion de Microsoft Graph pour ASP.NET 4.6 2 | 3 | ## Sommaire 4 | 5 | * [Conditions préalables](#prerequisites) 6 | * [Inscription de l’application](#register-the-application) 7 | * [Création et exécution de l’exemple](#build-and-run-the-sample) 8 | * [Code de note](#code-of-note) 9 | * [Questions et commentaires](#questions-and-comments) 10 | * [Contribution](#contributing) 11 | * [Ressources supplémentaires](#additional-resources) 12 | 13 | Cet exemple montre comment connecter une application web ASP.NET 4.6 MVC à un compte professionnel ou scolaire (Azure Active Directory), ou personnel (Microsoft) à l’aide de l’API Microsoft Graph pour récupérer l’image de profil d’un utilisateur, télécharger l’image vers OneDrive, et envoyer un courrier électronique contenant la photo en tant que pièce jointe et le lien de partage dans son texte. Il utilise la [bibliothèque Microsoft Graph .NET](https://github.com/microsoftgraph/msgraph-sdk-dotnet) pour exploiter les données renvoyées par Microsoft Graph. 14 | 15 | En outre, l’exemple utilise la [bibliothèque d’authentification Microsoft (MSAL)](https://www.nuget.org/packages/Microsoft.Identity.Client/) pour l’authentification. Le kit de développement logiciel (SDK) MSAL offre des fonctionnalités permettant d’utiliser le [point de terminaison Azure AD v2.0](https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview), qui permet aux développeurs d’écrire un flux de code unique qui gère l’authentification des comptes professionnels ou scolaires (Azure Active Directory) et personnels (Microsoft). 16 | 17 | ## Remarque importante à propos de la version d’essai MSAL 18 | 19 | La bibliothèque peut être utilisée dans un environnement de production. Nous fournissons la même prise en charge du niveau de production pour cette bibliothèque que pour nos bibliothèques de production actuelles. Lors de la version d’essai, nous pouvons apporter des modifications à l’API, au format de cache interne et à d’autres mécanismes de cette bibliothèque que vous devrez prendre en compte avec les correctifs de bogues ou les améliorations de fonctionnalités. Cela peut avoir un impact sur votre application. Par exemple, une modification du format de cache peut avoir un impact sur vos utilisateurs. Par exemple, il peut leur être demandé de se connecter à nouveau. Une modification de l’API peut vous obliger à mettre à jour votre code. Lorsque nous fournissons la version de disponibilité générale, vous devez effectuer une mise à jour vers la version de disponibilité générale dans un délai de six mois, car les applications écrites à l’aide de la version d’évaluation de la bibliothèque ne fonctionneront plus. 20 | 21 | ## Conditions préalables 22 | 23 | Cet exemple nécessite les éléments suivants : 24 | 25 | * [Visual Studio 2015](https://www.visualstudio.com/en-us/downloads) 26 | * Soit un [compte Microsoft](https://www.outlook.com), soit un [compte Office 365 pour entreprise](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). Vous pouvez vous inscrire à [Office 365 Developer](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account) pour accéder aux ressources dont vous avez besoin afin de commencer à créer des applications Office 365. 27 | 28 | ## Inscription de l’application 29 | 30 | 1. Connectez-vous au [portail d’inscription des applications](https://apps.dev.microsoft.com/) en utilisant votre compte personnel, professionnel ou scolaire. 31 | 32 | 2. Choisissez **Ajouter une application**. 33 | 34 | 3. Entrez un nom pour l’application, puis choisissez **Créer une application**. 35 | 36 | La page d’inscription s’affiche, répertoriant les propriétés de votre application. 37 | 38 | 4. Copiez l’ID de l’application. Il s’agit de l’identificateur unique de votre application. 39 | 40 | 5. Sous **Secrets de l'application**, choisissez **Générer un nouveau mot de passe**. Copiez le mot de passe à partir de la boîte de dialogue **Nouveau mot de passe créé**. 41 | 42 | Vous utiliserez l’ID de l’application et le mot de passe pour configurer l’exemple d’application dans la section suivante. 43 | 44 | 6. Sous **Plateformes**, choisissez **Ajouter une plateforme**. 45 | 46 | 7. Choisissez **Web**. 47 | 48 | 8. Assurez-vous que la case **Autoriser le flux implicite** est cochée, puis entrez *https://localhost:55065/* comme URI de redirection. 49 | 50 | L’option **Autoriser le flux implicite** active le flux hybride. Lors de l’authentification, cela permet à l’application de recevoir les informations de connexion (id_token) et les artefacts (dans ce cas, un code d’autorisation) qui servent à obtenir un jeton d’accès. 51 | 52 | 9. Cliquez sur **Enregistrer**. 53 | 54 | ## Création et exécution de l’exemple 55 | 56 | 1. Téléchargez ou clonez l’exemple de connexion Microsoft Graph pour ASP.NET 4.6. 57 | 58 | 2. Ouvrez l’exemple de solution dans Visual Studio. 59 | 60 | 3. Dans le fichier Web.config dans le répertoire racine, remplacez les valeurs d’espace réservé **ida:AppId** et **ida:AppSecret** par l’ID de l’application et le mot de passe que vous avez copiés lors de l’inscription de l’application. 61 | 62 | 4. Appuyez sur F5 pour créer et exécuter l’exemple. Cela entraîne la restauration des dépendances du package NuGet et l’ouverture de l’application. 63 | 64 | >Si vous constatez des erreurs pendant l’installation des packages, vérifiez que le chemin d’accès local où vous avez sauvegardé la solution n’est pas trop long/profond. Pour résoudre ce problème, il vous suffit de déplacer la solution dans un dossier plus près du répertoire racine de votre lecteur. 65 | 66 | 5. Connectez-vous à votre compte personnel, professionnel ou scolaire, et accordez les autorisations demandées. 67 | 68 | 6. Choisissez le bouton **Obtenir l’adresse de messagerie**. Une fois l’opération terminée, l’adresse de messagerie de l’utilisateur connecté s’affiche dans la page. 69 | 70 | 7. Vous pouvez également modifier la liste des destinataires et l’objet de l’e-mail, puis cliquer sur le bouton **Envoyer un message électronique**. Lorsque le message est envoyé, un message de réussite s’affiche sous le bouton. 71 | 72 | 8. Étapes suivantes : Consultez l’[exemple d’extraits de code Microsoft Graph pour ASP.NET 4.6](https://github.com/microsoftgraph/aspnet-snippets-sample) pour voir des exemples d’opérations courantes de Microsoft Graph. 73 | 74 | ## Code de note 75 | 76 | > Remarque : pour comprendre le code permettant d’appeler l’API Microsoft Graph dans une application ASP.NET MVC, consultez la rubrique relative à la [prise en main de Microsoft Graph dans une application ASP.NET 4.6 MVC](https://graph.microsoft.io/en-us/docs/platform/aspnetmvc). 77 | 78 | - [Startup.Auth.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/App_Start/Startup.Auth.cs). Authentifie l’utilisateur actuel et initialise le cache de jetons de l’exemple. 79 | 80 | - [SessionTokenCache.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/TokenStorage/SessionTokenCache.cs). Stocke les informations du jeton de l’utilisateur. Vous pouvez le remplacer par votre propre cache de jetons personnalisé. Pour plus d’informations, voir [Mise en cache des jetons d’accès dans une application mutualisée](https://azure.microsoft.com/en-us/documentation/articles/guidance-multitenant-identity-token-cache/). 81 | 82 | - [SampleAuthProvider.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SampleAuthProvider.cs). Implémente l’interface IAuthProvider locale et obtient un jeton d’accès à l’aide de la méthode MSAL **AcquireTokenSilentAsync**. Vous pouvez utiliser, à la place, votre propre fournisseur d’authentification. 83 | 84 | - [SDKHelper.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SDKHelper.cs). Initialise **GraphServiceClient** à partir de la [bibliothèque client Microsoft Graph .NET](https://github.com/microsoftgraph/msgraph-sdk-dotnet) qui sert à interagir avec Microsoft Graph. 85 | 86 | - [HomeController.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Controllers/HomeController.cs). Contient des méthodes qui utilisent **GraphServiceClient** pour créer et envoyer les appels au service Microsoft Graph et traiter la réponse. 87 | - L’action **GetMyEmailAddress** permet d’obtenir l’adresse de messagerie de l’utilisateur actuel à partir de la propriété **mail** ou **userPrincipalName**. 88 | - L’action **SendMail** envoie un message électronique au nom de l’utilisateur actuel. 89 | 90 | - [Graph.cshtml](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Views/Home/Graph.cshtml). Contient l’interface utilisateur de l’exemple. 91 | 92 | ## Questions et commentaires 93 | 94 | Nous serions ravis de connaître votre opinion sur cet exemple. Vous pouvez nous faire part de vos questions et suggestions dans la rubrique [Problèmes](https://github.com/microsoftgraph/aspnet-connect-sample/issues) de ce référentiel. 95 | 96 | Votre avis compte beaucoup pour nous. Communiquez avec nous sur [Stack Overflow](http://stackoverflow.com/questions/tagged/microsoftgraph). Posez vos questions avec la balise [MicrosoftGraph]. 97 | 98 | ## Contribution ## 99 | 100 | Si vous souhaitez contribuer à cet exemple, voir [CONTRIBUTING.MD](CONTRIBUTING.md). 101 | 102 | Ce projet a adopté le [code de conduite Microsoft Open Source](https://opensource.microsoft.com/codeofconduct/). Pour plus d’informations, reportez-vous à la [FAQ relative au code de conduite](https://opensource.microsoft.com/codeofconduct/faq/) ou contactez [opencode@microsoft.com](mailto:opencode@microsoft.com) pour toute question ou tout commentaire. 103 | 104 | ## Ressources supplémentaires 105 | 106 | - [Autres exemples de connexion avec Microsoft Graph](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 107 | - [Présentation de Microsoft Graph](http://graph.microsoft.io) 108 | - [Exemples de code du développeur Office](http://dev.office.com/code-samples) 109 | - [Centre de développement Office](http://dev.office.com/) 110 | 111 | ## Copyright 112 | Copyright (c) 2016 Microsoft. Tous droits réservés. 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /README-Localized/README-ja-jp.md: -------------------------------------------------------------------------------- 1 | # ASP.NET 4.6 用 Microsoft Graph Connect のサンプル 2 | 3 | ## 目次 4 | 5 | * [前提条件](#prerequisites) 6 | * [アプリケーションの登録](#register-the-application) 7 | * [サンプルのビルドと実行](#build-and-run-the-sample) 8 | * [ノートのコード](#code-of-note) 9 | * [質問とコメント](#questions-and-comments) 10 | * [投稿](#contributing) 11 | * [その他のリソース](#additional-resources) 12 | 13 | このサンプルでは、Microsoft Graph API を使って ASP.NET 4.6 MVC Web アプリを Microsoft の職場または学校 (Azure Active Directory) アカウントまたは個人用 (Microsoft) アカウントに接続して、ユーザーのプロフィール画像の取得、OneDrive への画像のアップロード、電子メール (画像が添付され、共有リンクがテキストに含まれる) の送信を行う方法を示します。 [Microsoft Graph .NET クライアント ライブラリ](https://github.com/microsoftgraph/msgraph-sdk-dotnet)を使用して、Microsoft Graph が返すデータを操作します。 14 | 15 | また、サンプルでは認証に [Microsoft 認証ライブラリ (MSAL)](https://www.nuget.org/packages/Microsoft.Identity.Client/) を使用します。MSAL SDK には、[Azure AD v2 0 エンドポイント](https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview)を操作するための機能が用意されており、開発者は職場または学校 (Azure Active Directory) アカウント、および個人用 (Microsoft) アカウントの両方に対する認証を処理する 1 つのコード フローを記述することができます。 16 | 17 | ## MSAL プレビューに関する重要な注意事項 18 | 19 | このライブラリは、運用環境での使用に適しています。 このライブラリに対しては、現在の運用ライブラリと同じ運用レベルのサポートを提供します。 プレビュー中にこのライブラリの API、内部キャッシュの形式、および他のメカニズムを変更する場合があります。これは、バグの修正や機能強化の際に実行する必要があります。 これは、アプリケーションに影響を与える場合があります。 例えば、キャッシュ形式を変更すると、再度サインインが要求されるなどの影響をユーザーに与えます。 API を変更すると、コードの更新が要求される場合があります。 一般提供リリースが実施されると、プレビュー バージョンを使って作成されたアプリケーションは動作しなくなるため、6 か月以内に一般提供バージョンに更新することが求められます。 20 | 21 | ## 前提条件 22 | 23 | このサンプルを実行するには次のものが必要です: 24 | 25 | * [Visual Studio 2015](https://www.visualstudio.com/en-us/downloads) 26 | * [Microsoft アカウント](https://www.outlook.com)または [Office 365 for Business アカウント](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account)のいずれか。Office 365 アプリのビルドを開始するために必要なリソースを含む、[Office 365 Developer サブスクリプション](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account)にサインアップできます。 27 | 28 | ## アプリケーションの登録 29 | 30 | 1. 個人用アカウント、あるいは職場または学校アカウントのいずれかを使用して、[アプリ登録ポータル](https://apps.dev.microsoft.com/)にサインインします。 31 | 32 | 2. **[アプリの追加]** を選択します。 33 | 34 | 3. アプリの名前を入力して、**[アプリケーションの作成]** を選択します。 35 | 36 | 登録ページが表示され、アプリのプロパティが一覧表示されます。 37 | 38 | 4. アプリケーション ID をコピーします。これは、アプリの一意識別子です。 39 | 40 | 5. **[アプリケーション シークレット]** で、**[新しいパスワードを生成する]** を選びます。**[新しいパスワードを生成する]** ダイアログからパスワードをコピーします。 41 | 42 | 次のセクションで、アプリケーション ID とパスワードを使用してサンプル アプリを構成します。 43 | 44 | 6. **[プラットフォーム]** で、**[プラットフォームの追加]** を選択します。 45 | 46 | 7. **[Web]** を選択します。 47 | 48 | 8. **[暗黙的フローを許可する]** のチェック ボックスが選択されていることを確認して、リダイレクト URI として *http://localhost:55065/* を入力します。 49 | 50 | **[暗黙的フローを許可する]** オプションにより、ハイブリッド フローが有効になります。認証時に、アクセス トークンを取得するためにアプリが使用できるサインイン情報 (id_token) と成果物 (この場合は、認証コード) の両方をアプリで受信できるようになります。 51 | 52 | 9. **[保存]** を選択します。 53 | 54 | ## サンプルの構築と実行 55 | 56 | 1. ASP.NET 4.6 用 Microsoft Graph Connect のサンプルをダウンロードするか、クローンを作成します。 57 | 58 | 2. Visual Studio でサンプル ソリューションを開きます。 59 | 60 | 3. ルート ディレクトリの Web.config ファイルで、**ida:AppId** と **ida:AppSecret** のプレースホルダ―の値をアプリの登録時にコピーしたアプリケーションの ID とパスワードと置き換えます。 61 | 62 | 4. F5 キーを押して、サンプルを構築して実行します。これにより、NuGet パッケージの依存関係が復元され、アプリが開きます。 63 | 64 | >パッケージのインストール中にエラーが発生した場合は、ソリューションを保存したローカル パスが長すぎたり深すぎたりしていないかご確認ください。ドライブのルート近くにソリューションを移動すると問題が解決します。 65 | 66 | 5. 個人用あるいは職場または学校アカウントでサインインし、要求されたアクセス許可を付与します。 67 | 68 | 6. **[メール アドレスの取得]** ボタンを選択します。操作が完了すると、サインインしているユーザーのメール アドレスがページに表示されます。 69 | 70 | 7. 必要に応じて、受信者一覧とメールの件名を編集し、**[メールの送信]** ボタンを選択します。メールが送信されると、ボタンの下に成功メッセージが表示されます。 71 | 72 | 8. 次の手順:[ASP.NET 4.6 用 Microsoft Graph スニペットのサンプル](https://github.com/microsoftgraph/aspnet-snippets-sample)を参照して、Microsoft Graph の一般的な操作の例を確認します。 73 | 74 | ## ノートのコード 75 | 76 | > 注:ASP.NET MVC アプリで Microsoft Graph API を呼び出すためのコードを理解するには、「[ASP.NET 4.6 MVC アプリで Microsoft Graph を開始する](https://graph.microsoft.io/en-us/docs/platform/aspnetmvc)」をご覧ください。 77 | 78 | - [Startup.Auth.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/App_Start/Startup.Auth.cs)。現在のユーザーを認証して、サンプルのトークン キャッシュを初期化します。 79 | 80 | - [SessionTokenCache.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/TokenStorage/SessionTokenCache.cs).ユーザーのトークン情報を保存します。これを独自のカスタム トークン キャッシュと置き換えることができます。詳細については、「[マルチテナント アプリケーションのアクセス トークンのキャッシュ](https://azure.microsoft.com/en-us/documentation/articles/guidance-multitenant-identity-token-cache/)」を参照してください。 81 | 82 | - [SampleAuthProvider.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SampleAuthProvider.cs)。ローカルの IAuthProvider インターフェイスを実装して、MSAL **AcquireTokenSilentAsync** メソッドを使用してアクセス トークンを取得します。これを独自の認証プロバイダーと置き換えることができます。 83 | 84 | - [SDKHelper.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SDKHelper.cs)。Microsoft Graph との対話に使用される [Microsoft Graph .NET クライアント ライブラリ](https://github.com/microsoftgraph/msgraph-sdk-dotnet)の **GraphServiceClient** を初期化します。 85 | 86 | - [HomeController.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Controllers/HomeController.cs)。呼び出しを構築して Microsoft Graph サービスに送信し、その応答を処理するために **GraphServiceClient** を使用するメソッドが含まれています。 87 | - **GetMyEmailAddress** アクションは、**メール** プロパティまたは **userPrincipalName** プロパティから現在のユーザーのメール アドレスを取得します。 88 | - **SendMail** アクションは、現在のユーザーに代わってメールを送信します。 89 | 90 | - [Graph.cshtml](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Views/Home/Graph.cshtml).サンプルの UI が含まれています。 91 | 92 | ## 質問とコメント 93 | 94 | このサンプルに関するフィードバックをお寄せください。質問や提案につきましては、このリポジトリの「[問題](https://github.com/microsoftgraph/aspnet-connect-sample/issues)」セクションで送信できます。 95 | 96 | お客様からのフィードバックを重視しています。[スタック オーバーフロー](http://stackoverflow.com/questions/tagged/microsoftgraph)でご連絡いただけます。ご質問には [MicrosoftGraph] のタグを付けてください。 97 | 98 | ## 投稿 ## 99 | 100 | このサンプルに投稿する場合は、[CONTRIBUTING.md](CONTRIBUTING.md) を参照してください。 101 | 102 | このプロジェクトでは、[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) が採用されています。詳細については、「[規範に関する FAQ](https://opensource.microsoft.com/codeofconduct/faq/)」を参照してください。または、その他の質問やコメントがあれば、[opencode@microsoft.com](mailto:opencode@microsoft.com) までにお問い合わせください。 103 | 104 | ## 追加リソース 105 | 106 | - [その他の Microsoft Graph Connect サンプル](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 107 | - [Microsoft Graph の概要](http://graph.microsoft.io) 108 | - [Office 開発者向けコード サンプル](http://dev.office.com/code-samples) 109 | - [Office デベロッパー センター](http://dev.office.com/) 110 | 111 | ## 著作権 112 | Copyright (c) 2016 Microsoft. All rights reserved. 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /README-Localized/README-pt-br.md: -------------------------------------------------------------------------------- 1 | # Exemplo de conexão com o Microsoft Graph para ASP.NET 4.6 2 | 3 | ## Sumário 4 | 5 | * [Pré-requisitos](#prerequisites) 6 | * [Registrar o aplicativo](#register-the-application) 7 | * [Criar e executar o exemplo](#build-and-run-the-sample) 8 | * [Código da observação](#code-of-note) 9 | * [Perguntas e comentários](#questions-and-comments) 10 | * [Colaboração](#contributing) 11 | * [Recursos adicionais](#additional-resources) 12 | 13 | Este exemplo mostra como conectar um aplicativo Web ASP.NET 4.6 MVC a uma conta corporativa ou de estudante (Azure Active Directory) da Microsoft ou a uma conta pessoal (Microsoft) usando a API do Microsoft Graph para recuperar a imagem de perfil de um usuário, carregar a imagem para o OneDrive e enviar um email que contém a foto como anexo e o link de compartilhamento em seu texto. O exemplo usa a [Biblioteca de Cliente .NET do Microsoft Graph](https://github.com/microsoftgraph/msgraph-sdk-dotnet) para trabalhar com dados retornados pelo Microsoft Graph. 14 | 15 | Além disso, o exemplo usa a [Biblioteca de Autenticação da Microsoft (MSAL)](https://www.nuget.org/packages/Microsoft.Identity.Client/) para autenticação. O SDK da MSAL fornece recursos para trabalhar com o [ponto de extremidade do Microsoft Azure AD versão 2.0](https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview), que permite aos desenvolvedores gravar um único fluxo de código para tratar da autenticação de contas pessoais (Microsoft), corporativas ou de estudantes (Azure Active Directory). 16 | 17 | ## Observação importante sobre a Visualização da MSAL 18 | 19 | Esta biblioteca é adequada para uso em um ambiente de produção. Ela recebe o mesmo suporte de nível de produção que fornecemos às nossas bibliotecas de produção atuais. Durante a visualização, podemos fazer alterações na API, no formato de cache interno e em outros mecanismos desta biblioteca, que você será solicitado a implementar juntamente com correções de bugs ou melhorias de recursos. Isso pode impactar seu aplicativo. Por exemplo, uma alteração no formato de cache pode impactar seus usuários, exigindo que eles entrem novamente. Uma alteração na API pode requerer que você atualize seu código. Quando fornecermos a versão de Disponibilidade Geral, você será solicitado a atualizar a versão de Disponibilidade Geral no prazo de seis meses, pois os aplicativos escritos usando uma versão de visualização da biblioteca podem não funcionar mais. 20 | 21 | ## Pré-requisitos 22 | 23 | Este exemplo requer o seguinte: 24 | 25 | * [Visual Studio 2015](https://www.visualstudio.com/en-us/downloads) 26 | * A [conta da Microsoft](https://www.outlook.com) ou a [conta do Office 365 para empresas](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). Inscreva-se em uma [Assinatura de Desenvolvedor do Office 365](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account) que inclua os recursos necessários para começar a criar aplicativos do Office 365. 27 | 28 | ## Registrar o aplicativo 29 | 30 | 1. Entre no [Portal de Registro do Aplicativo](https://apps.dev.microsoft.com/) usando sua conta pessoal ou sua conta comercial ou escolar. 31 | 32 | 2. Escolha **Adicionar um aplicativo**. 33 | 34 | 3. Insira um nome para o aplicativo e escolha **Criar aplicativo**. 35 | 36 | A página de registro é exibida, listando as propriedades do seu aplicativo. 37 | 38 | 4. Copie a ID do Aplicativo. Esse é o identificador exclusivo do aplicativo. 39 | 40 | 5. Em **Segredos do Aplicativo**, escolha **Gerar Nova Senha**. Copie a senha da caixa de diálogo **Nova senha gerada**. 41 | 42 | Você usará a ID do aplicativo e a senha para configurar o aplicativo de exemplo na próxima seção. 43 | 44 | 6. Em **Plataformas**, escolha **Adicionar plataforma**. 45 | 46 | 7. Escolha **Web**. 47 | 48 | 8. Verifique se a caixa de seleção **Permitir Fluxo Implícito** está selecionada e insira *http://localhost:55065/* como o URI de redirecionamento. 49 | 50 | A opção **Permitir Fluxo Implícito** habilita o fluxo híbrido. Durante a autenticação, isso permite que o aplicativo receba informações de entrada (o id_token) e artefatos (neste caso, um código de autorização) que o aplicativo pode usar para obter um token de acesso. 51 | 52 | 9. Escolha **Salvar**. 53 | 54 | ## Criar e executar o exemplo 55 | 56 | 1. Baixe ou clone o Exemplo de Conexão com o Microsoft Graph para ASP.NET 4.6. 57 | 58 | 2. Abra a solução de exemplo no Visual Studio. 59 | 60 | 3. No arquivo Web.config no diretório raiz, substitua os valores dos espaços reservados **ida:AppId** e **ida:AppSecret** pela ID de aplicativo e senha copiadas durante o registro do aplicativo. 61 | 62 | 4. Pressione F5 para criar e executar o exemplo. Isso restaurará dependências do pacote NuGet e abrirá o aplicativo. 63 | 64 | >Caso receba mensagens de erro durante a instalação de pacotes, verifique se o caminho para o local onde você colocou a solução não é muito longo ou extenso. Para resolver esse problema, coloque a solução junto à raiz da unidade. 65 | 66 | 5. Entre com sua conta pessoal,corporativa ou de estudante, e conceda as permissões solicitadas. 67 | 68 | 6. Escolha o botão **Obter endereço de email**. Quando a operação for concluída, o endereço de email do usuário conectado será exibido na página. 69 | 70 | 7. Como alternativa, edite a lista de destinatários e o assunto do email e, em seguida, escolha o botão **Enviar email**. Quando o email for enviado, será exibida uma mensagem de sucesso abaixo do botão. 71 | 72 | 8. Próximas etapas: Confira o tópico [Exemplo de trechos de código do Microsoft Graph para ASP.NET 4.6](https://github.com/microsoftgraph/aspnet-snippets-sample) para ver exemplos de operações comuns do Microsoft Graph. 73 | 74 | ## Código da observação 75 | 76 | > Observação: Para compreender o código de chamada para a API do Microsoft Graph em um aplicativo ASP.NET MVC, confira o tópico [Começar a usar o Microsoft Graph em um aplicativo ASP.NET 4.6 MVC](https://graph.microsoft.io/en-us/docs/platform/aspnetmvc). 77 | 78 | - [Startup.Auth.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/App_Start/Startup.Auth.cs). Autentica o usuário atual e inicializa o cache de token do exemplo. 79 | 80 | - [SessionTokenCache.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/TokenStorage/SessionTokenCache.cs). Armazena as informações de token do usuário. Você pode substituir pelo seu próprio cache de token personalizado. Saiba mais em [Armazenamento de tokens de acesso em cache em um aplicativo de vários locatários](https://azure.microsoft.com/en-us/documentation/articles/guidance-multitenant-identity-token-cache/). 81 | 82 | - [SampleAuthProvider.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SampleAuthProvider.cs). Implementa a interface IAuthProvider local e obtém acesso a um token usando o método **AcquireTokenSilentAsync da MSAL**. Isso pode ser substituído pelo seu próprio provedor de autenticação. 83 | 84 | - [SDKHelper.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SDKHelper.cs). Inicializa o **GraphServiceClient**, na [Biblioteca do Cliente .NET para Microsoft Graph](https://github.com/microsoftgraph/msgraph-sdk-dotnet), que é usado para interagir com o Microsoft Graph. 85 | 86 | - [HomeController.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Controllers/HomeController.cs). Contém métodos que usam o **GraphServiceClient** para criar e enviar chamadas para o serviço do Microsoft Graph e processar a resposta. 87 | - A ação **GetMyEmailAddress** obtém o endereço de email do usuário atual das propriedades **mail** ou **userPrincipalName**. 88 | - A ação **SendMail** envia um email em nome do usuário atual. 89 | 90 | - [Graph.cshtml](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Views/Home/Graph.cshtml). Contém a interface de usuário do exemplo. 91 | 92 | ## Perguntas e comentários 93 | 94 | Gostaríamos de saber sua opinião sobre este exemplo. Você pode nos enviar suas perguntas e sugestões por meio da seção [Issues](https://github.com/microsoftgraph/aspnet-connect-sample/issues) deste repositório. 95 | 96 | Seus comentários são importantes para nós. Junte-se a nós na página [Stack Overflow](http://stackoverflow.com/questions/tagged/microsoftgraph). Marque suas perguntas com [MicrosoftGraph]. 97 | 98 | ## Colaboração ## 99 | 100 | Se quiser contribuir para esse exemplo, confira [CONTRIBUTING.md](CONTRIBUTING.md). 101 | 102 | Este projeto adotou o [Código de Conduta do Código Aberto da Microsoft](https://opensource.microsoft.com/codeofconduct/). Para saber mais, confira as [Perguntas frequentes do Código de Conduta](https://opensource.microsoft.com/codeofconduct/faq/) ou contate [opencode@microsoft.com](mailto:opencode@microsoft.com) se tiver outras dúvidas ou comentários. 103 | 104 | ## Recursos adicionais 105 | 106 | - [Outros exemplos de conexão usando o Microsoft Graph](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 107 | - [Visão geral do Microsoft Graph](http://graph.microsoft.io) 108 | - [Exemplos de código para desenvolvedores do Office](http://dev.office.com/code-samples) 109 | - [Centro de Desenvolvimento do Office](http://dev.office.com/) 110 | 111 | ## Direitos autorais 112 | Copyright © 2016 Microsoft. Todos os direitos reservados. 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /README-Localized/README-ru-ru.md: -------------------------------------------------------------------------------- 1 | # Пример приложения, подключающегося с использованием Microsoft Graph, для ASP.NET 4.6 2 | 3 | ## Содержание 4 | 5 | * [Необходимые компоненты](#prerequisites) 6 | * [Регистрация приложения](#register-the-application) 7 | * [Сборка и запуск примера](#build-and-run-the-sample) 8 | * [Полезный код](#code-of-note) 9 | * [Вопросы и комментарии](#questions-and-comments) 10 | * [Участие](#contributing) 11 | * [Дополнительные ресурсы](#additional-resources) 12 | 13 | В этом примере показано, как подключить веб-приложение на базе ASP.NET 4.6 MVC к рабочей или учебной учетной записи Майкрософт (Azure Active Directory) либо личной учетной записи Майкрософт с помощью API Microsoft Graph, чтобы получить изображение профиля пользователя, передать это изображение в OneDrive и отправить электронное письмо с вложенной фотографией и ссылкой для общего доступа, указанной в тексте сообщения. Для работы с данными, возвращаемыми Microsoft Graph, используется [клиентская библиотека Microsoft Graph .NET](https://github.com/microsoftgraph/msgraph-sdk-dotnet). 14 | 15 | Кроме того, для проверки подлинности в этом примере используется [Microsoft Authentication Library (MSAL)](https://www.nuget.org/packages/Microsoft.Identity.Client/). В пакете SDK MSAL предусмотрены функции для работы с [конечной точкой Azure AD версии 2.0](https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview), которая позволяет разработчикам создать единый поток кода для проверки подлинности как рабочих или учебных (Azure Active Directory), так и личных учетных записей Майкрософт. 16 | 17 | ## Важное примечание о предварительной версии MSAL 18 | 19 | Эту библиотеку можно использовать в рабочей среде. Для этой библиотеки мы предоставляем тот же уровень поддержки, что и для текущих библиотек рабочей среды. Мы можем внести изменения в API, формат внутреннего кэша и другие функциональные элементы, касающиеся этой предварительной версии библиотеки, которые вам потребуется принять вместе с улучшениями или исправлениями. Это может повлиять на ваше приложение. Например, в результате изменения формата кэша пользователям может потребоваться опять выполнить вход. При изменении API может потребоваться обновить код. Когда мы предоставим общедоступный выпуск, вам потребуется выполнить обновление до общедоступной версии в течение шести месяцев, так как приложения, написанные с использованием предварительной версии библиотеки, могут больше не работать. 20 | 21 | ## Необходимые условия 22 | 23 | Для этого примера требуются следующие компоненты: 24 | 25 | * [Visual Studio 2015](https://www.visualstudio.com/en-us/downloads) 26 | * [Учетная запись Майкрософт](https://www.outlook.com) или [учетная запись Office 365 для бизнеса](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). Вы можете подписаться на [план Office 365 для разработчиков](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account), который включает ресурсы, необходимые для создания приложений Office 365. 27 | 28 | ## Регистрация приложения 29 | 30 | 1. Войдите на [портал регистрации приложений](https://apps.dev.microsoft.com/) с помощью личной, рабочей или учебной учетной записи. 31 | 32 | 2. Нажмите кнопку **Добавить приложение**. 33 | 34 | 3. Введите имя приложения и нажмите кнопку **Создать приложение**. 35 | 36 | Откроется страница регистрации со свойствами приложения. 37 | 38 | 4. Скопируйте идентификатор приложения. Это уникальный идентификатор приложения. 39 | 40 | 5. В разделе **Секреты приложения** нажмите кнопку **Создать новый пароль**. Скопируйте пароль из диалогового окна **Новый пароль создан**. 41 | 42 | Идентификатор приложения и пароль будут использованы для настройки примера приложения в следующем разделе. 43 | 44 | 6. В разделе **Платформы** выберите элемент **Добавление платформы**. 45 | 46 | 7. Выберите пункт **Веб**. 47 | 48 | 8. Установите флажок **Разрешить неявный поток** и введите *http://localhost:55065/* в качестве URI перенаправления. 49 | 50 | Параметр **Разрешить неявный поток** включает гибридный поток. Благодаря этому при проверке подлинности приложение может получить данные для входа (id_token) и артефакты (в данном случае — код авторизации), которые оно может использовать, чтобы получить маркер доступа. 51 | 52 | 9. Нажмите кнопку **Сохранить**. 53 | 54 | ## Сборка и запуск примера 55 | 56 | 1. Скачайте или клонируйте пример приложения, подключающегося с использованием Microsoft Graph, для ASP.NET 4.6. 57 | 58 | 2. Откройте пример решения в Visual Studio. 59 | 60 | 3. В корневом каталоге в файле Web.config замените заполнители **ida:AppId** и **ida:AppSecret** на идентификатор приложения и пароль, которые вы скопировали при регистрации приложения. 61 | 62 | 4. Нажмите клавишу F5 для сборки и запуска примера. При этом будут восстановлены зависимости пакета NuGet и открыто приложение. 63 | 64 | >Если при установке пакетов возникают ошибки, убедитесь, что локальный путь к решению не слишком длинный. Чтобы устранить эту проблему, переместите решение ближе к корню диска. 65 | 66 | 5. Войдите с помощью личной, рабочей или учебной учетной записи и предоставьте необходимые разрешения. 67 | 68 | 6. Нажмите кнопку **Получить адрес электронной почты**. После завершения операции на странице отобразится электронный адрес пользователя, выполнившего вход. 69 | 70 | 7. При необходимости измените список получателей и тему сообщения электронной почты, а затем нажмите кнопку **Отправить сообщение**. Под кнопкой отобразится сообщение об успешной отправке почты. 71 | 72 | 8. Дальнейшие действия: В статье [Пример фрагментов кода Microsoft Graph для ASP.NET 4.6](https://github.com/microsoftgraph/aspnet-snippets-sample) ознакомьтесь с примерами наиболее распространенных операций Microsoft Graph. 73 | 74 | ## Полезный код 75 | 76 | > Примечание. Сведения о коде для вызова API Microsoft Graph в приложении ASP.NET MVC см. в статье [Начало работы с Microsoft Graph в приложении ASP.NET 4.6 MVC](https://graph.microsoft.io/en-us/docs/platform/aspnetmvc). 77 | 78 | - [Startup.Auth.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/App_Start/Startup.Auth.cs). Выполняет проверку подлинности для текущего пользователя и инициализирует кэш маркеров примера. 79 | 80 | - [SessionTokenCache.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/TokenStorage/SessionTokenCache.cs). Хранит информацию о маркере пользователя. Вы можете заменить его на собственный кэш маркеров. Дополнительные сведения см. в статье [Кэширование маркеров доступа в мультитенантном приложении](https://azure.microsoft.com/en-us/documentation/articles/guidance-multitenant-identity-token-cache/). 81 | 82 | - [SampleAuthProvider.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SampleAuthProvider.cs). Реализует локальный интерфейс IAuthProvider и получает маркер доступа с помощью метода MSAL **AcquireTokenSilentAsync**. Вы можете заменить его на собственного поставщика проверки подлинности. 83 | 84 | - [SDKHelper.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SDKHelper.cs). Инициализирует класс **GraphServiceClient** из [клиентской библиотеки .NET Microsoft Graph](https://github.com/microsoftgraph/msgraph-sdk-dotnet), используемой для взаимодействия с Microsoft Graph. 85 | 86 | - [HomeController.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Controllers/HomeController.cs). Содержит методы, использующие класс **GraphServiceClient** для создания и отправки вызовов в службу Microsoft Graph и обработки ответа. 87 | - Действие **GetMyEmailAddress** позволяет получить адрес электронной почты текущего пользователя из свойства **mail** или **userPrincipalName**. 88 | - Действие **SendMail** позволяет отправить сообщение электронной почты от имени текущего пользователя. 89 | 90 | - [Graph.cshtml](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Views/Home/Graph.cshtml). Содержит пользовательский интерфейс образца. 91 | 92 | ## Вопросы и комментарии 93 | 94 | Мы будем рады узнать ваше мнение об этом примере. Вы можете отправлять нам вопросы и предложения на вкладке [Issues](https://github.com/microsoftgraph/aspnet-connect-sample/issues) этого репозитория. 95 | 96 | Ваш отзыв важен для нас. Для связи с нами используйте сайт [Stack Overflow](http://stackoverflow.com/questions/tagged/microsoftgraph). Помечайте свои вопросы тегом [MicrosoftGraph]. 97 | 98 | ## Участие ## 99 | 100 | Если вы хотите добавить код в этот пример, просмотрите статью [CONTRIBUTING.md](CONTRIBUTING.md). 101 | 102 | Этот проект соответствует [правилам поведения Майкрософт, касающимся обращения с открытым кодом](https://opensource.microsoft.com/codeofconduct/). Читайте дополнительные сведения в [разделе вопросов и ответов по правилам поведения](https://opensource.microsoft.com/codeofconduct/faq/) или отправляйте новые вопросы и замечания по адресу [opencode@microsoft.com](mailto:opencode@microsoft.com). 103 | 104 | ## Дополнительные ресурсы 105 | 106 | - [Другие примеры Microsoft Graph Connect](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 107 | - [Общие сведения о Microsoft Graph](http://graph.microsoft.io) 108 | - [Примеры кода приложений для Office](http://dev.office.com/code-samples) 109 | - [Центр разработки для Office](http://dev.office.com/) 110 | 111 | ## Авторское право 112 | (c) Корпорация Майкрософт (Microsoft Corporation), 2016. Все права защищены. 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /README-Localized/README-zh-cn.md: -------------------------------------------------------------------------------- 1 | # ASP.NET 4.6 的 Microsoft Graph Connect 示例 2 | 3 | ## 目录 4 | 5 | * [先决条件](#prerequisites) 6 | * [注册应用程序](#register-the-application) 7 | * [生成和运行示例](#build-and-run-the-sample) 8 | * [注释代码](#code-of-note) 9 | * [问题和意见](#questions-and-comments) 10 | * [参与](#contributing) 11 | * [其他资源](#additional-resources) 12 | 13 | 此示例展示了如何使用 Microsoft Graph API 将 ASP.NET 4.6 MVC Web 应用连接到 Microsoft 工作或学校帐户 (Azure Active Directory) 或个人 (Microsoft) 帐户,从而检索用户的个人资料照片,将此照片上传到 OneDrive,并发送将此照片作为附件且文本中包含共享链接的电子邮件。 它使用 [Microsoft Graph .NET 客户端库](https://github.com/microsoftgraph/msgraph-sdk-dotnet)来处理 Microsoft Graph 返回的数据。 14 | 15 | 此外,此示例使用 [Microsoft 身份验证库 (MSAL)](https://www.nuget.org/packages/Microsoft.Identity.Client/) 进行身份验证。MSAL SDK 提供可使用 [Azure AD v2.0 终结点](https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview)的功能,借助该终结点,开发人员可以编写单个代码流来处理对工作或学校 (Azure Active Directory) 帐户或个人 (Microsoft) 帐户的身份验证。 16 | 17 | ## 有关 MSAL 预览版的重要说明 18 | 19 | 此库适用于生产环境。 我们为此库提供的生产级支持与为当前生产库提供的支持相同。 在预览期间,我们可能会更改 API、内部缓存格式和此库的其他机制,必须接受这些更改以及 bug 修复或功能改进。 这可能会影响应用。 例如,缓存格式更改可能会对用户造成影响,如要求用户重新登录。 API 更改可能会要求更新代码。 在我们提供通用版后,必须在 6 个月内更新到通用版,因为使用预览版库编写的应用可能不再可用。 20 | 21 | ## 先决条件 22 | 23 | 此示例需要以下各项: 24 | 25 | * [Visual Studio 2015](https://www.visualstudio.com/en-us/downloads) 26 | * [Microsoft 帐户](https://www.outlook.com)或 [Office 365 商业版帐户](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account)。可以注册 [Office 365 开发人员订阅](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account),其中包含开始构建 Office 365 应用所需的资源。 27 | 28 | ## 注册应用 29 | 30 | 1. 使用个人或工作或学校帐户登录到 [应用注册门户](https://apps.dev.microsoft.com/)。 31 | 32 | 2. 选择“**添加应用**”。 33 | 34 | 3. 输入应用的名称,并选择“**创建应用程序**”。 35 | 36 | 将显示注册页,其中列出应用的属性。 37 | 38 | 4. 复制应用程序 ID。这是应用的唯一标识符。 39 | 40 | 5. 在“**应用程序密码**”下,选择“**生成新密码**”。从“**生成的新密码**”对话框复制密码。 41 | 42 | 使用应用程序 ID 和密码在下一部分中配置示例应用。 43 | 44 | 6. 在“**平台**”下,选择“**添加平台**”。 45 | 46 | 7. 选择“**Web**”。 47 | 48 | 8. 请务必选中“允许隐式流”****复选框,然后输入“http://localhost:55065/”**作为重定向 URI。 49 | 50 | “**允许隐式流**”选项启用混合流。在身份验证过程中,这可使应用同时接收登录信息 (id_token) 以及应用可用来获取访问令牌的项目(在这种情况下,项目为授权代码)。 51 | 52 | 9. 选择“**保存**”。 53 | 54 | ## 生成和运行示例 55 | 56 | 1. 下载或克隆适用于 ASP.NET 4.6 的 Microsoft Graph Connect 示例。 57 | 58 | 2. 在 Visual Studio 中打开示例解决方案。 59 | 60 | 3. 在根目录的 Web.config 文件中,使用你在应用注册过程中复制的应用程序 ID 和密码来替换 **ida:AppId** 和 **ida:AppSecret** 占位符值。 61 | 62 | 4. 按 F5 生成和运行此示例。这将还原 NuGet 包依赖项,并打开应用。 63 | 64 | >如果在安装包时出现任何错误,请确保你放置该解决方案的本地路径并未太长/太深。将解决方案移动到更接近驱动器根目录的位置可以解决此问题。 65 | 66 | 5. 使用个人帐户/工作或学校帐户登录,并授予所请求的权限。 67 | 68 | 6. 选择“**获取电子邮件地址**”按钮。完成此操作后,网页上会显示登录用户的电子邮件地址。 69 | 70 | 7. 还可以编辑收件人列表和电子邮件主题,然后选择“**发送电子邮件**”按钮。在邮件发送后,按钮下方将显示成功消息。 71 | 72 | 8. 后续步骤:签出[适用于 ASP.NET 4.6 的 Microsoft Graph 代码段示例](https://github.com/microsoftgraph/aspnet-snippets-sample)查看 Microsoft Graph 的常见操作示例。 73 | 74 | ## 要注意的代码 75 | 76 | > 注意:要了解在 ASP.NET 4.6 MVC 应用中调用 Microsoft Graph API 的代码,请参阅 [ASP.NET MVC 应用中的 Microsoft Graph 入门](https://graph.microsoft.io/en-us/docs/platform/aspnetmvc)。 77 | 78 | - [Startup.Auth.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/App_Start/Startup.Auth.cs)。对当前用户进行身份验证,并初始化此示例的令牌缓存。 79 | 80 | - [SessionTokenCache.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/TokenStorage/SessionTokenCache.cs).存储用户的令牌信息。可以使用你自己的自定义令牌缓存来替换此信息。从[在多租户应用程序中缓存访问令牌](https://azure.microsoft.com/en-us/documentation/articles/guidance-multitenant-identity-token-cache/)了解详细信息。 81 | 82 | - [SampleAuthProvider.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SampleAuthProvider.cs)。实现本地 IAuthProvider 接口,并通过使用 MSAL **AcquireTokenSilentAsync** 方法获取一个访问令牌。可以使用你自己的身份验证提供程序来替换此方法。 83 | 84 | - [SDKHelper.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SDKHelper.cs)。初始化来自用于与 Microsoft Graph 交互的 [Microsoft Graph .NET 客户端库](https://github.com/microsoftgraph/msgraph-sdk-dotnet)中的 **GraphServiceClient**。 85 | 86 | - [HomeController.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Controllers/HomeController.cs)。包含使用 **GraphServiceClient** 生成并发送到 Microsoft Graph 服务的调用并处理响应的方法。 87 | - **GetMyEmailAddress** 操作从 **mail** 或 **userPrincipalName** 属性获取当前用户的电子邮件地址。 88 | - **SendMail** 操作将代表当前用户发送一封电子邮件。 89 | 90 | - [Graph.cshtml](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Views/Home/Graph.cshtml).包含该示例的 UI。 91 | 92 | ## 问题和意见 93 | 94 | 我们乐意倾听你有关此示例的反馈。你可以在该存储库中的[问题](https://github.com/microsoftgraph/aspnet-connect-sample/issues) 部分将问题和建议发送给我们。 95 | 96 | 我们非常重视你的反馈意见。请在 [Stack Overflow](http://stackoverflow.com/questions/tagged/microsoftgraph) 上与我们联系。使用 [MicrosoftGraph] 标记出你的问题。 97 | 98 | ## 参与 ## 99 | 100 | 如果想要参与本示例,请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)。 101 | 102 | 此项目采用 [Microsoft 开源行为准则](https://opensource.microsoft.com/codeofconduct/)。有关详细信息,请参阅 [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)(行为准则常见问题解答),有任何其他问题或意见,也可联系 [opencode@microsoft.com](mailto:opencode@microsoft.com)。 103 | 104 | ## 其他资源 105 | 106 | - [其他 Microsoft Graph Connect 示例](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 107 | - [Microsoft Graph 概述](http://graph.microsoft.io) 108 | - [Office 开发人员代码示例](http://dev.office.com/code-samples) 109 | - [Office 开发人员中心](http://dev.office.com/) 110 | 111 | ## 版权 112 | 版权所有 (c) 2016 Microsoft。保留所有权利。 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /README-Localized/README-zh-tw.md: -------------------------------------------------------------------------------- 1 | # Microsoft Graph Connect 範例 (適用於 ASP.NET 4.6) 2 | 3 | ## 目錄 4 | 5 | * [必要條件](#prerequisites) 6 | * [註冊應用程式](#register-the-application) 7 | * [建置及執行範例](#build-and-run-the-sample) 8 | * [附註的程式碼](#code-of-note) 9 | * [問題和建議](#questions-and-comments) 10 | * [參與](#contributing) 11 | * [其他資源](#additional-resources) 12 | 13 | 這個範例會顯示如何使用 Microsoft Graph API 將 ASP.NET 4.6 MVC Web 應用程式連線至 Microsoft 工作或學校 (Azure Active Directory) 或個人 (Microsoft) 帳戶,用來擷取使用者的基本資料圖片、將圖片上傳至 OneDrive,並傳送含有相片作為附件且文字中包含共用連結的電子郵件。 它會使用 [Microsoft Graph.NET 用戶端程式庫](https://github.com/microsoftgraph/msgraph-sdk-dotnet),使用 Microsoft Graph 所傳回的資料。 14 | 15 | 此外,範例會使用 [Microsoft 驗證程式庫 (MSAL)](https://www.nuget.org/packages/Microsoft.Identity.Client/) 進行驗證。MSAL SDK 提供功能以使用 [Azure AD v2.0 端點](https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview),可讓開發人員撰寫單一程式碼流程,控制工作或學校 (Azure Active Directory) 和個人 (Microsoft) 帳戶的驗證。 16 | 17 | ## MSAL 預覽相關的重要事項 18 | 19 | 這個程式庫適合在實際執行環境中使用。 我們為我們目前的實際執行程式庫提供與此程式庫相同的實際執行層級支援。 在預覽期間,我們可能會變更此程式庫的 API、內部快取格式和其他機制,您將必須對此程式庫進行錯誤修復或增強功能。 這可能會影響您的應用程式。 舉例來說,變更快取格式可能會影響您的使用者,例如需要使用者重新登入。 API 變更可能需要更新您的程式碼。 當我們提供「一般可用性」版本時,將要求您在六個月內更新至「一般可用性」版本,因為使用程式庫預覽版本所撰寫的應用程式可能無法運作。 20 | 21 | ## 必要條件 22 | 23 | 此範例需要下列項目: 24 | 25 | * [Visual Studio 2015](https://www.visualstudio.com/en-us/downloads) 26 | * [Microsoft 帳戶](https://www.outlook.com)或[商務用 Office 365 帳戶](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account)。您可以註冊 [Office 365 開發人員訂用帳戶](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account),其中包含開始建置 Office 365 應用程式所需的資源。 27 | 28 | ## 註冊應用程式 29 | 30 | 1. 使用您的個人或工作或學校帳戶登入[應用程式註冊入口網站](https://apps.dev.microsoft.com/)。 31 | 32 | 2. 選擇 [新增應用程式]****。 33 | 34 | 3. 為應用程式輸入名稱,然後選擇 [建立應用程式]****。 35 | 36 | [註冊] 頁面隨即顯示,列出您的應用程式的屬性。 37 | 38 | 4. 複製應用程式 ID。這是您的應用程式的唯一識別碼。 39 | 40 | 5. 在 [應用程式密碼]**** 底下,選擇 [產生新密碼]****。從 [產生的新密碼]**** 對話方塊中複製密碼。 41 | 42 | 使用應用程式 ID 和密碼,在下一個區段中設定範例應用程式。 43 | 44 | 6. 在 [平台]**** 底下,選擇 [新增平台]****。 45 | 46 | 7. 選擇 [Web]****。 47 | 48 | 8. 請確定已選取 [允許隱含的流程]**** 核取方塊,然後輸入 *http://localhost:55065/* 做為重新導向 URI。 49 | 50 | [允許隱含的流程]**** 選項會啟用混合式流程。在驗證期間,這可讓應用程式收到登入資訊 (id_token) 和成品 (在這種情況下,是授權程式碼),應用程式可以用來取得存取權杖。 51 | 52 | 9. 選擇 [儲存]****。 53 | 54 | ## 建置及執行範例 55 | 56 | 1. 下載或複製 Microsoft Graph Connect 範例 (適用於 ASP.NET 4.6)。 57 | 58 | 2. 在 Visual Studio 中開啟範例解決方案。 59 | 60 | 3. 在根目錄的 Web.config 檔案中,將 **ida:AppId** 和 **ida:AppSecret** 預留位置值取代為您在應用程式註冊期間複製的應用程式 ID 與密碼。 61 | 62 | 4. 按 F5 以建置及執行範例。這樣會還原 NuGet 封裝相依性,並開啟應用程式。 63 | 64 | >如果您在安裝封裝時看到任何錯誤,請確定您放置解決方案的本機路徑不會太長/太深。將解決方案移靠近您的磁碟機根目錄可解決這個問題。 65 | 66 | 5. 登入您的個人或工作或學校帳戶,並授與要求的權限。 67 | 68 | 6. 選擇 [取得電子郵件地址]**** 按鈕。當作業完成時,登入使用者的電子郵件地址會顯示在頁面中。 69 | 70 | 7. 選擇性編輯收件者清單和電子郵件主旨,然後選擇 [傳送郵件]**** 按鈕。當郵件傳送時,成功的訊息會顯示在按鈕下方。 71 | 72 | 8. 後續步驟:查看 [Microsoft Graph 程式碼片段範例 (適用於 ASP.NET 4.6)](https://github.com/microsoftgraph/aspnet-snippets-sample),以查看一般 Microsoft Graph 作業的範例。 73 | 74 | ## 程式碼附註 75 | 76 | > 附註:若要了解在 ASP.NET MVC 應用程式中用於呼叫 Microsoft Graph API 的程式碼,請參閱[在 ASP.NET 4.6 MVC 應用程式中開始使用 Microsoft Graph](https://graph.microsoft.io/en-us/docs/platform/aspnetmvc)。 77 | 78 | - [Startup.Auth.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/App_Start/Startup.Auth.cs).驗證目前使用者,並初始化範例的權杖快取。 79 | 80 | - [SessionTokenCache.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/TokenStorage/SessionTokenCache.cs).儲存使用者的權杖資訊。您可以將這個項目取代為您自己的自訂權杖快取。在[多租用戶應用程式中的快取存取權杖](https://azure.microsoft.com/en-us/documentation/articles/guidance-multitenant-identity-token-cache/)中深入了解。 81 | 82 | - [SampleAuthProvider.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SampleAuthProvider.cs).實作本機 IAuthProvider 介面,並取得存取權杖,方法是使用 MSAL **AcquireTokenSilentAsync** 方法。您可以將這個項目取代為您自己的驗證提供者。 83 | 84 | - [SDKHelper.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SDKHelper.cs).從 **Microsoft Graph.NET 用戶端程式庫**初始化 [GraphServiceClient](https://github.com/microsoftgraph/msgraph-sdk-dotnet) 用來與 Microsoft Graph 互動。 85 | 86 | - [HomeController.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Controllers/HomeController.cs).包含方法,該方法使用 **GraphServiceClient** 以建置並傳送呼叫至 Microsoft Graph 服務,並且處理回應。 87 | - **GetMyEmailAddress** 動作會從 **mail** 或 **userPrincipalName** 屬性,取得目前使用者的電子郵件地址。 88 | - **SendMail** 動作會代表目前的使用者傳送電子郵件。 89 | 90 | - [Graph.cshtml](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Views/Home/Graph.cshtml).包含範例的 UI。 91 | 92 | ## 問題和建議 93 | 94 | 我們很樂於收到您對於此範例的意見反應。您可以在此儲存機制的[問題](https://github.com/microsoftgraph/aspnet-connect-sample/issues)區段中,將您的問題及建議傳送給我們。 95 | 96 | 我們很重視您的意見。請透過 [Stack Overflow](http://stackoverflow.com/questions/tagged/microsoftgraph) 與我們連絡。以 [MicrosoftGraph] 標記您的問題。 97 | 98 | ## 參與 ## 99 | 100 | 如果您想要參與這個範例,請參閱 [CONTRIBUTING.md](CONTRIBUTING.md)。 101 | 102 | 此專案已採用 [Microsoft 開放原始碼執行](https://opensource.microsoft.com/codeofconduct/)。如需詳細資訊,請參閱[程式碼執行常見問題集](https://opensource.microsoft.com/codeofconduct/faq/),如果有其他問題或意見,請連絡 [opencode@microsoft.com](mailto:opencode@microsoft.com)。 103 | 104 | ## 其他資源 105 | 106 | - [其他 Microsoft Graph connect 範例](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 107 | - [Microsoft Graph 概觀](http://graph.microsoft.io) 108 | - [Office 開發人員程式碼範例](http://dev.office.com/code-samples) 109 | - [Office 開發人員中心](http://dev.office.com/) 110 | 111 | ## 著作權 112 | Copyright (c) 2016 Microsoft.著作權所有,並保留一切權利。 113 | 114 | 115 | 116 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [ARCHIVED] Microsoft Graph Connect Sample for ASP.NET 4.6 2 | 3 | ## IMPORTANT 4 | 5 | **This project is being archived and replaced with the [Build MVC apps with the Microsoft Graph .NET SDK training](https://github.com/microsoftgraph/msgraph-training-aspnetmvcapp). As part of the archival process, we're closing all open issues and pull requests.** 6 | 7 | **You can continue to use this sample "as-is", but it won't be maintained moving forward. We apologize for any inconvenience.** 8 | 9 | ## Table of contents 10 | 11 | * [Prerequisites](#prerequisites) 12 | * [Register the application](#register-the-application) 13 | * [Build and run the sample](#build-and-run-the-sample) 14 | * [Code of note](#code-of-note) 15 | * [Questions and comments](#questions-and-comments) 16 | * [Contributing](#contributing) 17 | * [Additional resources](#additional-resources) 18 | 19 | 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](https://github.com/microsoftgraph/msgraph-sdk-dotnet) to work with data returned by Microsoft Graph. 20 | 21 | In addition, the sample uses the [Microsoft Authentication Library (MSAL)](https://www.nuget.org/packages/Microsoft.Identity.Client/) for authentication. The MSAL SDK provides features for working with the [Azure AD v2.0 endpoint](https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview), which enables developers to write a single code flow that handles authentication for both work or school (Azure Active Directory) and personal (Microsoft) accounts. 22 | 23 | ## Important Note about the MSAL Preview 24 | 25 | 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. 26 | 27 | ## Prerequisites 28 | 29 | This sample requires the following: 30 | 31 | * [Visual Studio 2015](https://www.visualstudio.com/en-us/downloads) 32 | * Either a [Microsoft account](https://www.outlook.com) or [Office 365 for business account](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account). You can sign up for [an Office 365 Developer subscription](https://msdn.microsoft.com/en-us/office/office365/howto/setup-development-environment#bk_Office365Account) that includes the resources that you need to start building Office 365 apps. 33 | 34 | ## Register the application 35 | 36 | 1. Sign into the [App Registration Portal](https://apps.dev.microsoft.com/) using either your personal or work or school account. 37 | 38 | 2. Choose **Add an app**. 39 | 40 | 3. Enter a name for the app, and choose **Create application**. 41 | 42 | The registration page displays, listing the properties of your app. 43 | 44 | 4. Copy the Application Id. This is the unique identifier for your app. 45 | 46 | 5. Under **Application Secrets**, choose **Generate New Password**. Copy the password from the **New password generated** dialog. 47 | 48 | You'll use the application ID and password to configure the sample app in the next section. 49 | 50 | 6. Under **Platforms**, choose **Add platform**. 51 | 52 | 7. Choose **Web**. 53 | 54 | 8. Make sure the **Allow Implicit Flow** check box is selected, and enter *http://localhost:55065/* as the Redirect URI. 55 | 56 | 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. 57 | 58 | 9. Choose **Save**. 59 | 60 | ## Build and run the sample 61 | 62 | 1. Download or clone the Microsoft Graph Connect Sample for ASP.NET 4.6. 63 | 64 | 2. Open the sample solution in Visual Studio. 65 | 66 | 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. 67 | 68 | 4. Press F5 to build and run the sample. This will restore NuGet package dependencies and open the app. 69 | 70 | >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. 71 | 72 | 5. Sign in with your personal or work or school account and grant the requested permissions. 73 | 74 | 6. Choose the **Get email address** button. When the operation completes, the email address of the signed-in user is displayed on the page. 75 | 76 | 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. 77 | 78 | 8. Next steps: Check out the [Microsoft Graph Snippets Sample for ASP.NET 4.6](https://github.com/microsoftgraph/aspnet-snippets-sample) to see examples of common Microsoft Graph operations. 79 | 80 | ## Code of note 81 | 82 | > 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](https://graph.microsoft.io/en-us/docs/platform/aspnetmvc). 83 | 84 | - [Startup.Auth.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/App_Start/Startup.Auth.cs). Authenticates the current user and initializes the sample's token cache. 85 | 86 | - [SessionTokenCache.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/TokenStorage/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](https://azure.microsoft.com/en-us/documentation/articles/guidance-multitenant-identity-token-cache/). 87 | 88 | - [SampleAuthProvider.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/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. 89 | 90 | - [SDKHelper.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Helpers/SDKHelper.cs). Initializes the **GraphServiceClient** from the [Microsoft Graph .NET Client Library](https://github.com/microsoftgraph/msgraph-sdk-dotnet) that's used to interact with the Microsoft Graph. 91 | 92 | - [HomeController.cs](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Controllers/HomeController.cs). Contains methods that use the **GraphServiceClient** to build and send calls to the Microsoft Graph service and to process the response. 93 | - The **GetMyEmailAddress** action gets the email address of the current user from the **mail** or **userPrincipalName** property. 94 | - The **SendMail** action sends an email on behalf of the current user. 95 | 96 | - [Graph.cshtml](/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Microsoft%20Graph%20SDK%20ASPNET%20Connect/Views/Home/Graph.cshtml). Contains the sample's UI. 97 | 98 | ## Questions and comments 99 | 100 | We'd love to get your feedback about this sample. You can send us your questions and suggestions in the [Issues](https://github.com/microsoftgraph/aspnet-connect-sample/issues) section of this repository. 101 | 102 | Your feedback is important to us. Connect with us on [Stack Overflow](http://stackoverflow.com/questions/tagged/microsoftgraph). Tag your questions with [MicrosoftGraph]. 103 | 104 | ## Contributing ## 105 | 106 | If you'd like to contribute to this sample, see [CONTRIBUTING.md](CONTRIBUTING.md). 107 | 108 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 109 | 110 | ## Additional resources 111 | 112 | - [Other Microsoft Graph Connect samples](https://github.com/MicrosoftGraph?utf8=%E2%9C%93&query=-Connect) 113 | - [Microsoft Graph overview](http://graph.microsoft.io) 114 | - [Office developer code samples](http://dev.office.com/code-samples) 115 | - [Office dev center](http://dev.office.com/) 116 | 117 | ## Copyright 118 | Copyright (c) 2016 Microsoft. All rights reserved. 119 | 120 | 121 | 122 | -------------------------------------------------------------------------------- /aspnet-connect-sample.yml: -------------------------------------------------------------------------------- 1 | ### YamlMime:Sample 2 | sample: 3 | - name: Microsoft Graph Connect Sample for ASP.NET 4.6 4 | path: '' 5 | description: This walkthrough shows you how to use the Office 365 Connected Services in Visual Studio 2017. 6 | readme: '' 7 | generateZip: FALSE 8 | isLive: TRUE 9 | technologies: 10 | - Microsoft Graph 11 | - Azure AD 12 | azureDeploy: '' 13 | author: jamescro 14 | platforms: [] 15 | languages: 16 | - C# 17 | extensions: 18 | products: 19 | - OneDrive 20 | - Office 365 21 | scenarios: [] 22 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft Graph SDK ASPNET Connect", "Microsoft Graph SDK ASPNET Connect\Microsoft Graph SDK ASPNET Connect.csproj", "{26148A63-47CC-4A3E-896D-12992A40A89A}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {26148A63-47CC-4A3E-896D-12992A40A89A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {26148A63-47CC-4A3E-896D-12992A40A89A}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {26148A63-47CC-4A3E-896D-12992A40A89A}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {26148A63-47CC-4A3E-896D-12992A40A89A}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/App_GlobalResources/Resource.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace Resources { 12 | using System; 13 | 14 | 15 | /// 16 | /// A strongly-typed resource class, for looking up localized strings, etc. 17 | /// 18 | // This class was auto-generated by the StronglyTypedResourceBuilder 19 | // class via a tool like ResGen or Visual Studio. 20 | // To add or remove a member, edit your .ResX file then rerun ResGen 21 | // with the /str option or rebuild the Visual Studio project. 22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Web.Application.StronglyTypedResourceProxyBuilder", "14.0.0.0")] 23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] 24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 25 | internal class Resource { 26 | 27 | private static global::System.Resources.ResourceManager resourceMan; 28 | 29 | private static global::System.Globalization.CultureInfo resourceCulture; 30 | 31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] 32 | internal Resource() { 33 | } 34 | 35 | /// 36 | /// Returns the cached ResourceManager instance used by this class. 37 | /// 38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 39 | internal static global::System.Resources.ResourceManager ResourceManager { 40 | get { 41 | if (object.ReferenceEquals(resourceMan, null)) { 42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Resources.Resource", global::System.Reflection.Assembly.Load("App_GlobalResources")); 43 | resourceMan = temp; 44 | } 45 | return resourceMan; 46 | } 47 | } 48 | 49 | /// 50 | /// Overrides the current thread's CurrentUICulture property for all 51 | /// resource lookups using this strongly typed resource class. 52 | /// 53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] 54 | internal static global::System.Globalization.CultureInfo Culture { 55 | get { 56 | return resourceCulture; 57 | } 58 | set { 59 | resourceCulture = value; 60 | } 61 | } 62 | 63 | /// 64 | /// Looks up a localized string similar to About. 65 | /// 66 | internal static string About { 67 | get { 68 | return ResourceManager.GetString("About", resourceCulture); 69 | } 70 | } 71 | 72 | /// 73 | /// Looks up a localized string similar to Your application description page.. 74 | /// 75 | internal static string About_Description { 76 | get { 77 | return ResourceManager.GetString("About_Description", resourceCulture); 78 | } 79 | } 80 | 81 | /// 82 | /// Looks up a localized string similar to Microsoft Graph Connect sample for ASP.NET 4.6. 83 | /// 84 | internal static string App_Name { 85 | get { 86 | return ResourceManager.GetString("App_Name", resourceCulture); 87 | } 88 | } 89 | 90 | /// 91 | /// Looks up a localized string similar to Microsoft Graph Connect sample. 92 | /// 93 | internal static string App_Name_Short { 94 | get { 95 | return ResourceManager.GetString("App_Name_Short", resourceCulture); 96 | } 97 | } 98 | 99 | /// 100 | /// Looks up a localized string similar to Caller needs to authenticate.. 101 | /// 102 | internal static string Error_AuthChallengeNeeded { 103 | get { 104 | return ResourceManager.GetString("Error_AuthChallengeNeeded", resourceCulture); 105 | } 106 | } 107 | 108 | /// 109 | /// Looks up a localized string similar to An error occurred while processing your request.. 110 | /// 111 | internal static string Error_Introduction { 112 | get { 113 | return ResourceManager.GetString("Error_Introduction", resourceCulture); 114 | } 115 | } 116 | 117 | /// 118 | /// Looks up a localized string similar to Error in . 119 | /// 120 | internal static string Error_Message { 121 | get { 122 | return ResourceManager.GetString("Error_Message", resourceCulture); 123 | } 124 | } 125 | 126 | /// 127 | /// Looks up a localized string similar to Get email address. 128 | /// 129 | internal static string Graph_GetEmailAddress_Button { 130 | get { 131 | return ResourceManager.GetString("Graph_GetEmailAddress_Button", resourceCulture); 132 | } 133 | } 134 | 135 | /// 136 | /// Looks up a localized string similar to Get email address. 137 | /// 138 | internal static string Graph_GetEmailAddress_Heading { 139 | get { 140 | return ResourceManager.GetString("Graph_GetEmailAddress_Heading", resourceCulture); 141 | } 142 | } 143 | 144 | /// 145 | /// Looks up a localized string similar to Choose the <b>Get email address</b> button to get the current user's email address:. 146 | /// 147 | internal static string Graph_GetEmailAddress_Instruction { 148 | get { 149 | return ResourceManager.GetString("Graph_GetEmailAddress_Instruction", resourceCulture); 150 | } 151 | } 152 | 153 | /// 154 | /// Looks up a localized string similar to Current user's email address. 155 | /// 156 | internal static string Graph_GetEmailAddress_Results_Label { 157 | get { 158 | return ResourceManager.GetString("Graph_GetEmailAddress_Results_Label", resourceCulture); 159 | } 160 | } 161 | 162 | /// 163 | /// Looks up a localized string similar to <html><head> 164 | ///<meta http-equiv='Content-Type' content='text/html; charset=us-ascii'> 165 | ///<title></title> 166 | ///</head> 167 | ///<body style='font-family:calibri'> 168 | ///<h2>Congratulations!</h2> 169 | ///<p>This is a message from the Microsoft Graph Connect Sample. You are well on your way to incorporating Microsoft Graph endpoints in your apps.</p> 170 | ///<h3>What's next?</h3><ul> 171 | ///<li>Check out <a href='https://graph.microsoft.io'>graph.microsoft.io</a> to start building Microsoft Graph apps today with all the latest tools, templates, and [rest of string was truncated]";. 172 | /// 173 | internal static string Graph_SendMail_Body_Content { 174 | get { 175 | return ResourceManager.GetString("Graph_SendMail_Body_Content", resourceCulture); 176 | } 177 | } 178 | 179 | /// 180 | /// Looks up a localized string similar to Send email. 181 | /// 182 | internal static string Graph_SendMail_Button { 183 | get { 184 | return ResourceManager.GetString("Graph_SendMail_Button", resourceCulture); 185 | } 186 | } 187 | 188 | /// 189 | /// Looks up a localized string similar to Send an email. 190 | /// 191 | internal static string Graph_SendMail_Heading { 192 | get { 193 | return ResourceManager.GetString("Graph_SendMail_Heading", resourceCulture); 194 | } 195 | } 196 | 197 | /// 198 | /// Looks up a localized string similar to After you get the email address, optionally change the following fields and then choose the <b>Send mail</b> button:. 199 | /// 200 | internal static string Graph_SendMail_Instruction { 201 | get { 202 | return ResourceManager.GetString("Graph_SendMail_Instruction", resourceCulture); 203 | } 204 | } 205 | 206 | /// 207 | /// Looks up a localized string similar to Please choose the <b>Get email address</b> button first.. 208 | /// 209 | internal static string Graph_SendMail_Message_GetEmailFirst { 210 | get { 211 | return ResourceManager.GetString("Graph_SendMail_Message_GetEmailFirst", resourceCulture); 212 | } 213 | } 214 | 215 | /// 216 | /// Looks up a localized string similar to Recipient email addresses, separated by a semicolon. 217 | /// 218 | internal static string Graph_SendMail_Recipients_Label { 219 | get { 220 | return ResourceManager.GetString("Graph_SendMail_Recipients_Label", resourceCulture); 221 | } 222 | } 223 | 224 | /// 225 | /// Looks up a localized string similar to Subject of email. 226 | /// 227 | internal static string Graph_SendMail_Subject_Label { 228 | get { 229 | return ResourceManager.GetString("Graph_SendMail_Subject_Label", resourceCulture); 230 | } 231 | } 232 | 233 | /// 234 | /// Looks up a localized string similar to Sent from the. 235 | /// 236 | internal static string Graph_SendMail_Subject_Text { 237 | get { 238 | return ResourceManager.GetString("Graph_SendMail_Subject_Text", resourceCulture); 239 | } 240 | } 241 | 242 | /// 243 | /// Looks up a localized string similar to Success! Your mail was sent.. 244 | /// 245 | internal static string Graph_SendMail_Success_Result { 246 | get { 247 | return ResourceManager.GetString("Graph_SendMail_Success_Result", resourceCulture); 248 | } 249 | } 250 | 251 | /// 252 | /// Looks up a localized string similar to Home. 253 | /// 254 | internal static string Home { 255 | get { 256 | return ResourceManager.GetString("Home", resourceCulture); 257 | } 258 | } 259 | 260 | /// 261 | /// Looks up a localized string similar to Sign in with Microsoft. 262 | /// 263 | internal static string SignIn { 264 | get { 265 | return ResourceManager.GetString("SignIn", resourceCulture); 266 | } 267 | } 268 | 269 | /// 270 | /// Looks up a localized string similar to Sign out. 271 | /// 272 | internal static string SignOut { 273 | get { 274 | return ResourceManager.GetString("SignOut", resourceCulture); 275 | } 276 | } 277 | } 278 | } 279 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/App_GlobalResources/Resource.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | text/microsoft-resx 110 | 111 | 112 | 2.0 113 | 114 | 115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 116 | 117 | 118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 119 | 120 | 121 | About 122 | Link to About page 123 | 124 | 125 | Your application description page. 126 | Description of app for About view 127 | 128 | 129 | Microsoft Graph Connect sample for ASP.NET 4.6 130 | Full app name for title and copyright 131 | 132 | 133 | Microsoft Graph Connect sample 134 | Short app name for navigation bar and browser tab 135 | 136 | 137 | Caller needs to authenticate. 138 | Error message when unable to retrieve the access token silently. 139 | 140 | 141 | An error occurred while processing your request. 142 | Generic text for Error view 143 | 144 | 145 | Error in 146 | Prefix of error message sent to Error view 147 | 148 | 149 | Get email address 150 | Button text for 'email address' section in Graph view 151 | 152 | 153 | Get email address 154 | Heading for 'email address' section in Graph view 155 | 156 | 157 | Choose the <b>Get email address</b> button to get the current user's email address: 158 | Instructions for 'email address' section in Graph view 159 | 160 | 161 | Current user's email address 162 | Label for email address result in Graph view 163 | 164 | 165 | <html><head> 166 | <meta http-equiv='Content-Type' content='text/html; charset=us-ascii'> 167 | <title></title> 168 | </head> 169 | <body style='font-family:calibri'> 170 | <h2>Congratulations!</h2> 171 | <p>This is a message from the Microsoft Graph Connect Sample. You are well on your way to incorporating Microsoft Graph endpoints in your apps.</p> 172 | <h3>What's next?</h3><ul> 173 | <li>Check out <a href='https://graph.microsoft.io'>graph.microsoft.io</a> to start building Microsoft Graph apps today with all the latest tools, templates, and guidance to get started quickly.</li> 174 | <li>Use the <a href='https://graph.microsoft.io/graph-explorer'>Graph explorer</a> to explore the rest of the APIs and start your testing.</li> 175 | <li>Browse other <a href='https://github.com/microsoftgraph/'>samples on GitHub</a> to see more of the APIs in action.</li> 176 | <li>Use the Microsoft Graph .NET Client Library to integrate additional Microsoft services and data into your own apps.</li></ul> 177 | <h3>Give us feedback</h3> 178 | <p>If you have any trouble running this sample, please <a href='https://github.com/microsoftgraph/aspnet-connect-sample/issues'> 179 | log an issue</a> on our repository.</p><p>For general questions about the Microsoft Graph API, post to <a href='https://stackoverflow.com/questions/tagged/microsoftgraph'>Stack Overflow</a>. Make sure that your questions or comments are tagged with [microsoftgraph].</p> 180 | <p>Thanks, and happy coding!<br> 181 | &nbsp;&nbsp;&nbsp;&nbsp;Your Microsoft Graph samples development team </p> 182 | <div style='text-align:center; font-family:calibri'> 183 | <table style='width:100%; font-family:calibri'> 184 | <tbody> 185 | <tr> 186 | <td><a href='https://github.com/microsoftgraph/aspnet-connect-sample'>See on GitHub</a> 187 | </td> 188 | <td><a href='https://office365.uservoice.com'>Suggest on UserVoice</a> 189 | </td> 190 | <td><a href='https://twitter.com/share?text=I%20just%20started%20developing%20apps%20for%20%23ASP.NET%20using%20the%20%23MicrosoftGraph%20Connect%20app%20%40OfficeDev&amp;url=https://github.com/microsoftgraph/aspnet-connect-sample'>Share on Twitter</a> 191 | </td> 192 | </tr> 193 | </tbody> 194 | </table> 195 | </div> 196 | </body> 197 | </html> 198 | HTML body of email (not shown in UI) 199 | 200 | 201 | Send email 202 | Button text for 'send mail' section in Graph view 203 | 204 | 205 | Send an email 206 | Heading for 'send mail' section in Graph view 207 | 208 | 209 | After you get the email address, optionally change the following fields and then choose the <b>Send mail</b> button: 210 | Instructions for 'send mail' section in Graph view 211 | 212 | 213 | Please choose the <b>Get email address</b> button first. 214 | Message if email address is missing 215 | 216 | 217 | Recipient email addresses, separated by a semicolon 218 | Label for mail recipients input in 'send mail' section in Graph view 219 | 220 | 221 | Subject of email 222 | Label for mail subject input in 'send mail' section in Graph view 223 | 224 | 225 | Sent from the 226 | Placeholder partial text for mail subject input in 'send mail' section in Graph view 227 | 228 | 229 | Success! Your mail was sent. 230 | Success message for 'send mail' section in Graph view 231 | 232 | 233 | Home 234 | Link to Home page 235 | 236 | 237 | Sign in with Microsoft 238 | Link to Account.SignIn action 239 | 240 | 241 | Sign out 242 | Link to Account.SignOut 243 | 244 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/App_Start/BundleConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Optimization; 3 | 4 | namespace Microsoft_Graph_SDK_ASPNET_Connect 5 | { 6 | public class BundleConfig 7 | { 8 | // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 9 | public static void RegisterBundles(BundleCollection bundles) 10 | { 11 | bundles.Add(new StyleBundle("~/Content/css").Include( 12 | "~/Content/site.css")); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/App_Start/FilterConfig.cs: -------------------------------------------------------------------------------- 1 | using System.Web; 2 | using System.Web.Mvc; 3 | 4 | namespace Microsoft_Graph_SDK_ASPNET_Connect 5 | { 6 | public class FilterConfig 7 | { 8 | public static void RegisterGlobalFilters(GlobalFilterCollection filters) 9 | { 10 | filters.Add(new HandleErrorAttribute()); 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/App_Start/RouteConfig.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | using System.Web.Routing; 7 | 8 | namespace Microsoft_Graph_SDK_ASPNET_Connect 9 | { 10 | public class RouteConfig 11 | { 12 | public static void RegisterRoutes(RouteCollection routes) 13 | { 14 | routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 15 | 16 | routes.MapRoute( 17 | name: "Default", 18 | url: "{controller}/{action}/{id}", 19 | defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } 20 | ); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/App_Start/Startup.Auth.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System.Web; 7 | using Owin; 8 | using Microsoft.Owin.Security; 9 | using Microsoft.Owin.Security.Cookies; 10 | using Microsoft.Owin.Security.OpenIdConnect; 11 | using System.Configuration; 12 | using System.Threading.Tasks; 13 | using Microsoft_Graph_SDK_ASPNET_Connect.TokenStorage; 14 | using System.IdentityModel.Tokens; 15 | using System.IdentityModel.Claims; 16 | using Microsoft.Identity.Client; 17 | 18 | namespace Microsoft_Graph_SDK_ASPNET_Connect 19 | { 20 | public partial class Startup 21 | { 22 | 23 | // The appId is used by the application to uniquely identify itself to Azure AD. 24 | // The appSecret is the application's password. 25 | // The redirectUri is where users are redirected after sign in and consent. 26 | // The graphScopes are the Microsoft Graph permission scopes that are used by this sample: User.Read Mail.Send 27 | private static string appId = ConfigurationManager.AppSettings["ida:AppId"]; 28 | private static string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"]; 29 | private static string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"]; 30 | private static string graphScopes = ConfigurationManager.AppSettings["ida:GraphScopes"]; 31 | 32 | public void ConfigureAuth(IAppBuilder app) 33 | { 34 | app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); 35 | 36 | app.UseCookieAuthentication(new CookieAuthenticationOptions()); 37 | 38 | app.UseOpenIdConnectAuthentication( 39 | new OpenIdConnectAuthenticationOptions 40 | { 41 | 42 | // The `Authority` represents the Microsoft v2.0 authentication and authorization service. 43 | // The `Scope` describes the permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/ 44 | ClientId = appId, 45 | Authority = "https://login.microsoftonline.com/common/v2.0", 46 | PostLogoutRedirectUri = redirectUri, 47 | RedirectUri = redirectUri, 48 | Scope = "openid email profile offline_access " + graphScopes, 49 | TokenValidationParameters = new TokenValidationParameters 50 | { 51 | ValidateIssuer = false, 52 | // In a real application you would use IssuerValidator for additional checks, 53 | // like making sure the user's organization has signed up for your app. 54 | // IssuerValidator = (issuer, token, tvp) => 55 | // { 56 | // if (MyCustomTenantValidation(issuer)) 57 | // return issuer; 58 | // else 59 | // throw new SecurityTokenInvalidIssuerException("Invalid issuer"); 60 | // }, 61 | }, 62 | Notifications = new OpenIdConnectAuthenticationNotifications 63 | { 64 | AuthorizationCodeReceived = async (context) => 65 | { 66 | var code = context.Code; 67 | string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; 68 | 69 | TokenCache userTokenCache = new SessionTokenCache(signedInUserID, 70 | context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(); 71 | ConfidentialClientApplication cca = new ConfidentialClientApplication( 72 | appId, 73 | redirectUri, 74 | new ClientCredential(appSecret), 75 | userTokenCache, 76 | null); 77 | string[] scopes = graphScopes.Split(new char[] { ' ' }); 78 | 79 | AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes); 80 | }, 81 | AuthenticationFailed = (context) => 82 | { 83 | context.HandleResponse(); 84 | context.Response.Redirect("/Error?message=" + context.Exception.Message); 85 | return Task.FromResult(0); 86 | } 87 | } 88 | }); 89 | } 90 | } 91 | } -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Content/Site.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-top: 50px; 3 | padding-bottom: 20px; 4 | } 5 | 6 | /* Set padding to keep content from hitting the edges */ 7 | .body-content { 8 | padding-left: 15px; 9 | padding-right: 15px; 10 | } 11 | 12 | /* Override the default bootstrap behavior where horizontal description lists 13 | will truncate terms that are too long to fit in the left column 14 | */ 15 | .dl-horizontal dt { 16 | white-space: normal; 17 | } 18 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Content/test.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/starter-project/Microsoft Graph SDK ASPNET Connect/Content/test.jpg -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Controllers/AccountController.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System.Web; 7 | using System.Web.Mvc; 8 | using Microsoft.Owin.Security; 9 | using Microsoft.Owin.Security.Cookies; 10 | using Microsoft.Owin.Security.OpenIdConnect; 11 | using Microsoft_Graph_SDK_ASPNET_Connect.TokenStorage; 12 | using Microsoft_Graph_SDK_ASPNET_Connect.Helpers; 13 | using System.Security.Claims; 14 | 15 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Controllers 16 | { 17 | public class AccountController : Controller 18 | { 19 | public void SignIn() 20 | { 21 | if (!Request.IsAuthenticated) 22 | { 23 | // Signal OWIN to send an authorization request to Azure. 24 | HttpContext.GetOwinContext().Authentication.Challenge( 25 | new AuthenticationProperties { RedirectUri = "/" }, 26 | OpenIdConnectAuthenticationDefaults.AuthenticationType); 27 | } 28 | } 29 | 30 | // Here we just clear the token cache, sign out the GraphServiceClient, and end the session with the web app. 31 | public void SignOut() 32 | { 33 | if (Request.IsAuthenticated) 34 | { 35 | // Get the user's token cache and clear it. 36 | string userObjectId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; 37 | 38 | SessionTokenCache tokenCache = new SessionTokenCache(userObjectId, HttpContext); 39 | HttpContext.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); 40 | } 41 | 42 | SDKHelper.SignOutClient(); 43 | 44 | // Send an OpenID Connect sign-out request. 45 | HttpContext.GetOwinContext().Authentication.SignOut( 46 | CookieAuthenticationDefaults.AuthenticationType); 47 | Response.Redirect("/"); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Controllers/ErrorController.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System.Web.Mvc; 7 | 8 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Controllers 9 | { 10 | public class ErrorController : Controller 11 | { 12 | // GET: Error 13 | public ActionResult Index(string message) 14 | { 15 | ViewBag.Message = message; 16 | return View("Error"); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Controllers/HomeController.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System; 7 | using System.Threading.Tasks; 8 | using System.Web.Mvc; 9 | using Microsoft_Graph_SDK_ASPNET_Connect.Helpers; 10 | using Microsoft_Graph_SDK_ASPNET_Connect.Models; 11 | using Resources; 12 | 13 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Controllers 14 | { 15 | public class HomeController : Controller 16 | { 17 | GraphService graphService = new GraphService(); 18 | 19 | public ActionResult Index() 20 | { 21 | return View("Graph"); 22 | } 23 | 24 | // Controller actions 25 | 26 | public ActionResult About() 27 | { 28 | return View(); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Global.asax: -------------------------------------------------------------------------------- 1 | <%@ Application Codebehind="Global.asax.cs" Inherits="Microsoft_Graph_SDK_ASPNET_Connect.MvcApplication" Language="C#" %> 2 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Global.asax.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Web; 5 | using System.Web.Mvc; 6 | using System.Web.Optimization; 7 | using System.Web.Routing; 8 | 9 | namespace Microsoft_Graph_SDK_ASPNET_Connect 10 | { 11 | public class MvcApplication : System.Web.HttpApplication 12 | { 13 | protected void Application_Start() 14 | { 15 | AreaRegistration.RegisterAllAreas(); 16 | FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 17 | RouteConfig.RegisterRoutes(RouteTable.Routes); 18 | BundleConfig.RegisterBundles(BundleTable.Bundles); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Helpers/IAuthProvider.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using System.Threading.Tasks; 7 | 8 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Helpers 9 | { 10 | public interface IAuthProvider 11 | { 12 | Task GetUserAccessTokenAsync(); 13 | } 14 | } -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Helpers/SampleAuthProvider.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using Microsoft.Identity.Client; 7 | using Microsoft.Owin.Security; 8 | using Microsoft.Owin.Security.OpenIdConnect; 9 | using Microsoft_Graph_SDK_ASPNET_Connect.TokenStorage; 10 | using System.Collections.Generic; 11 | using System.Configuration; 12 | using System.Linq; 13 | using System.Security.Claims; 14 | using System.Threading.Tasks; 15 | using System.Web; 16 | using Microsoft.Graph; 17 | using Resources; 18 | using System; 19 | 20 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Helpers 21 | { 22 | public sealed class SampleAuthProvider : IAuthProvider 23 | { 24 | 25 | // Properties used to get and manage an access token. 26 | private string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"]; 27 | private string appId = ConfigurationManager.AppSettings["ida:AppId"]; 28 | private string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"]; 29 | private string scopes = ConfigurationManager.AppSettings["ida:GraphScopes"]; 30 | private SessionTokenCache tokenCache { get; set; } 31 | 32 | private static readonly SampleAuthProvider instance = new SampleAuthProvider(); 33 | private SampleAuthProvider() { } 34 | 35 | public static SampleAuthProvider Instance 36 | { 37 | get 38 | { 39 | return instance; 40 | } 41 | } 42 | 43 | // Gets an access token. First tries to get the token from the token cache. 44 | public async Task GetUserAccessTokenAsync() 45 | { 46 | string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value; 47 | HttpContextWrapper httpContext = new HttpContextWrapper(HttpContext.Current); 48 | TokenCache userTokenCache = new SessionTokenCache(signedInUserID, httpContext).GetMsalCacheInstance(); 49 | //var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache 50 | 51 | ConfidentialClientApplication cca = new ConfidentialClientApplication( 52 | appId, 53 | redirectUri, 54 | new ClientCredential(appSecret), 55 | userTokenCache, 56 | null); 57 | 58 | try 59 | { 60 | AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }), cca.Users.First()); 61 | return result.AccessToken; 62 | } 63 | 64 | // Unable to retrieve the access token silently. 65 | catch (Exception) 66 | { 67 | HttpContext.Current.Request.GetOwinContext().Authentication.Challenge( 68 | new AuthenticationProperties() { RedirectUri = "/" }, 69 | OpenIdConnectAuthenticationDefaults.AuthenticationType); 70 | 71 | throw new ServiceException( 72 | new Error 73 | { 74 | Code = GraphErrorCode.AuthenticationFailure.ToString(), 75 | Message = Resource.Error_AuthChallengeNeeded, 76 | }); 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Models/GraphService.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using Resources; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.IO; 10 | using System.Threading.Tasks; 11 | 12 | namespace Microsoft_Graph_SDK_ASPNET_Connect.Models 13 | { 14 | public class GraphService 15 | { 16 | 17 | // GetMyEmailAddress 18 | 19 | // SendEmail 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Microsoft_Graph_SDK_ASPNET_Connect")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Microsoft_Graph_SDK_ASPNET_Connect")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("e0acf779-6715-46c4-a159-31a4cde3c9c1")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Revision and Build Numbers 33 | // by using the '*' as shown below: 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Scripts/_references.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/starter-project/Microsoft Graph SDK ASPNET Connect/Scripts/_references.js -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Startup.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using Owin; 7 | using Microsoft.Owin; 8 | 9 | [assembly: OwinStartup(typeof(Microsoft_Graph_SDK_ASPNET_Connect.Startup))] 10 | 11 | namespace Microsoft_Graph_SDK_ASPNET_Connect 12 | { 13 | public partial class Startup 14 | { 15 | public void Configuration(IAppBuilder app) 16 | { 17 | ConfigureAuth(app); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/TokenStorage/SessionTokenCache.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. 3 | * See LICENSE in the source repository root for complete license information. 4 | */ 5 | 6 | using Microsoft.Identity.Client; 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Threading; 11 | using System.Web; 12 | 13 | namespace Microsoft_Graph_SDK_ASPNET_Connect.TokenStorage 14 | { 15 | 16 | // Store the user's token information. 17 | public class SessionTokenCache 18 | { 19 | private static ReaderWriterLockSlim SessionLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); 20 | string UserId = string.Empty; 21 | string CacheId = string.Empty; 22 | HttpContextBase httpContext = null; 23 | 24 | TokenCache cache = new TokenCache(); 25 | 26 | public SessionTokenCache(string userId, HttpContextBase httpcontext) 27 | { 28 | // not object, we want the SUB 29 | UserId = userId; 30 | CacheId = UserId + "_TokenCache"; 31 | httpContext = httpcontext; 32 | Load(); 33 | } 34 | 35 | public TokenCache GetMsalCacheInstance() 36 | { 37 | cache.SetBeforeAccess(BeforeAccessNotification); 38 | cache.SetAfterAccess(AfterAccessNotification); 39 | Load(); 40 | return cache; 41 | } 42 | 43 | public void SaveUserStateValue(string state) 44 | { 45 | SessionLock.EnterWriteLock(); 46 | httpContext.Session[CacheId + "_state"] = state; 47 | SessionLock.ExitWriteLock(); 48 | } 49 | public string ReadUserStateValue() 50 | { 51 | string state = string.Empty; 52 | SessionLock.EnterReadLock(); 53 | state = (string)httpContext.Session[CacheId + "_state"]; 54 | SessionLock.ExitReadLock(); 55 | return state; 56 | } 57 | public void Load() 58 | { 59 | SessionLock.EnterReadLock(); 60 | cache.Deserialize((byte[])httpContext.Session[CacheId]); 61 | SessionLock.ExitReadLock(); 62 | } 63 | 64 | public void Persist() 65 | { 66 | SessionLock.EnterWriteLock(); 67 | 68 | // Optimistically set HasStateChanged to false. We need to do it early to avoid losing changes made by a concurrent thread. 69 | cache.HasStateChanged = false; 70 | 71 | // Reflect changes in the persistent store 72 | httpContext.Session[CacheId] = cache.Serialize(); 73 | SessionLock.ExitWriteLock(); 74 | } 75 | 76 | // Triggered right before MSAL needs to access the cache. 77 | // Reload the cache from the persistent store in case it changed since the last access. 78 | void BeforeAccessNotification(TokenCacheNotificationArgs args) 79 | { 80 | Load(); 81 | } 82 | 83 | // Triggered right after MSAL accessed the cache. 84 | void AfterAccessNotification(TokenCacheNotificationArgs args) 85 | { 86 | // if the access operation resulted in a cache update 87 | if (cache.HasStateChanged) 88 | { 89 | Persist(); 90 | } 91 | } 92 | 93 | } 94 | } -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Views/Home/About.cshtml: -------------------------------------------------------------------------------- 1 |  3 | 4 | @using Resources 5 | 6 | @{ 7 | ViewBag.Title = Resource.About; 8 | } 9 |

@ViewBag.Title

10 | 11 |

@Resource.About_Description

-------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Views/Home/Graph.cshtml: -------------------------------------------------------------------------------- 1 |  3 | 4 | @using Resources 5 | 6 | @{ 7 | ViewBag.Title = Resource.App_Name; 8 | } 9 | 10 |

@ViewBag.Title

11 |

@Resource.Graph_GetEmailAddress_Heading

12 |

@Html.Raw(Resource.Graph_GetEmailAddress_Instruction)

13 | @using (Html.BeginForm("GetMyEmailAddress", "Home")) 14 | { 15 |
16 |
17 | 18 |
19 |
20 | } 21 |
22 | 23 |
@ViewBag.Email
24 |
25 | 26 |

@Resource.Graph_SendMail_Heading

27 |

@Html.Raw(Resource.Graph_SendMail_Instruction)

28 | @using (Html.BeginForm("SendEmail", "Home")) 29 | { 30 |
31 |
32 | 33 | 34 |
35 |
36 | 37 | 38 |
39 |
40 | 41 | 42 |
43 |
44 | } 45 |
46 |

@Html.Raw(ViewBag.Message)

47 |
48 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Views/Shared/Error.cshtml: -------------------------------------------------------------------------------- 1 |  3 | 4 | @using Resources 5 | 6 | @{ 7 | ViewBag.Title = Resource.App_Name; 8 | } 9 | 10 |

@ViewBag.Title

11 |

@Resource.Error_Introduction

12 | 13 |
@ViewBag.Message
-------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Views/Shared/_Layout.cshtml: -------------------------------------------------------------------------------- 1 |  3 | 4 | @using Resources 5 | 6 | 7 | 8 | 9 | 10 | 11 | @ViewBag.Title 12 | @Styles.Render("~/Content/css") 13 | @Styles.Render("https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css") 14 | @Styles.Render("https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap-theme.min.css") 15 | @Scripts.Render("https://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.6.2.js") 16 | 17 | 18 | 37 |
38 | @RenderBody() 39 |
40 |
41 |

© @DateTime.Now.Year - @ViewBag.Title

42 |
43 |
44 | @Scripts.Render("https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.3.min.js") 45 | @Scripts.Render("https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js") 46 | @RenderSection("scripts", required: false) 47 | 48 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Views/Shared/_LoginPartial.cshtml: -------------------------------------------------------------------------------- 1 |  3 | 4 | @using Resources 5 | 6 | @if (Request.IsAuthenticated) 7 | { 8 | 9 | 18 | 19 | } 20 | else 21 | { 22 | 40 | 41 | 48 | } 49 | 50 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Views/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 |
7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Views/_ViewStart.cshtml: -------------------------------------------------------------------------------- 1 | @{ 2 | Layout = "~/Views/Shared/_Layout.cshtml"; 3 | } 4 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/Web.config: -------------------------------------------------------------------------------- 1 |  2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/starter-project/Microsoft Graph SDK ASPNET Connect/favicon.ico -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/starter-project/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/starter-project/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/starter-project/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoftgraph/aspnet-connect-sample/60e6b3d805516752cc036b7dc182cb324781a3b5/starter-project/Microsoft Graph SDK ASPNET Connect/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /starter-project/Microsoft Graph SDK ASPNET Connect/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /starter-project/README.md: -------------------------------------------------------------------------------- 1 | # Microsoft Graph Connect for ASP.NET 4.6 MVC app starter project 2 | This is the starter project used by the [ASP.NET 4.6 MVC app walkthrough](https://graph.microsoft.io/en-us/docs/get-started/aspnetmvc) in the Microsoft Graph documentation. 3 | 4 | ## Copyright 5 | Copyright (c) 2016 Microsoft. All rights reserved. 6 | --------------------------------------------------------------------------------