简体   繁体   English

Auth0:如何使用M2M令牌和React Frontend提交POST

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

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. 我无法找到使用Auth0的M2M令牌客户端凭据流程流程集成工作POST请求提交的任何解决方案,以从我的React前端向Django后端提交POST条目。

I've currently fully built on a setup compromising of the following, with Auth0 somewhat fully integrated: 我目前完全建立在以下设置的妥协基础上,并完全集成了Auth0:

  1. Frontend : 前端

    • React Browser Setup making POST to retrieve AUTH0 token via Auth0 server. 反应浏览器设置,使POST通过Auth0服务器检索AUTH0令牌。
    • React Browser Setup using retrieved M2M Token based on JWT authentication, to execute GET requests to backend for data. 使用基于JWT身份验证的检索到的M2M令牌来反应浏览器设置,以执行GET请求以向后端发送数据。
  2. Backend : 后端

    • Django Backend Setup authenticating M2M Token with GET requests to release data. Django后端安装程序使用GET请求对M2M令牌进行身份验证以释放数据。

The above setup currently works originally without any Auth0 implementation and subsequently, with GET data requests. 目前,上述设置最初可以在没有任何Auth0实现的情况下正常运行,随后可以使用GET数据请求。 However, the issue finally popped up recently, when I attempted to make POST data requests. 但是,当我尝试发出POST数据请求时,该问题终于在最近弹出。


I do realised that given my setup where, 我确实意识到,根据我的设置,

  • request codes based on React, 根据React请求代码
  • token used retrieved via M2M setup, 通过M2M设置获取的使用令牌,

I was unable to find any sort of solution on integrating a working POST-request submission to my Django backend. 在将有效的POST请求提交集成到Django后端时,我找不到任何解决方案。

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. 我目前确实知道,如果没有任何Auth0身份验证,则当前所有的POST请求都将起作用。

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. 上面的代码是POST请求代码的示例,该代码以前在没有Auth0的情况下可以工作,并且在实现Auth0时突然引发了500错误,可能抛出500错误是JWT身份验证配置可能被错误编码。 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: 我希望有人可以帮助查明我可以进行的潜在代码更改,以尝试通过Auth0 POST请求提交来纠正它:


Hope to hear back from someone who can assist on this issue. 希望能收到可以解决此问题的人的回音。 Much appreciated in advance for the help! 提前非常感谢您的帮助!

Just sort of trialed and tested my way through and sort of found a viable working answer after 7-days of testing. 经过7天的测试后,我进行了一些尝试和测试,找到了一个可行的工作答案。 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. 但是,此时此刻,我不得不说我只成功完成了1-3次测试,而该解决方案尚未经过严格测试。 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 . 可以通过使用JWT令牌来提交POST请求 ,只是有一种非常具体的方法可以使其工作
  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. 启用 ' Permission_classes((IsAuthenticated,)) '和' authentication_classes((JSONWebTokenAuthentication,)) '后在基于Django Rest Framework的服务器中使用类将无法工作,但是如果您在后端使用Django,则在禁用它们时将可使用。
  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. 在views.py中使用API_View代码将是可行的解决方案,以允许同时启用Permission_classes((IsAuthenticated,)) ”和“ authentication_classes((JSONWebTokenAuthentication,)) ”。
  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. 在带有AXIOS或FETCH的带有React Frontend的发送请求中,当您包括“ Content-Type”:“ application / x-www-form-urlencoded”而不是“ Content-Type”: POST请求标头中的application / json”。

Sample Sample Key Codes to Take Note: 需要注意的样本样本关键代码:

A. FRONTEND --- REACT A.前锋---反应

// 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 B.后端-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. 以下是一个示例,您可以自己检查自己的代码,因为它是个人在使用JWT令牌时面临的常见问题之一。 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: 我相信只要两端相同,无论是“ J​​WT”还是“ Bearer”,它仍然可以工作,但是强烈建议仅使用“ JWT”或“ Bearer”作为您的选择:


A. FRONTEND --- REACT --- SENDER AUTHORIZATION HEADER A.前锋---反应---发件人授权标题

Authorization: "JWT " + auth0Token,

B. BACKEND --- DJANGO REST FRAMEWORK --- RECEIVER AUTHORIZATION HEADER B.后端--- DJANGO REST框架---接收器授权标头


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. 我还要感谢@Dan Woda以前提供的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM