Skip to content

Instantly share code, notes, and snippets.

@ivanbuzyka
Created February 12, 2024 18:15
Show Gist options
  • Save ivanbuzyka/eeafb07516e013053bf26a88a248ba2c to your computer and use it in GitHub Desktop.
Save ivanbuzyka/eeafb07516e013053bf26a88a248ba2c to your computer and use it in GitHub Desktop.
[TEMP] AAD Identity provider sample
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Notifications;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
using Sitecore.Abstractions;
using Sitecore.Configuration;
using Sitecore.Data.Clones;
using Sitecore.Diagnostics;
using Sitecore.Owin.Authentication.Configuration;
using Sitecore.Owin.Authentication.Pipelines.IdentityProviders;
using Sitecore.Owin.Authentication.Services;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace Sitecore.FederatedAuth.Extensions.Pipelines
{
public class AzureADIdentityProviderProcessor : IdentityProvidersProcessor
{
const string GraphResource = "https://graph.microsoft.com";
public AzureADIdentityProviderProcessor(FederatedAuthenticationConfiguration federatedAuthenticationConfiguration, ICookieManager cookieManager, BaseSettings settings)
: base(federatedAuthenticationConfiguration, cookieManager, settings)
{
}
protected override string IdentityProviderName
{
get { return "Extensions.AzureAd"; }
}
protected string AadInstance
{
get { return Settings.GetSetting("AADInstance"); }
}
protected string Tenant
{
get { return Settings.GetSetting("Tenant"); }
}
protected string TenantId
{
get { return Settings.GetSetting("TenantId"); }
}
protected string ClientId
{
get { return Settings.GetSetting("ClientId"); }
}
protected string ClientSecret
{
get { return Settings.GetSetting("ClientSecret"); }
}
protected string PostLogoutRedirectUri
{
get { return Settings.GetSetting("PostLogoutRedirectURI"); }
}
protected string RedirectUri
{
get { return Settings.GetSetting("RedirectURI"); }
}
protected override void ProcessCore(IdentityProvidersArgs args)
{
Assert.ArgumentNotNull(args, nameof(args));
var identityProvider = this.GetIdentityProvider();
var authenticationType = this.GetAuthenticationType();
//string aadInstance = Settings.GetSetting("AADInstance");
//string tenant = Settings.GetSetting("Tenant");
//string tenantId = Settings.GetSetting("TenantId");
//string clientId = Settings.GetSetting("ClientId");
//string clientSecret = Settings.GetSetting("ClientSecret");
//string postLogoutRedirectURI = Settings.GetSetting("PostLogoutRedirectURI");
//string redirectURI = Settings.GetSetting("RedirectURI");
//const string graphResource = "https://graph.microsoft.com";
string authority = string.Format(CultureInfo.InvariantCulture, AadInstance, Tenant);
args.App.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
Caption = identityProvider.Caption,
AuthenticationType = authenticationType,
AuthenticationMode = AuthenticationMode.Passive,
ClientId = ClientId,
Authority = authority,
PostLogoutRedirectUri = PostLogoutRedirectUri,
RedirectUri = RedirectUri,
CookieManager = this.CookieManager,
Scope = "openid profile email group.read.all",
//SaveTokens = true,
//RedeemCode = true,
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = notification =>
{
var identity = notification.AuthenticationTicket.Identity;
foreach (var claimTransformationService in identityProvider.Transformations)
{
claimTransformationService.Transform(identity,
new TransformationContext(FederatedAuthenticationConfiguration, identityProvider));
}
notification.AuthenticationTicket = new AuthenticationTicket(identity, notification.AuthenticationTicket.Properties);
return Task.FromResult(0);
},
//AuthorizationCodeReceived = notification =>
//{
// //ClientID generated in Client Secrets menu of app registration
// ClientCredential credential = new ClientCredential(ClientId, ClientSecret);
// //guid is AAD TenantID
// AuthenticationContext authContext = new AuthenticationContext(string.Format(AadInstance, TenantId));
// var accessTokenTask = authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(RedirectUri), credential, GraphResource);
// //The async code below is bad practice, please use approach from here https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect/blob/master/TodoListWebApp/App_Start/Startup.Auth.cs
// var accessToken = accessTokenTask.Result.AccessToken;
// Sitecore.Diagnostics.Log.Info($"DEBUGAAD: access token: {accessToken}", this);
// return Task.FromResult(0);
//}
AuthorizationCodeReceived = OnAuthorizationCodeReceived
}
});
}
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
{
ClientCredential credential = new ClientCredential(ClientId, ClientSecret);
//guid is AAD TenantID
AuthenticationContext authContext = new AuthenticationContext(string.Format(AadInstance, TenantId));
// var accessTokenTask = authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(redirectURI), credential);
// var accessTokenTask = authContext.AcquireTokenByAuthorizationCodeAsync(authorizationCode: context.Code, redirectUri: new Uri(RedirectUri), clientCredential: credential);
AuthenticationResult authenticationResult = await authContext.AcquireTokenByAuthorizationCodeAsync(context.Code, new Uri(RedirectUri), credential, GraphResource);
var accessToken = authenticationResult.AccessToken;
var idToken = authenticationResult.IdToken;
var identity = context.AuthenticationTicket.Identity;
identity.AddClaim(new System.Security.Claims.Claim("access_token", accessToken));
identity.AddClaim(new System.Security.Claims.Claim("id_token", idToken));
//ToDo: do MSFT graph API calls here
//ToDo: find the way to map claims again dynamically
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
//httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");
var data = new StringContent("{ 'securityEnabledOnly': true }", Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://graph.microsoft.com/v1.0/me/getMemberGroups", data);
Sitecore.Diagnostics.Log.Info($"DEBUGAAD: MSFT Graph API GetMemeberGroups call results: {response.Content.ReadAsStringAsync().Result}", this);
Sitecore.Diagnostics.Log.Info($"DEBUGAAD: access token: {authenticationResult.AccessToken}", this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment