protected override void ExecuteCmdlet() { var officeManagementApiToken = OfficeManagementApiToken.AcquireToken(TenantId, ClientId, ClientSecret); WriteObject(officeManagementApiToken.AccessToken); }
/// <summary> /// Tries to get a token for the provided audience /// </summary> /// <param name="tokenAudience">Audience to try to get a token for</param> /// <param name="roles">The specific roles to request access to (i.e. Group.ReadWrite.All). Optional, will use default groups assigned to clientId if not specified.</param> /// <returns><see cref="GenericToken"/> for the audience or NULL if unable to retrieve a token for the audience on the current connection</returns> internal GenericToken TryGetToken(TokenAudience tokenAudience, string[] roles = null) { GenericToken token = null; // Validate if we have a token already if (AccessTokens.ContainsKey(tokenAudience)) { // We have a token already, ensure it is still valid token = AccessTokens[tokenAudience]; if (token.ExpiresOn > DateTime.Now) { // Token is still valid, ensure we dont have specific roles to check for or the requested roles to execute the command are present in the token if (roles == null || roles.Length == 0 || roles.Any(r => token.Roles.Contains(r))) { return(token); } if (roles != null) { // Requested role was not part of the access token, throw an exception explaining which application registration is missing which role throw new PSSecurityException($"Access to {tokenAudience} failed because the app registration {ClientId} in tenant {Tenant} is not granted {(roles.Length != 1 ? "any of " : string.Empty)}the permission{(roles.Length != 1 ? "s" : string.Empty)} {string.Join(", ", roles).TrimEnd(new[] { ',', ' ' })}"); } } // Token was no longer valid, proceed with trying to create a new token } // We do not have a token for the requested audience yet or it was no longer valid, try to create (a new) one switch (tokenAudience) { case TokenAudience.MicrosoftGraph: if (!string.IsNullOrEmpty(Tenant)) { if (Certificate != null) { token = GraphToken.AcquireToken(Tenant, ClientId, Certificate); } else if (ClientSecret != null) { token = GraphToken.AcquireToken(Tenant, ClientId, ClientSecret); } } break; case TokenAudience.OfficeManagementApi: if (!string.IsNullOrEmpty(Tenant)) { if (Certificate != null) { token = OfficeManagementApiToken.AcquireToken(Tenant, ClientId, Certificate); } else if (ClientSecret != null) { token = OfficeManagementApiToken.AcquireToken(Tenant, ClientId, ClientSecret); } } break; case TokenAudience.SharePointOnline: // This is not a token type we can request on demand return(null); } if (token != null) { // Managed to create a token for the requested audience, add it to our collection with tokens AccessTokens[tokenAudience] = token; return(token); } // Didn't have a token yet and unable to retrieve one return(null); }