Azure-Samples / active-directory-dotnet-graphapi-web

A .NET 4.5 MVC web app that demonstrates how to query the Azure AD Graph API using the Azure AD Graph Client Library
82 stars 68 forks source link

Multitenant application #38

Open shyambhiogade opened 8 years ago

shyambhiogade commented 8 years ago

hi, can this application be made multinatenant

Compufreak345 commented 7 years ago

FYI : I was able to convert the application to multitenant by using some code from this project : https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-multitenant-openidconnect

Probably the most complicated step for this process was getting rid of the static token and changing the AuthenticationHelper accordingly, I came up with this code :

internal class AuthenticationHelper
{

    /// <summary>
    ///     Async task to acquire token for Application.
    /// </summary>
    /// <returns>Async Token for application.</returns>
    public static async Task<string> AcquireTokenAsync()
    {
        string clientId = ConfigurationManager.AppSettings["ida:ClientID"];
        string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
        string graphResourceID = Constants.ResourceUrl;
        string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
        string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
        string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

        // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
        ClientCredential clientcred = new ClientCredential(clientId, appKey);
        // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
        AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", tenantID), new EFADALTokenCache(signedInUserID));
        AuthenticationResult result = await authContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
        return result.AccessToken;
    }

    /// <summary>
    ///     Get Active Directory Client for Application.
    /// </summary>
    /// <returns>ActiveDirectoryClient for Application.</returns>
    public static ActiveDirectoryClient GetActiveDirectoryClient()
    {
        string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
        Uri baseServiceUri = new Uri(Constants.ResourceUrl);
        ActiveDirectoryClient activeDirectoryClient =
            new ActiveDirectoryClient(new Uri(baseServiceUri, tenantID),
                async () => await AcquireTokenAsync());
        return activeDirectoryClient;
    }
}