How to get SharePoint site logo using Graph?

EJ 366 Reputation points
2022-09-26T06:38:56.91+00:00

Hi,

I'm creating open/save dialog similar to Excel which displays OneDrive and SharePoint Sites. I want to display sites with their logos (colored square boxes), but can't find a way how to obtain them. Graph API doesn't have any API to get site logos, so I've tried getting directly from SharePoint website like in below example:

string url = $"https://{tenantname}.sharepoint.com/sites/{sitename}/_api/siteiconmanager/getsitelogo?type=1";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add( "Authorization", new AuthenticationHeaderValue("bearer", AuthenticationHelper.TokenForUser).ToString());

Problem is I get 401 response, e.g. not authorized.

Any ideas how can I get around this or obtain site logos using different approach?

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,316 questions
SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
9,408 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,615 questions
{count} votes

5 answers

Sort by: Most helpful
  1. EJ 366 Reputation points
    2022-09-26T22:50:23.22+00:00

    Hi,

    Authentication code:

    public static GraphServiceClient GetAuthenticatedClient()  
            {  
                if (graphClient == null)  
                {  
                    // Create Microsoft Graph client.  
                    try  
                    {  
                        graphClient = new GraphServiceClient(  
                            $"https://graph.microsoft.com/v1.0/",  
                            new DelegateAuthenticationProvider(  
                                async (requestMessage) =>  
                                {  
                                    var token = await GetTokenForUserAsync();  
                                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);  
                                }));  
                        return graphClient;  
                    }  
      
                    catch (Exception ex)  
                    {  
                        Debug.WriteLine("Could not create a graph client: " + ex.Message);  
                    }  
                }  
      
                return graphClient;  
            }  
      
            public static async Task<string> GetTokenForUserAsync()  
            {  
                AuthenticationResult authResult;  
                var accounts = await IdentityClientApp.GetAccountsAsync();  
      
                try  
                {  
                    authResult = await IdentityClientApp.AcquireTokenSilent(Scopes, accounts.FirstOrDefault()).ExecuteAsync();  
                    TokenForUser = authResult.AccessToken;  
                }  
      
                catch (Exception)  
                {  
                    if (TokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))  
                    {  
                        authResult = await IdentityClientApp.AcquireTokenInteractive(Scopes).ExecuteAsync();  
      
                        TokenForUser = authResult.AccessToken;  
                        Expiration = authResult.ExpiresOn;  
                    }  
                }  
      
                return TokenForUser;  
            }  
    

    And this is the code which tries to get site icon:

    string url = $"https://{tenantname}.sharepoint.com/sites/{sitename}/_api/siteiconmanager/getsitelogo?type=1";  
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);  
    request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36";   
    request.Headers.Add( "Authorization", new AuthenticationHeaderValue("bearer", AuthenticationHelper.TokenForUser).ToString());  
          
    using (var response = request.GetResponse())  
    {  
        using (var stream = response.GetResponseStream())  
        {  
            System.Drawing.Image image = Bitmap.FromStream(stream);  
        }  
    }  
    
    0 comments No comments

  2. CarlZhao-MSFT 36,001 Reputation points
    2022-09-27T09:01:54.99+00:00

    Hi @EJ

    I noticed that your code is calling the SP Rest API with the graph API's token, so that's what's causing the problem. Since there is no SDK specific to the SP Rest API, I am using a PowerShell command to call this endpoint:

      $clientID = 'client id'             
      $secretKey = 'client secret'           
      $tenantID = 'tenant id'        
      $userName = 'user name'        
      $password ='password'              
      $authUrl = "https://login.microsoftonline.com/" + $tenantID + "/oauth2/v2.0/token/"            
      $body = @{             
          "scope" = "https://jmaster.sharepoint.com/.default";             
          "grant_type" = "password"             
          "client_id" = $ClientID             
          "client_secret" = $secretKey        
          "username" = $userName      
          "password" = $password          
      }                     
      $authToken = Invoke-RestMethod -Uri $authUrl –Method POST -Body $body                         
      $url = "https://{tenant name}.sharepoint.com/sites/{site name}/_api/siteiconmanager/getsitelogo?type=1"        
      $headers = @{             
      "Authorization" = "Bearer $($authToken.access_token)"        
       "Content-Type"  = "image/jpg"             
      }             
      Invoke-RestMethod -Uri $url -Headers $headers -Method Get    
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. CarlZhao-MSFT 36,001 Reputation points
    2022-09-28T08:54:54.787+00:00

    Hi @EJ

    Or you can also directly use postman to call this endpoint to get the site logo.

    245435-image.png

    245453-image.png


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  4. EJ 366 Reputation points
    2022-09-29T01:18:39.57+00:00

    Hi,

    Our Azure AD requires multifactor authentication so we can't use direct OAuth like your PowerShell code does as we don't know user password.

    I wonder if we could use IdentityClientApp for SharePoint authentication similar how its done for GraphClient?


  5. CarlZhao-MSFT 36,001 Reputation points
    2022-09-30T10:12:33.837+00:00

    Hi @EJ

    Of course, if you're using MFA, then ROPC flow obviously doesn't apply. However, you can use auth code flow for SharePoint authentication, which is no different from verifying the graph client.

    246436-page-3.png


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments