API calling return 401 when using access token return by Auth0.webAuth() login

I follow the iOS quick start step by step to set up my app, and follow the quick start in the APIs section to create an API and set up my server. Then I try to follow this tutorial (https://auth0.com/docs/quickstart/native/ios-swift/04-calling-apis) to call my API, however, it doesn’t work. It always return 401. But when I used the ‘test’ in APIs section, the API works fine.

I compared the access token generated by login with the one generated by ‘test’ curl, the access token is shorter. I have tried attaching idToken instead of access token in my API call, but it still doesn’t work.

why I follow the quick start but end up with an fault?

When using the Test option in the APIs section the access token in question is guaranteed to be suitable to the selected API which means unless the API is incorrectly configured the call will succeed.

The above is an excellent way to troubleshoot that the API is correctly configured. In your case doing the call with the Test access token it works so it’s highly likely that the issue is not in the API.

By exclusion the problem should be in the client application; in particular, for such an error condition the most probable cause is that you’re either:

  1. sending the wrong token; it should be the access token that is sent to the API, not the ID token.
  2. sending an access token that is not suitable for the API in question.

Based on the information provided you seem to be in the second option. If you take a look at the quickstart step you mentioned you’ll notice that there is a call to an audience method that sets the audience associated with the authentication request. When you want the client application to obtain an access token suitable to call your own API that you defined in the dashboard then you must set the audience to match the identifier of the API you configured. In my opinion the quickstart does not go over this in sufficient detail so it likely needs to be revisited/updated, but based on what you shared you’re sending the wrong audience and as a consequence obtaining an access token not suitable to your API.