Skip to content
This repository has been archived by the owner on Nov 16, 2023. It is now read-only.

Commit

Permalink
Switching from ADAL to MSAL
Browse files Browse the repository at this point in the history
  • Loading branch information
Jim Crowley committed Mar 6, 2018
1 parent c9da9b6 commit 26bdbce
Show file tree
Hide file tree
Showing 14 changed files with 258 additions and 213 deletions.
54 changes: 0 additions & 54 deletions Microsoft-Graph-ExcelRest-ToDo/Auth/AuthHelper.cs

This file was deleted.

14 changes: 8 additions & 6 deletions Microsoft-Graph-ExcelRest-ToDo/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft_Graph_ExcelRest_ToDo.TokenStorage;
using System.Security.Claims;

namespace Microsoft_Graph_ExcelRest_ToDo.Controllers
{
Expand All @@ -16,7 +17,7 @@ public void SignIn()
{
if (!Request.IsAuthenticated)
{
// Signal OWIN to send an authorization request to Azure
// Signal OWIN to send an authorization request to Azure.
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
Expand All @@ -27,13 +28,14 @@ public void SignOut()
{
if (Request.IsAuthenticated)
{
// Get the user's token cache and clear it
string userObjId = System.Security.Claims.ClaimsPrincipal.Current
.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
// Get the user's token cache and clear it.
string userObjectId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);
tokenCache.Clear();
SessionTokenCache tokenCache = new SessionTokenCache(userObjectId, HttpContext);
HttpContext.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
}


// Send an OpenID Connect sign-out request.
HttpContext.GetOwinContext().Authentication.SignOut(
CookieAuthenticationDefaults.AuthenticationType);
Expand Down
7 changes: 2 additions & 5 deletions Microsoft-Graph-ExcelRest-ToDo/Controllers/ChartController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
using System.Web.Mvc;
using System.Threading.Tasks;
using Microsoft_Graph_ExcelRest_ToDo.TokenStorage;
using Microsoft_Graph_ExcelRest_ToDo.Auth;
using Microsoft_Graph_ExcelRest_ToDo.Helpers;
using System.Configuration;

namespace Microsoft_Graph_ExcelRest_ToDo.Controllers
Expand All @@ -20,10 +20,7 @@ public async Task<FileResult> GetChart()
string userObjId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

string tenantId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string authority = string.Format(ConfigurationManager.AppSettings["ida:AADInstance"], tenantId, "");
AuthHelper authHelper = new AuthHelper(authority, ConfigurationManager.AppSettings["ida:AppId"], ConfigurationManager.AppSettings["ida:AppSecret"], tokenCache);
string accessToken = await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme));
string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync();


return await ExcelApiHelper.getChartImage(accessToken);
Expand Down
12 changes: 2 additions & 10 deletions Microsoft-Graph-ExcelRest-ToDo/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
using Microsoft_Graph_ExcelRest_ToDo.TokenStorage;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft_Graph_ExcelRest_ToDo.Auth;
using Microsoft_Graph_ExcelRest_ToDo.Helpers;

namespace Microsoft_Graph_ExcelRest_ToDo.Controllers
{
Expand Down Expand Up @@ -41,15 +41,7 @@ public async Task<ActionResult> Graph()

SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

string tenantId = System.Security.Claims.ClaimsPrincipal.Current
.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

string authority = string.Format(ConfigurationManager.AppSettings["ida:AADInstance"], tenantId, "");

AuthHelper authHelper = new AuthHelper(authority, ConfigurationManager.AppSettings["ida:AppId"],
ConfigurationManager.AppSettings["ida:AppSecret"], tokenCache);

ViewBag.AccessToken = await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme));
ViewBag.AccessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync();

if (null == ViewBag.AccessToken)
{
Expand Down
12 changes: 3 additions & 9 deletions Microsoft-Graph-ExcelRest-ToDo/Controllers/ToDoListController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
using System.Threading.Tasks;
using System;
using Microsoft_Graph_ExcelRest_ToDo.TokenStorage;
using Microsoft_Graph_ExcelRest_ToDo.Auth;
using Microsoft_Graph_ExcelRest_ToDo.Helpers;
using System.Configuration;

namespace Microsoft_Graph_ExcelRest_ToDo.Controllers
Expand All @@ -21,10 +21,7 @@ public async Task<ActionResult> Index()
string userObjId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

string tenantId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string authority = string.Format(ConfigurationManager.AppSettings["ida:AADInstance"], tenantId, "");
AuthHelper authHelper = new AuthHelper(authority, ConfigurationManager.AppSettings["ida:AppId"], ConfigurationManager.AppSettings["ida:AppSecret"], tokenCache);
string accessToken = await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme));
string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync();

await ExcelApiHelper.LoadWorkbook(accessToken);

Expand Down Expand Up @@ -65,10 +62,7 @@ public async Task<ActionResult> Create(FormCollection collection)
string userObjId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
SessionTokenCache tokenCache = new SessionTokenCache(userObjId, HttpContext);

