I have built an application using python django rest framework and Vue js.
The rest framework link is something similar like this 198.123.1.1:8001/test i am using this link to get records in Vuejs.
when i call this link generally 198.123.1.1:8001/test
GET /test/
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"test_id": 11,
"test_n_key": "as-all-1",
}
i am getting the below response now i want to hide this response to outside world and what will be the better way to do it.
1)I don't want to show this url to outside world.
2)when someone is calling this from browser other than application it should not show it
if the API is exposed to the outside world you cant hide it, add an authentication to the API and prevent external request.
Add authentication and CORS:
CORS-Headers
Authentication
Related
I have an issue related to access_token which I've received from a React Native app. The React Native app uses the expo-facebook library and when the pop-up of authentication disappears the token is created and sent to the backend API. The token is created by logInWithReadPermissionsAsync method.
const { type, token, expirationDate, permissions, declinedPermissions, graphDomain } =
await Facebook.logInWithReadPermissionsAsync({
permissions: ["public_profile", "email"],
});
I see that the server received this token on http://localhost:8000/api/rest-auth/facebook/ endpoint and sends it to the Facebook endpoint verify. The problem occurs on the response from Facebook. I expect that it should be valid by Facebook, but it seems that something went wrong.
HTTP 400 Bad Request
Allow: POST, OPTIONS
Content-Type: application/json
Vary: Accept
{
"non_field_errors": [
"Incorrect value."
],
"code": 400,
"message": "Bad Request"
}
An access token that I generate in Graph API Explorer is shorter (when I use it, it works in the backend app) than the token which is generated in the React Native expo app. Why are these two tokens different? And why doesn't it work as I am expecting?
I discovered where the issue was. I knew that the issue is was in the token, a good direction was a response from Facebook.
{"error":{"message":"Invalid appsecret_proof provided in the API argument","type":"GraphMethodException","code":100}}.
After that, I realized that probably something is wrong with React Native Expo. Expo-facebook doesn't react when you even pass the app id, it used the wrong APP ID which was defined in the expo environment(APP_ID=1696089354000816). App-id was set in settings and also in the
await Facebook.initializeAsync({
appId: '<APP_ID>',
});".
So the main issue was that I relied on an access_token that didn't belong to my app.
Hay ! I am new here so let me describe clearly my issue,Please Ignore mistakes.
I am making request on a page which literlaly works on js.
Acually its the page of paytm payemnt response through UPI.
When ever i do the requests the response is {'POLL_STATUS':"STOP_POLLING"}
But the problem is the reqest is giving this response while the browser is giving another response with loaded html.
I tried everyting like stopeed redirects and printing raw content nothing works.
I just think may be urllib post request may be work but i do not know the uses.
Can anyone please tell me how to get the exact html response as the browser gives.
Note[0]:Please dont provide answer of selenium because this issue having in the middle of my script.
Note[1]:Friendly answer appriciated.
for i in range(0,15):
resp_check_transaction=self.s.post("https://secure.website.in/theia/upi/transactionStatus?MID="+str(Merchant_ID)+"&ORDER_ID="+str(ORDER_ID),headers=check_transaction(str(ORDER_ID)),data=check_transaction_payload(Merchant_ID,ORDER_ID,TRANSID,CASHIERID))
print(resp_check_transaction.text)
resp_check_transaction=resp_check_transaction.json()
if resp_check_transaction['POLL_STATUS']=="STOP_POLLING":
print("Breaking looop")
break
time.sleep(4)
self.clear_header()
parrms={
"MID": str(Merchant_ID),
"ORDER_ID": str(ORDER_ID)
}
resp_transaction_pass=requests.post("https://secure.website.in/theia/upi/transactionStatus",headers=transaction_pass(str(ORDER_ID)),data=transaction_pass_payload(CASHIERID,UPISTATUSURL,Merchant_ID,ORDER_ID,TRANSID,TXN_AMOUNT),params=parrms,allow_redirects=True)
print("Printing response")
print(resp_transaction_pass.text)
print(resp_transaction_pass.content)
And in the web browser its showing that Status Code: 302 Moved Temporarily in the bank response of Bank response. :(
About the 302 status code
You mention that the web browser is sends a 302 status code in response to the request. In the simplest terms the 302 status code is just the web servers way of saying "Hey I know what you're looking for but it is actually located at this other URL.".
Basically all modern browsers and HTTP request libraries like Python's Requests will automatically follow a 302 redirect and act as though you send the request to the new URL instead. (Your browser's developer tools may show that a 302 redirect has happened but as far as the JavaScript is concerned it just got a normal 200 response).
If you really want to see if your Python script receives a 302 status you can do so by setting the allow_redirects option to False, but this means you will manually have to get the stuff from the new URL.
import requests
r1 = requests.get('https://httpstat.us/302', allow_redirects=False)
r2 = requests.get('https://httpstat.us/302', allow_redirects=True)
print('No redirects:', r1.status_code) # 302
print('Redirects on:', r2.status_code) # 200 (status code of page it redirects to)
Note that allow_redirects is already set to True by default, I just wanted to make the example a bit more verbose so the difference is obvious.
So why is the response content different?
So even though the browser and the Requests library are both automatically following the 302 redirect the response they get is still different, you didn't share any screenshots of the browsers requests or responses so I can only give a few educated guesses but it boils down to the fact that the request made by your Python code is somehow different from the JavaScript loaded by the web browser.
Some things to consider:
Are you sure you are using the he correct HTTP method? Is the browser also making a POST request?
If so are you sure the body of the request is the same/of the same format as the one sent by the web browser?
Perhaps the browser has a session cookie it is sending along with the request (Note this usually not explicitly said in the JS but happens automatically).
Alternatively the JS might include some API key/credentials in the HTTP auth header (this should be explicitly visible in JS).
Although unlikely it could be that whatever API you're trying to query is trying to block reverse engineering attempts by blocking the Requests library's user agent string.
Luckily all of these differences can be easily examined with some print statements and your browser's developer tools :p.
I'm currently stopped in my work because of some authentication work on a project.
I set up a REST API, which needs to have a JWT authentication system.
Some work was already done and I overrode it. So the library used was Python's TurboGears2, and I used PyJWT to manage tokens.
My WS and the token's creation works well. The post method with auth info JSON request's body can create a token, that's sent in the response.
But after that, when I do a 'GET' request on the restricted resource, I can't retrieve the token.
What I do: send a GET request to the restricted resource, with "Authorization: Bearer <TOKEN>" in request headers.
But when I do a 'request.authorization' in my web service function, I always get 'None'.
Do I need to set up a full auth system using TurboGears to access this header?
thanks for help
Where are you trying to access the request.authorization from?
I tried with a newly quickstarted application and modified the index to print the authorization header:
#expose('testauth.templates.index')
def index(self):
"""Handle the front-page."""
print(request.authorization)
return dict(page='index')
And I sent the authorization header from Postman.
It worked fine and printed my test header
Authorization(authtype='Bearer', params='HELLO')
I also tried to disable any auth_backend so that authentication is disabled and it still works as expected.
I'm using both Appcelerator Titanium and Python's Django to create a mobile app. As you might have guessed, Django is being used for the back-end. At the moment I'm trying to create a login form which requires a CSRF token to accept the data correctly. I'm trying to retrieve the CSRF token from Django, but I've tried and failed, and Google doesn't have any answers for me.
The problem is normally you'd get an HTML page with a CSRF token included in the form and just send it. What I'm trying to do now is send a POST without knowing the CSRF. In appcelerator, I've tried running
HTTPSession.open(GET, *url*)
token = HTTPSession.getRecievedHeaders("X-CSRF-TOKEN")
HTTPSession.open(POST, *url)
HTTPSession.getRecievedHeaders("X-CSRF-TOKEN", token)
HTTPSession.send(data)
But this doesn't work because of how Titanium works. So how can I get the token? Do I need to create a specific url just to create a session and display a CSRF token? I'm just worried that once I've recieved the token, I'll need to reconnect to the server and the token will have changed.
During my Googling, I found that Drupal has a function for this at the url: services/session/token
Is there an equivillant for this in Django? Or do I need to create my own page showing just a CSRF token?
If you are using Titanium for app creation you can use SetRequestHeader for setting the token with the request.
Hope it helps.
I needed to create my own function in Django to achieve this, but I finally got it working!
function getCSRF() {
var csrfHTTP = Ti.Network.createHTTPClient({
onload : function() {
Ti.App.Properties.setString("csrf", this.responseText);
}
});
csrfHTTP.open("GET", "http://website.com/api/csrftoken/");
csrfHTTP.send();
}
Then retrieve it via
Ti.App.Properties.getString("csrf")
and use it:
loginHTTP.setRequestHeader("X-CSRFToken", Ti.App.Properties.getString("csrf"));
Connecting to the website once creates a session in Django also creating a csrf token for that specific IP to use so you can retrieve it multiple times if needed
I wrote a Django view that responses ether a text/html or a application/json depending on request.is_ajax().
So far so good, but when I use my browsers history buttons, I end up getting a JSON response rather than the HTML.
I can't figure out the problem. It's true an jQuery ajax request is getting the same url after the page was loaded, but that shouldn't end up in the history, or should it?
Thanks, Joe
If you send different content depending on request.is_ajax(), you need to send Vary: X-Requested-With to the browser. That way, the browser will be able to distinguish the two kinds of response based on the value of the X-Requested-With header on the request. You can do that via:
from django.views.decorators.vary import vary_on_headers
#vary_on_headers('X-Requested-With')
def yourview(request, ...):
pass