authenticationmicrosoft-graph-apisites

Failed to get the sites followed by user from Microsoft Graph


I am trying to retrieve the sites that the user is following from Microsoft Graph Explorer.

I found this document to do that: https://learn.microsoft.com/en-us/graph/api/sites-list-followed?view=graph-rest-1.0&tabs=http

In that document, they mentioned that a Bearer token is required for Authorization. But where can I get that token?

If I try to query without a token, I am getting "Authentication failed, No valid token found" 401 error. How to resolve that error?

Any help is appreciated. Thanks in advance


Solution

  • If you're using Graph Explorer, which is a Microsoft-created user interface to access the Graph API, you don't need to specify the token in the headers. When you sign into Graph Explorer with your user account, you'll automatically obtain a token, and it will be automatically supplied in your request.

    You can actually retrieve the token of the signed-in user from Graph Explorer as well, by clicking on the Access token button.

    enter image description here

    If you're accessing the Graph API from any other interface (e.g. code), you'll need to manually form the request headers and include the token that you've obtained.

    How to obtain a token for a service application would require further information, you can read more from the official documentation

    Here is a simple example using Python and MSAL, as well as the constructed request header.

    app = msal.ConfidentialClientApplication(
        client_id         = client_id,
        client_credential = client_secret,
        authority         = f"https://login.microsoftonline.com/{tenant_id}")
    
    scopes = ["https://graph.microsoft.com/.default"]
    
    token = None
    token = app.acquire_token_for_client(scopes = scopes)
    
    req_headers = {
        "Authorization": "Bearer " + token['access_token']
        }