经过身份验证的提取请求仅工作一半时间

时间:2019-05-18 22:36:25

标签: django reactjs redux django-rest-framework fetch

我正在尝试从react组件向django api后端发出经过身份验证的提取请求,但是它只工作一半时间(通常是在我登录并验证用户身份之后)。另一半时间,我收到401(未经授权):“未经授权:/ api / payments / charge /”

我的redux开发工具清楚地表明令牌存在: token present

有人可以帮助我确定为什么吗?

前锋: 我的react组件的Submit方法:

async submit(ev) {
    // User clicked submit

    let {stripeToken} = await this.props.stripe.createToken({name: this.state.cardholderName})
    let amount = this.state.amount

    this.setState({
      isLoading: true,
    })
    let response = await fetch("http://127.0.0.1:8000/api/payments/charge/", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: 'JWT ' + this.props.token

        },
        body: JSON.stringify({stripeToken, amount})
    })

    if (response.ok) console.log("Purchase Complete!")
    if (response.ok) this.setState({complete: true, isLoading: false});

  }
const mapStateToProps = state => {
  return {
    token: state.token
  }
}

export default injectStripe(connect(mapStateToProps)(withStyles(styles)(CheckoutForm)))

BACKEND: api / views.py

class ChargeAndCreateCustomerAPIView(APIView):

    permission_classes = [permissions.IsAuthenticated]
    parser_classes = (JSONParser, )

    def post(self, request, *args, **kwargs):

        # Check if user is authenticated
        if self.request.user.is_authenticated:

            print('USER IS AUTHENTICATED')

            user = self.request.user

            if user.profile.stripe_customer_id != '':
                print('CUSTOMER ID IS: ' + str(user.profile.stripe_customer_id))
            else:
                print('CUSTOMER HAS NO ID')
                customer = stripe.Customer.create(
                    source=request.data['token']['id'],
                    email='paying.user@example.com',
                )
                user.profile.stripe_customer_id = customer.id
                user.save()

                print('created new customer id: ')
                print(user.profile.stripe_customer_id)

            amount = int(request.data['amount'])*100
            charge = stripe.Charge.create(
                amount=amount,
                currency='usd',
                description='A Django charge',
                customer=user.profile.stripe_customer_id
            )

        return Response(status=200)

settings.py

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        # 'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES' : (
        #'rest_framework.permissions.IsAuthenticated',
        #'rest_framework.permissions.IsAuthenticatedOrReadOnly',
        'rest_framework.permissions.AllowAny',
    )
}

失败时: 控制台错误: console error

终端中的

django服务器错误: django terminal error

1 个答案:

答案 0 :(得分:0)

我将JWT与Roll一起使用,并且遇到了类似的问题。

可能是每次服务器重新启动时,您的JWT机密都会重置。 在这种情况下,您发送的令牌将无法通过验证,因为机密有所不同,您需要重新生成令牌。

但是,要解决此问题,您可以在设置或其他地方对您的秘密进行硬编码以进行开发。