Skip to content

Commit 552d1ee

Browse files
authored
Merge pull request #47 from microsoftgraph/po/msalAuthProvider
Adds MSAL-Graph auth provider support.
2 parents 755f2ae + df56e7b commit 552d1ee

27 files changed

+760
-756
lines changed

Graph-ASPNET-46-Snippets/Microsoft Graph ASPNET Snippets/App_GlobalResources/Resource.designer.cs

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Graph-ASPNET-46-Snippets/Microsoft Graph ASPNET Snippets/App_GlobalResources/Resource.resx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@
138138
<comment>Title and heading for Error view</comment>
139139
</data>
140140
<data name="Error_AuthChallengeNeeded" xml:space="preserve">
141-
<value>Caller needs to authenticate.</value>
141+
<value>authenticationChallengeRequired</value>
142142
<comment>Error message when unable to retrieve the access token silently.</comment>
143143
</data>
144144
<data name="Error_Introduction" xml:space="preserve">

Graph-ASPNET-46-Snippets/Microsoft Graph ASPNET Snippets/App_Start/Startup.Auth.cs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,9 @@
1414
using System.Threading.Tasks;
1515
using Microsoft_Graph_ASPNET_Snippets.TokenStorage;
1616
using System.IdentityModel.Tokens;
17-
using System.IdentityModel.Claims;
1817
using Microsoft.Identity.Client;
1918
using Microsoft_Graph_ASPNET_Snippets.Utils;
19+
using Microsoft.Graph.Auth;
2020

2121
namespace Microsoft_Graph_ASPNET_Snippets
2222
{
@@ -79,14 +79,12 @@ public void ConfigureAuth(IAppBuilder app)
7979
AuthorizationCodeReceived = async (context) =>
8080
{
8181
var code = context.Code;
82-
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
83-
string graphScopes = nonAdminScopes;
84-
string[] scopes = graphScopes.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
82+
string[] scopes = nonAdminScopes.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
8583

86-
ConfidentialClientApplication cca = new ConfidentialClientApplication(appId, redirectUri,
87-
new ClientCredential(appSecret),
88-
new SessionTokenCache(signedInUserID, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance(), null);
89-
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
84+
SessionTokenCacheProvider sessionTokenCacheProvider = new SessionTokenCacheProvider(context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase);
85+
IConfidentialClientApplication cca = AuthorizationCodeProvider.CreateClientApplication(appId, redirectUri, new ClientCredential(appSecret), sessionTokenCacheProvider);
86+
AuthorizationCodeProvider authorizationCodeProvider = new AuthorizationCodeProvider(cca, scopes);
87+
AuthenticationResult result = await authorizationCodeProvider.GetTokenByAuthorizationCodeAsync(code);
9088

9189
// Check whether the login is from the MSA tenant.
9290
// The sample uses this attribute to disable UI buttons for unsupported operations when the user is logged in with an MSA account.

Graph-ASPNET-46-Snippets/Microsoft Graph ASPNET Snippets/Controllers/AccountController.cs

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,6 @@
88
using Microsoft.Owin.Security;
99
using Microsoft.Owin.Security.Cookies;
1010
using Microsoft.Owin.Security.OpenIdConnect;
11-
using Microsoft_Graph_ASPNET_Snippets.TokenStorage;
12-
using Microsoft_Graph_ASPNET_Snippets.Helpers;
13-
using System.Security.Claims;
1411

1512
namespace Microsoft_Graph_ASPNET_Snippets.Controllers
1613
{
@@ -32,14 +29,9 @@ public void SignOut()
3229
{
3330
if (Request.IsAuthenticated)
3431
{
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);
3932
HttpContext.GetOwinContext().Authentication.SignOut(OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);
4033
}
4134

42-
4335
// Send an OpenID Connect sign-out request.
4436
HttpContext.GetOwinContext().Authentication.SignOut(
4537
CookieAuthenticationDefaults.AuthenticationType);

Graph-ASPNET-46-Snippets/Microsoft Graph ASPNET Snippets/Controllers/AdminController.cs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,11 @@
44
*/
55

66
using System;
7-
using System.Collections.Generic;
87
using System.Configuration;
98
using System.Linq;
10-
using System.Security.Claims;
119
using System.Threading.Tasks;
12-
using System.Web;
1310
using System.Web.Mvc;
11+
using Microsoft.Graph.Auth;
1412
using Microsoft.Identity.Client;
1513
using Microsoft_Graph_ASPNET_Snippets.TokenStorage;
1614
using Microsoft_Graph_ASPNET_Snippets.Utils;
@@ -27,29 +25,27 @@ public class AdminController : Controller
2725
// GET: Admin
2826
public async Task<ActionResult> Index()
2927
{
30-
// try to get token silently
31-
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
32-
TokenCache theCache = new SessionTokenCache(signedInUserID, this.HttpContext).GetMsalCacheInstance();
33-
34-
ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri,
35-
new ClientCredential(appKey), theCache, null);
3628
string[] scopes = adminScopes.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
29+
SessionTokenCacheProvider sessionTokenCacheProvider = new SessionTokenCacheProvider(this.HttpContext);
30+
IConfidentialClientApplication cca = AuthorizationCodeProvider.CreateClientApplication(clientId, redirectUri, new ClientCredential(appKey), sessionTokenCacheProvider);
31+
3732
try
3833
{
39-
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, cca.Users.First());
34+
AuthenticationResult result = await cca.AcquireTokenSilentAsync(scopes, (await cca.GetAccountsAsync()).FirstOrDefault());
4035
}
4136
catch (Exception)
4237
{
4338
try
4439
{// when failing, manufacture the URL and assign it
45-
string authReqUrl = await OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca, this.HttpContext, Url);
40+
string authReqUrl = await OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, cca as ConfidentialClientApplication, this.HttpContext, Url);
4641
ViewBag.AuthorizationRequest = authReqUrl;
4742
}
4843
catch (Exception ee)
4944
{
5045

5146
}
5247
}
48+
5349
return View("Admin");
5450

5551
}