string tenantId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string authority = string.Format(ConfigurationManager.AppSettings["ida:AADInstance"], tenantId, "");
AuthHelper authHelper = new AuthHelper(authority, ConfigurationManager.AppSettings["ida:AppId"], ConfigurationManager.AppSettings["ida:AppSecret"], tokenCache);
string accessToken = await authHelper.GetUserAccessToken(Url.Action("Index", "Home", null, Request.Url.Scheme));
string accessToken = await SampleAuthProvider.Instance.GetUserAccessTokenAsync();

await ExcelApiHelper.CreateToDoItem(
accessToken,
Expand Down
14 changes: 14 additions & 0 deletions Microsoft-Graph-ExcelRest-ToDo/Helpers/IAuthProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
* See LICENSE in the source repository root for complete license information.
*/

using System.Threading.Tasks;

namespace Microsoft_Graph_ExcelRest_ToDo.Helpers
{
public interface IAuthProvider
{
Task<string> GetUserAccessTokenAsync();
}
}
73 changes: 73 additions & 0 deletions Microsoft-Graph-ExcelRest-ToDo/Helpers/SampleAuthProvider.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
* See LICENSE in the source repository root for complete license information.
*/

using Microsoft.Identity.Client;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft_Graph_ExcelRest_ToDo.TokenStorage;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System;

namespace Microsoft_Graph_ExcelRest_ToDo.Helpers
{
public sealed class SampleAuthProvider : IAuthProvider
{

// Properties used to get and manage an access token.
private string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
private string appId = ConfigurationManager.AppSettings["ida:AppId"];
private string appSecret = ConfigurationManager.AppSettings["ida:AppSecret"];
private string scopes = ConfigurationManager.AppSettings["ida:GraphScopes"];
private SessionTokenCache tokenCache { get; set; }

private static readonly SampleAuthProvider instance = new SampleAuthProvider();
private SampleAuthProvider() { }

public static SampleAuthProvider Instance
{
get
{
return instance;
}
}

// Gets an access token. First tries to get the token from the token cache.
public async Task<string> GetUserAccessTokenAsync()
{
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
HttpContextWrapper httpContext = new HttpContextWrapper(HttpContext.Current);
TokenCache userTokenCache = new SessionTokenCache(signedInUserID, httpContext).GetMsalCacheInstance();
//var cachedItems = tokenCache.ReadItems(appId); // see what's in the cache

ConfidentialClientApplication cca = new ConfidentialClientApplication(
appId,
redirectUri,
new ClientCredential(appSecret),
userTokenCache,
null);

try
{
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes.Split(new char[] { ' ' }), cca.Users.First());
return result.AccessToken;
}

// Unable to retrieve the access token silently.
catch (Exception)
{
HttpContext.Current.Request.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties() { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);

throw new Exception("Caller needs to authenticate.");
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,8 @@
<Private>True</Private>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.IdentityModel.Clients.ActiveDirectory, Version=3.19.1.3001, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.IdentityModel.Clients.ActiveDirectory.3.19.1\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Clients.ActiveDirectory.Platform, Version=3.19.1.3001, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.IdentityModel.Clients.ActiveDirectory.3.19.1\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll</HintPath>
<Reference Include="Microsoft.Identity.Client, Version=1.1.2.0, Culture=neutral, PublicKeyToken=0a613f4dd989e8ae, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Identity.Client.1.1.2-preview0008\lib\net45\Microsoft.Identity.Client.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Protocol.Extensions">
<HintPath>..\packages\Microsoft.IdentityModel.Protocol.Extensions.1.0.2.206221351\lib\net45\Microsoft.IdentityModel.Protocol.Extensions.dll</HintPath>
Expand Down Expand Up @@ -107,6 +104,7 @@
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
Expand Down Expand Up @@ -160,7 +158,6 @@
<Compile Include="App_Start\BundleConfig.cs" />
<Compile Include="App_Start\FilterConfig.cs" />
<Compile Include="App_Start\RouteConfig.cs" />
<Compile Include="Auth\AuthHelper.cs" />
<Compile Include="Controllers\AccountController.cs" />
<Compile Include="Controllers\ErrorController.cs" />
<Compile Include="Controllers\HomeController.cs" />
Expand All @@ -170,6 +167,8 @@
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="EXCEL_CLIENT_CODE\ExcelAPIHelper.cs" />
<Compile Include="Helpers\IAuthProvider.cs" />
<Compile Include="Helpers\SampleAuthProvider.cs" />
<Compile Include="Models\ToDoItem.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Startup.cs" />
Expand Down Expand Up @@ -224,6 +223,7 @@
</ItemGroup>
<ItemGroup>
<Folder Include="App_Data\" />
<Folder Include="Auth\" />
<Folder Include="Views\Account\" />
<Folder Include="Views\Error\" />
</ItemGroup>
Expand Down
Loading

0 comments on commit 26bdbce

Please sign in to comment.