Auth0: How to Submit POST Using M2M Token with React Frontend

孤街浪徒 提交于 2019-12-11 14:57:59

问题


I was unable to find any sort of solution on integrating a working POST-request submission, using Auth0's M2M Token Client Credential Flow process, to submit a POST entry to my Django backend from my React frontend.

I’ve currently fully built on a setup compromising of the following, with Auth0 somewhat fully integrated:

  1. Frontend:

    • React Browser Setup making POST to retrieve AUTH0 token via Auth0 server.
    • React Browser Setup using retrieved M2M Token based on JWT authentication, to execute GET requests to backend for data.
  2. Backend:

    • Django Backend Setup authenticating M2M Token with GET requests to release data.

The above setup currently works originally without any Auth0 implementation and subsequently, with GET data requests. However, the issue finally popped up recently, when I attempted to make POST data requests.


I do realised that given my setup where,

  • request codes based on React,
  • token used retrieved via M2M setup,

I was unable to find any sort of solution on integrating a working POST-request submission to my Django backend.

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);
            }
        }

I currently do know that if without any Auth0 authentication, the overall current POST requests will work.

The above codes are a sample POST-request code of what previously worked without Auth0 and suddenly threw a 500 error when Auth0 is implemented, when presumably a 500 error thrown is that the JWT authentication config might be wrongly coded. I hope that someone can help pinpoint potential code changes I can make, in attempt to rectify it to work through the Auth0 POST-request submission:


Hope to hear back from someone who can assist on this issue. Much appreciated in advance for the help!


回答1:


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",
    ...

}

I would like to also extend my thanks to @Dan Woda for providing assistance previously.



来源:https://stackoverflow.com/questions/56854148/auth0-how-to-submit-post-using-m2m-token-with-react-frontend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!