Graph-ASPNET-46-Snippets/Microsoft Graph ASPNET Snippets/Controllers/EventsController.cs

Lines changed: 52 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,27 @@
44
*/
55

66
using Microsoft.Graph;
7+
using Microsoft.Graph.Auth;
78
using Microsoft_Graph_ASPNET_Snippets.Helpers;
89
using Microsoft_Graph_ASPNET_Snippets.Models;
910
using Resources;
10-
using System;
11-
using System.Collections.Generic;
1211
using System.Threading.Tasks;
12+
using System.Web;
1313
using System.Web.Mvc;
1414

1515
namespace Microsoft_Graph_ASPNET_Snippets.Controllers
1616
{
1717
[Authorize]
1818
public class EventsController : Controller
1919
{
20-
EventsService eventsService = new EventsService();
21-
20+
EventsService eventsService;
21+
22+
public EventsController()
23+
{
24+
// Initialize the GraphServiceClient.
25+
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
26+
eventsService = new EventsService(graphClient);
27+
}
2228
public ActionResult Index()
2329
{
2430
return View("Events");
@@ -30,20 +36,17 @@ public async Task<ActionResult> GetMyEvents()
3036
ResultsViewModel results = new ResultsViewModel();
3137
try
3238
{
33-
34-
// Initialize the GraphServiceClient.
35-
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
36-
3739
// Get events.
38-
results.Items = await eventsService.GetMyEvents(graphClient);
40+
results.Items = await eventsService.GetMyEvents();
3941
}
4042
catch (ServiceException se)
4143
{
42-
if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
43-
44-
// Personal accounts that aren't enabled for the Outlook REST API get a "MailboxNotEnabledForRESTAPI" or "MailboxNotSupportedForRESTAPI" error.
44+
if ((se.InnerException as AuthenticationException)?.Error.Code == Resource.Error_AuthChallengeNeeded)
45+
{
46+
HttpContext.Request.GetOwinContext().Authentication.Challenge();
47+
return new EmptyResult();
48+
}
4549
return RedirectToAction("Index", "Error", new { message = string.Format(Resource.Error_Message, Request.RawUrl, se.Error.Code, se.Error.Message) });
46-
4750
}
4851
return View("Events", results);
4952
}
@@ -54,17 +57,16 @@ public async Task<ActionResult> GetMyCalendarView()
5457
ResultsViewModel results = new ResultsViewModel();
5558
try
5659
{
57-
// Initialize the GraphServiceClient.
58-
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
59-
6060
// Get a calendar view.
61-
results.Items = await eventsService.GetMyCalendarView(graphClient);
61+
results.Items = await eventsService.GetMyCalendarView();
6262
}
6363
catch (ServiceException se)
6464
{
65-
if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
66-
67-
// Personal accounts that aren't enabled for the Outlook REST API get a "MailboxNotEnabledForRESTAPI" or "MailboxNotSupportedForRESTAPI" error.
65+
if ((se.InnerException as AuthenticationException)?.Error.Code == Resource.Error_AuthChallengeNeeded)
66+
{
67+
HttpContext.Request.GetOwinContext().Authentication.Challenge();
68+
return new EmptyResult();
69+
}
6870
return RedirectToAction("Index", "Error", new { message = string.Format(Resource.Error_Message, Request.RawUrl, se.Error.Code, se.Error.Message) });
6971
}
7072
return View("Events", results);
@@ -77,18 +79,16 @@ public async Task<ActionResult> CreateEvent()
7779
ResultsViewModel results = new ResultsViewModel();
7880
try
7981
{
80-
81-
// Initialize the GraphServiceClient.
82-
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
83-
8482
// Create the event.
85-
results.Items = await eventsService.CreateEvent(graphClient);
83+
results.Items = await eventsService.CreateEvent();
8684
}
8785
catch (ServiceException se)
8886
{
89-
if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
90-
91-
// Personal accounts that aren't enabled for the Outlook REST API get a "MailboxNotEnabledForRESTAPI" or "MailboxNotSupportedForRESTAPI" error.
87+
if ((se.InnerException as AuthenticationException)?.Error.Code == Resource.Error_AuthChallengeNeeded)
88+
{
89+
HttpContext.Request.GetOwinContext().Authentication.Challenge();
90+
return new EmptyResult();
91+
}
9292
return RedirectToAction("Index", "Error", new { message = string.Format(Resource.Error_Message, Request.RawUrl, se.Error.Code, se.Error.Message) });
9393
}
9494
return View("Events", results);
@@ -100,18 +100,16 @@ public async Task<ActionResult> GetEvent(string id)
100100
ResultsViewModel results = new ResultsViewModel();
101101
try
102102
{
103-
104-
// Initialize the GraphServiceClient.
105-
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
106-
107103
// Get the event.
108-
results.Items = await eventsService.GetEvent(graphClient, id);
104+
results.Items = await eventsService.GetEvent(id);
109105
}
110106
catch (ServiceException se)
111107
{
112-
if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
113-
114-
// Personal accounts that aren't enabled for the Outlook REST API get a "MailboxNotEnabledForRESTAPI" or "MailboxNotSupportedForRESTAPI" error.
108+
if ((se.InnerException as AuthenticationException)?.Error.Code == Resource.Error_AuthChallengeNeeded)
109+
{
110+
HttpContext.Request.GetOwinContext().Authentication.Challenge();
111+
return new EmptyResult();
112+
}
115113
return RedirectToAction("Index", "Error", new { message = string.Format(Resource.Error_Message, Request.RawUrl, se.Error.Code, se.Error.Message) });
116114
}
117115
return View("Events", results);
@@ -124,18 +122,16 @@ public async Task<ActionResult> UpdateEvent(string id, string name)
124122
ResultsViewModel results = new ResultsViewModel();
125123
try
126124
{
127-
128-
// Initialize the GraphServiceClient.
129-
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
130-
131125
// Update the event.
132-
results.Items = await eventsService.UpdateEvent(graphClient, id, name);
126+
results.Items = await eventsService.UpdateEvent(id, name);
133127
}
134128
catch (ServiceException se)
135129
{
136-
if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
137-
138-
// Personal accounts that aren't enabled for the Outlook REST API get a "MailboxNotEnabledForRESTAPI" or "MailboxNotSupportedForRESTAPI" error.
130+
if ((se.InnerException as AuthenticationException)?.Error.Code == Resource.Error_AuthChallengeNeeded)
131+
{
132+
HttpContext.Request.GetOwinContext().Authentication.Challenge();
133+
return new EmptyResult();
134+
}
139135
return RedirectToAction("Index", "Error", new { message = string.Format(Resource.Error_Message, Request.RawUrl, se.Error.Code, se.Error.Message) });
140136
}
141137
return View("Events", results);
@@ -147,18 +143,16 @@ public async Task<ActionResult> DeleteEvent(string id)
147143
ResultsViewModel results = new ResultsViewModel(false);
148144
try
149145
{
150-
151-
// Initialize the GraphServiceClient.
152-
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
153-
154146
// Delete the event.
155-
results.Items = await eventsService.DeleteEvent(graphClient, id);
147+
results.Items = await eventsService.DeleteEvent(id);
156148
}
157149
catch (ServiceException se)
158150
{
159-
if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
160-
161-
// Personal accounts that aren't enabled for the Outlook REST API get a "MailboxNotEnabledForRESTAPI" or "MailboxNotSupportedForRESTAPI" error.
151+
if ((se.InnerException as AuthenticationException)?.Error.Code == Resource.Error_AuthChallengeNeeded)
152+
{
153+
HttpContext.Request.GetOwinContext().Authentication.Challenge();
154+
return new EmptyResult();
155+
}
162156
return RedirectToAction("Index", "Error", new { message = string.Format(Resource.Error_Message, Request.RawUrl, se.Error.Code, se.Error.Message) });
163157
}
164158
return View("Events", results);
@@ -172,17 +166,16 @@ public async Task<ActionResult> AcceptMeetingRequest(string id)
172166
ResultsViewModel results = new ResultsViewModel(false);
173167
try
174168
{
175-
// Initialize the GraphServiceClient.
176-
GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();
177-
178169
// Accept the meeting.
179-
results.Items = await eventsService.AcceptMeetingRequest(graphClient, id);
170+
results.Items = await eventsService.AcceptMeetingRequest(id);
180171
}
181172
catch (ServiceException se)
182173
{
183-
if (se.Error.Message == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
184-
185-
// Personal accounts that aren't enabled for the Outlook REST API get a "MailboxNotEnabledForRESTAPI" or "MailboxNotSupportedForRESTAPI" error.
174+
if ((se.InnerException as AuthenticationException)?.Error.Code == Resource.Error_AuthChallengeNeeded)
175+
{
176+
HttpContext.Request.GetOwinContext().Authentication.Challenge();
177+
return new EmptyResult();
178+
}
186179
return RedirectToAction("Index", "Error", new { message = string.Format(Resource.Error_Message, Request.RawUrl, se.Error.Code, se.Error.Message) });
187180
}
188181
return View("Events", results);

0 commit comments

Comments
 (0)