简体   繁体   中英

How can I make my Django API only accept requests that come from my website itself?

I had to create an API for my Django application for something sensitive that I couldn't have in a public and static Javascript file.How can I make it so that this view only accepts requests coming from my own website, and reject any from the "outside" (if someone copied my request below they should get an error)?

If there are any other security concerns please do mention them in your response. My website is hosted on Heroku.

The request in my javascript file:

var clientSecret = await fetch('https://url.com/api/', {
    method: 'POST',
    body: params,
    headers: {
        'Content-Type': 'text/plain'
      },
}).then(r => r.json())

My view for my API ( https://url.com/api/ ):

from rest_framework.request import Request as RESTRequest
from rest_framework.response import Response
from rest_framework.decorators import api_view
import requests

@api_view(['POST'])
def payment(request, *args, **kwargs):
    ... #define headers_in and params_in here
    response = requests.post('https://outboundapirequest.com/v1/request', 
            headers=headers_in,
            data=params_in)

    return Response(response.json()['value'])

By using ''cross-origin resource sharing (CORS)''

In Django settings you can set a list of all domains where requests to your API server are allowed to originate.

Like so

CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:9000" ]

Here is a detailed reference on how to set it up

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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