Wednesday, January 4, 2023

Using Postman to Authenticate to GraphQL

With the release of Sitecore 10.3, a whole bunch of new capabilities have come into GraphQL, such as the ability to create items and templates, do index rebuilds, publish items, and so forth.  But the documentation for setting up authentication to these services is somewhat intimidating, requiring you to build an MVC controller just to sign in.  In fact, it's pretty simple to set authentication with Postman too, which will be a familiar option for those who have worked with Sitecore Commerce.
First step, enable GraphQL. You can do that by dropping this file in your App_Config/Environments folder:

<?xml version="1.0" encoding="UTF-8"?>
<sitecore xmlns:set="http://www.sitecore.net/xmlconfig/set">
    <settings>
        <setting name="GraphQL.Enabled" set:value="true" />
        <setting name="GraphQL.ExposePlayground" set:value="true" />
    </settings>
</sitecore>

Now you should be able to hit the GraphQL playground at this URL:

https://<site root>/sitecore/api/authoring/graphql/playground/

The first time you open this, you may see this displayed on the right:

{
  "error": "Unexpected token '<', \"<!DOCTYPE \"... is not valid JSON"
}

You can fix this by updating the URL bar inside the tool to point to:

https://stock103sc.dev.local:443/sitecore/api/authoring/graphql/v1/


and change the panel on the left to have a valid query, like

query {sites { name }}

Now you should see a valid GraphQL response, indicating you are not authenticated.

{
  "errors": [
    {
      "message": "The current user is not authorized to access this resource.",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "sites"
      ],
      "extensions": {
        "code": "AUTH_NOT_AUTHENTICATED"
      }
    }
  ],
  "data": {
    "sites": null
  }
}

In context, it will appear like this:



Enabling Authentication

Now let's authenticate.  We'll do this by adding a "bearer" token to the HTTP Headers section on the bottom left, and we'll get that token by using Postman.

I've created a simple, publically accessible Postman collection here.  You can also download this collection in JSON format here, and import it into your local Postman instance. 

Before we get started with Postman, we'll need to make Identity Sever ready to accept Postman calls. We can do that by adding the following lines to the Siteocore.IdentityServer.Host.xml, in the Clients node: 

Recycle the Identity Server app service, and now open that first, publically accessible, Postman link. Postman allows you to privately change environment values. Click on "Variables"

Then update your local values here:

Per Postman's documentation, these are private:


Now with the URL changed to your own identity server, and password (hopefully!) changed from "b", you can issue a GetToken request.

(But first, apparently, you need to create a free account. The things you learn doing Incognito mode testing.) 


Second late edit: You can't hit a private URL form the Browser client. You'll have to download the Desktop version, but you should still be able to access the collection by searching for "Sitecore API Bearer Token Authenticator", or importing the collection from the JSON format I linked to earlier.  (I need to dig deeper into how Postman collection sharing works.)



In Postman Desktop mode, with variables updated correctly, you should be able to fire GetToken, and see an access token come back:



I also left it place some magic from the Sitecore Commerce Postman collection to save that token value to a Global variable (look at the green dot on the "Test" tab), so you can also get to it by clicking on the button in the top right:

then:


then copy this whole value:



Putting the pieces together

Now that you have a token, go back to the GraphQL playground, and click on HTTP HEADERS:



And then past this, using the token you just generated, ensuring it is preceded with "Bearer ":


Now click that big Play button again. If you see this, you are ready to start exploring all the new 10.3. GraphQL capabilities:


Digging deeper:

  • A fun, live GraphQL tutorial, featuring R2-D2. A few key points:
    • Requests look like JSON, with the return values stripped out. 
    • It is less chatty than REST, with the ability to ask for several elements of data at once, e.g. a parent and several children.  
    • It supports introspection, and thus intellisense like behavior in smart clients.  You can confirm this by right clicking on the left in the Playground.
    • Despite the "V1" in Sitecore's URL, you don't really need to version GraphQL APIs, since capabilities can be added in a non destructive way.  They say it's fine, but they don't really encourage it.
  • Sitecore's documentation for creating an access token, which involves building an MVC controller.  
    • I had recalled the Postman workflow with Identity Server from previous commerce work, so wanted to explore whether that would work with GraphQL. Hence this post.
  • Sitecore's new authoring and management endpoints.
  • Postman docs. This tool is going to be very important in our Services focused future.  For example, OrderCloud is documented using a Postman collection.







No comments:

Post a Comment