Auth0 Home Blog Docs

Can Auth0 M2M Token Be Used To Send POST Requests?

To whom it may concern,

I have been trying to resolve this issue for the last 5-days and have been quite disappointed that I can’t seem to find any sort of documentation with regards to verifying if I can use Tokens to submit POST requests.

My current issue stems from a supposed final major bug with using Auth0 JWT Tokens, through the Client Credential Flow M2M method. Though I may understand that I am using a very unique setup:

  • React Frontend
  • Django Backend
  • No user login intended to access secured API access

I guess it just now leads me to questioning on whether simply, “Can I even send POST requests to a Auth0 JWT Token secured backend?”. If it is possible, hope someone may redirect me to a potential solution, else, at least I know I really need to source something else entirely.

The potential solutions I do only see with a React frontend, is to actually build a:

  • Express.js backend
  • Enable user-account login access

This would not be ideal as both options are not the intended use case, and it will dramatically require me to change extensive code, especially to rebuild an entire backend. I was suppose to launch 2-3 weeks ago, but apparently now, this is the last security roadblock I am facing.


Hope some kind soul may help to redirect me on a potential solution on how can I send POST requests, with JWT Token validation, to a Django backend?

The current code I am using is as follows, and sadly, the GET option works, but this POST request option doesn’t seem to work:

let getBackendConfig = {
            headers: { 
                "Content-Type": "application/json",
                Authorization: process.env.REACT_APP_JWT_AUTH0_HEADER + " " + auth0Token,
            },
        };



async function submitLocationViaPOST( dataToPOST ) {
            setIsLocationUploaded("process");
            try {
                Promise.all([
                    await axios
                        .post(urlSubmitLocationPOSTAPI, dataToPOST, getBackendConfig)
                        .then(response => {
                            console.log("👉 urlSubmitLocationPOSTAPI Reply Data: ", response);
                            if (response.status === 201) {
                                // EXECUTE ONLY IF RESPONSE IS "201" --- MEANING ENTRY CREATED SUCCESSFULLY
                                setIsLocationUploaded("finish");
                            }
                        })
                ]);
            }
            catch (err) {
                setIsLocationUploaded("error");
                console.log("😱 urlSubmitLocationPOSTAPI Error: " + err);
            }
        }

Yes, you can protect POST endpoints with a JWT access token.

What is the value of process.env.REACT_APP_JWT_AUTH0_HEADER ? Is the value Bearer ?

Best to provide the exact request headers in here (of course not the real access token itself), you can use the browser’s developer tools for that.

Thanks @mathiasconradt for replying.

Currently the header process.env.REACT_APP_JWT_AUTH0_HEADER is “JWT” instead of “Bearer”. My previous tests showed that as long as the receiving end is set as “JWT”, it will work as long as “JWT” is used in the sender header.

Hopefully I am not wrong in this presumption? The odd thing is that sending GET requests still works, but none of my POST requests are working.

Any tips to further testing where is the issue?

Without knowing your detailed configuration on both ends, it’s hard to say. Please provide the following info:

  • what is the response code / error you’re currently getting with your POST request?
  • please provide the headers of sample requests you do with both GET and POST request (remove any access tokens from it)
  • please provide the method signatures on your backend endpoints for both the GET and POST endpoint

Whether JWT instead of Bearer works or not depends on your backend configuration. Possibly not an issue. It just doesn’t sound that common to me. I assume your GET request uses the same authorization headers (using your getBackendConfig)?

Hi @mathiasconradt ,

Just sort of trialed and tested my way through and sort of found a viable working answer after 7-days of testing. Hopefully this solution may help someone else in the process.

However, at this juncture, I have to say I only did 1-3 successful testing session and the solution have not been vigorously tested. But it worked out every single one of the tests so far.


Basically, here are some key pointers:

  1. POST requests submissions are possible through use of JWT Tokens, just that there is a very specific method to get it working.
  2. Use of Classes within Django Rest Framework based server will not work when ‘permission_classes((IsAuthenticated, ))’ and ‘authentication_classes((JSONWebTokenAuthentication,))’ is enabled, but will work when they are disabled if you are using Django at the backend.
  3. Use of API_View codes in views.py will be the working solution to allow both ‘permission_classes((IsAuthenticated, ))’ and ‘authentication_classes((JSONWebTokenAuthentication,))’ to be enabled altogether.
  4. In the send request with a React Frontend, either with AXIOS or FETCH, it does seem to highly work when you include “Content-Type”: “application/x-www-form-urlencoded” instead of “Content-Type”: “application/json” in your POST request Headers.

Sample Sample Key Codes to Take Note:

A. FRONTEND — REACT

// HANDLES "POST" REQUESTS CONFIGS
        let postBackendConfig = {
            headers: { 
                "Content-Type": "application/x-www-form-urlencoded",
                Authorization: process.env.REACT_APP_JWT_AUTH0_HEADER + " " + auth0Token,
            },
        };

B. BACKEND — DJANGO REST FRAMEWORK

views.py

@csrf_exempt
@permission_classes((IsAuthenticated, ))
@authentication_classes((JSONWebTokenAuthentication,))
def newsubmission(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = SubmissionsSerializer(data=data)
        

        if serializer.is_valid():
            submitted = serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

One last key item to take note is with your sending / receiving Authorization Header, which is very critical to ensure that all this code works as well.

The following is an example for your to review your own codes as it is one of the common issues individuals faced while using JWT Tokens. I believe as long as both ends are the same, be it “JWT” or “Bearer” it will still work, but it will be highly recommended to use only either of “JWT” or “Bearer” as your options:


A. FRONTEND — REACT — SENDER AUTHORIZATION HEADER

Authorization: "JWT " + auth0Token,

B. BACKEND — DJANGO REST FRAMEWORK — RECEIVER AUTHORIZATION HEADER


settings.py


# JWT settings
JWT_AUTH = {
    ...
    'JWT_AUTH_HEADER_PREFIX': "JWT",
    ...

}

Really appreciate the help and support provided so far! Thank you so much! :wink:

1 Like

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.