I have created an MVC web app, that has certain pages that require a user to be logged in. The app is multitenant, and the authentication is configured in the Startup.Auth.cs. The ConfigureAuth file looks like this:
public void ConfigureAuth(IAppBuilder app){
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
ClientId = clientId,
Authority = authority,
RedirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"],
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters{
ValidateIssuer = false,
},
Notifications = new OpenIdConnectAuthenticationNotifications(){
SecurityTokenValidated = (context) => {
return Task.FromResult(0);
},
AuthorizationCodeReceived = (context) => {
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(
aadInstance + tenantID,
new ADALTokenCache(signedInUserID)
);
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code,
new Uri(ConfigurationManager.AppSettings["ida:RedirectUri"]),
credential,
graphResourceID
);
return Task.FromResult(0);
},
AuthenticationFailed = (context) => {
context.HandleResponse(); // Suppress the exception
context.Response.Redirect("/Error?message=" + context.Exception.Message);
return Task.FromResult(0);
}
}
});
}
This works - perfectly. My problem is, I would love to this the same authorization in my controller, when calling a Microsoft Graph endpoint.
I can see that the AccessToken contained in the AuthenticationResult has the correct scopes - meaning I should be able to reuse this when calling Graph, right?
But how do I use this in my controller? And how do I ensure the token is refreshed?
All examples I can find either use MSAL with v2 endpoint, or connects on behalf of the client - this does not work for me.