# M2M scopes end to end

## 1. Register the API

Applications > APIs > Create API. Identifier e.g. `https://YOUR-API-IDENTIFIER`. This string is the audience.

## 2. Define permissions

APIs > your API > Permissions tab > Add Permission: `read:orders`, `write:orders`. Defining them only makes them grantable; nobody has them yet.

## 3. Authorize the app

Applications > your M2M app > APIs tab > Authorize the API > tick the scopes this app may request. This is the grant. Alternatively the Management API grants endpoint. The app can now request any SUBSET of these scopes.

## 4. Request with scopes

```
curl --request POST --url https://YOUR-TENANT-DOMAIN/oauth/token   --header "content-type: application/json"   --data '{"client_id":"[your value]","client_secret":"[your value]",
           "audience":"https://YOUR-API-IDENTIFIER",
           "grant_type":"client_credentials","scope":"read:orders"}'
```

Omit scope to get all granted scopes. Requesting a scope the app was not granted fails the whole request.

## 5. Enforce in the API

```
const { auth, requiredScopes } = require("express-oauth2-jwt-bearer");
app.get("/orders", checkJwt, requiredScopes("read:orders"), handler);
```

Check `req.auth.payload.scope` contains what the route needs.

## Debugging chain

Token has no scope claim: step 3 or 4. 403 from requiredScopes: token scope vs route scope. "Grant type not allowed": app type wrong.

## Checklist

- Four steps, in order, all four done.
- Least privilege: grant only the scopes the service needs.