DJango Post csrf_token invalid and /favicon.ico not found - javascript

I got a problem with DJango. Im trying to send data to a SQL Database in DJango. So I need my token, which I get with {{ csrf_token }}. But when I send the data on the HTML Website, it tells me POST 403 Forbidden and the DJango Terminal says NotFound: /favicon.ico, as well as Forbidden (CSRF token from POST has incorrect length.): /ausgeben/
Does anyone have a solution for this. Down below is the code I`m using for the token request.
Thanks!
let formData = new FormData();
formData.append("name", name);
formData.append("gewinde", gewinde);
formData.append("laenge", laenge);
formData.append("durchmesser", durchmesser);
//formData.append("containerNR", containerNR);
formData.append('csrfmiddlewaretoken', token);
fetch('/ausgeben/',{
method: 'POST',
body: formData
});

Try sending the csrftoken in the fetch headers rather than in the body of the request. Disclaimer that I haven't used this with fetch but it was necessary with JQuery and an $.ajax request.
fetch('/ausgeben/',{
headers: {
'X-CSRFToken': token
},
...

TL;DR
Add a favicon.ico
Long version :
Searching for more topics about CSRF issues, I found this one.
I think you are facing an old (but it seems still valid) issue with CSRF and some browsers. It is often related to the favicon.ico file but it could happen with other static ressources (like javacript sourcemap *.map files).
After accessing your page, the browser requests the favicon.ico. If the file does not exist AND the request is handled by your framework, it could lead to generating a new CSRF token, therefore making the one on your form invalid.
To quote another :
Users are assigned a session cookie when they land on a PHP page. A CSRF token is associated with a session when users visit the login page.
Favicon requests were going to PHP instead of a static resource. Normally that's fine, since PHP will see the cookie.
But since the request looked like it was for a static resource, Varnish stripped the cookies before passing it back to Apache/PHP. That meant PHP issued a new session that replaced the old one.
https://news.ycombinator.com/item?id=3590328

Related

Access and Refresh Tokens

I am using caspio rest api to authenticate my users in a mobile app. Upon authenticating, I was given an access token to which I included in my AJAX call under the parameter 'Authorization' : Bearer [access token].
I understand that I can renew the token with the refresh token given to me where I can use the POST call.
My question is: prior to using the POST call for a new token, must I store the access token?
Also, the Caspio website advised this format for the POST call:
Method: POST
URL: Token Endpoint
Body: grant_type=refresh_token&refresh_token= [token value]
Header parameters:
Authorization: Basic [string "Client_ID:Client_Secret" encoded in Base64]
Content-Type: application/x-www-form-urlencoded
Should I also include the client ID and client secret in the parameters? Upon using Firefox's rest client, I'm getting a bad request (400) error.
Thank you for the help!
I never using caspio rest api before. The answer base on my OAuth experiences.
My question is: prior to using the POST call for a new token, must I store the access token?
YES! The OAuth 2.0 using the access token to switch the refresh token at first time.
Should I also include the client ID and client secret in the parameters? Upon using Firefox's rest client, I'm getting a bad request (400) error.
According to the api document. You should include the client ID and client secret in your request, like most OAuth 2.0 do.
The bad request (400) error you may see the rfc6749 to find further information.

How to render a page following a GET request node js

I am working on express js and a particular endpoint renders the page using
res.render('dialog',{state:'admin'});
This endpoint is at http://localhost:3000/api/login. When i open this link in the browser, it opens the dialog.ejs page but when i call this endpoint using a GET request from another part of the server, the dialog.ejs page is not rendered
request({
url: 'http://localhost:3000/api/login',
headers:{
'Authorization' : auth
},
method: 'GET'
}, function(err, response, body) {
console.log("Response to request for authorization code : " + response.statusCode);
});
Please help !
Well, when you build a handmade request chances are that you're missing half of the headers the browser is sending, so that can be one of the reasons the whole thing is failing
On the other, if your making a machine to machine request, you DON'T want the ejs page renders, You only need to recover the neeeded data and /or make the server do something "as you were login in from a browser".
And as you're including the authorization Header, you're probably trying to simulate a login or authorization of some kind ( maybe a JWT Token ?)
Any case i think oyour only options is to mimic what your browser do as far as possible . So Build a perfectly correct set of headers, inject what will
be the result of form data, probably url_encoded, and use the correct request method (GET is perfectly correct, but coming from an html from POST is much more common. check it)
Just only one suggestion. Rendering a full web page from an /api/login seems a bit incorrect. Usually Api enpoints talk JSON only. In and out

Authenticate to API within Javascript

I have an API that I am able to authenticate against using the Postman client. Using Postman I am able to enter in my username and password into the header and receive back an access token.
I would like to accomplish the same authentication with a simple HTML page using Javascript. However, I am unsure how to craft the Javascript request and pass in my username and password as I did with Postman.
A password is normally considered private, if you include it in your javascript anyone can read it and fire requests off to the API as your user.
Additionally, the browsers same-origin policy - unless configured otherwise will stop you firing ajax requests to a domain other than the one the webpage was loaded from.
Instead you should create a proxy script in the server-side language of your choice hosted on your domain and fire your ajax requests off to this.
This script would do the relevant actions with the API keeping your credentials a secret and return the response.
Under the address bar of Postman there's a link that says "Generate Code" on previous versions it was a button with a </> symbol.
Clicking that link opens up a popup with a dropdownlist where Javascript is one option, this will generate the code to do the request.
Let me also add to the other answers that with jQuery you can do a get request with $.get(), and a post request with $.post(). But I would do what Vector suggests and generate the JavaScript with Postman.
You could do that with ajax call within a javascript file and you can aslo do with the xhttprequest .
example of ajax call:
$.ajax({
url : url, //URL
type : 'POST', // The HTTP Method
data : array,
contentType : 'application/json',
cache : false,
success : function (data) {
},
error : function (err) {
});
In this you can also add the Headers where u can your api access token

Ruby on Rails: Difference of Authenticity Token being in Header or POST

I've just noticed it doesn't matter where I put my Authenticity Token when submitting a request via AJAX. I can either append it to the form as POST data, or put it into the Header.
Is there any difference? Especially regarding security?
Additionally:
I didn't encode the Token in Javascript. Am I exposed to something now?
Thanks in advance.
EDIT:
form.on("sending", function(file, xhr, formData) {
xhr.setRequestHeader('X-CSRF-Token', AUTH_TOKEN);
// formData.append('authenticity_token', AUTH_TOKEN);
});
This is my Javascript adding the token to the Header or (commented out) to the POST data. AUTH_TOKEN is the raw key. I did not encode it in any way.
Part one
There is totally no difference if you pass authenticity token via GET params, POST data or request headers (POST/GET params are virtually the same in Rails).
Let's look at the code (not the best code I've ever seen but...)
def verified_request?
!protect_against_forgery? || request.get? || request.head? ||
form_authenticity_token == params[request_forgery_protection_token] ||
form_authenticity_token == request.headers['X-CSRF-Token']
end
Request if valid if (any of following)
protect_against_forgery? is false
request is GET
request is HEAD
token in params equals one stored in session
token in headers equals one stored in session
I should add that token is generated for every request and stored in session for later inspection (if subsequent request is POST/PUT/PATCH/DELETE)
So as you see both ways of passing authenticity token are valid.
Part two
Is passing raw auth token in AJAX dangerous? No, as much as passing it in a form is totally not dangerous. To explain further I will quote an excellent answer in another SO question
Why this happens: Since the authenticity token is stored in the
session, the client can not know its value. This prevents people from
submitting forms to a rails app without viewing the form within that
app itself. Imagine that you are using service A, you logged into the
service and everything is ok. Now imagine that you went to use service
B, and you saw a picture you like, and pressed on the picture to view
a larger size of it. Now, if some evil code was there at service B, it
might send a request to service A (which you are logged into), and ask
to delete your account, by sending a request to
http://serviceA.com/close_account. This is what is known as CSRF
(Cross Site Request Forgery).
original answer: https://stackoverflow.com/a/1571900/2422778
I still consider this question laziness/lack of patience on your side as all I wrote is very well explained both in Rails Guides and on Stack Overflow. Hope next time you will be more persistent in looking for answers before posting here.
Anyway I am glad I could help.
You can see the difference when you use some tool like https://www.owasp.org/index.php/Category:OWASP_WebScarab_Project or http://www.charlesproxy.com/
That are proxies, which you can turn on locally to fiddle with your HTTP requests and responses.
Very useful for web development.
Good luck.

How to add an authorization header to a DOM form element?

I am trying to upload a file to a server, and have my DOM element setup as such:
_uploadForm = document.createElement("form");
_uploadForm.method = "POST";
_uploadForm.action = "#";
if(_isBrowser.IE)
_uploadForm.encoding = "multipart/form-data";
else
_uploadForm.enctype = "multipart/form-data";
My server requires an http basic authorization header. How can I pass that through this DOM element?
Your javascript client is going to have to add headers when submitting the form.
I am not sure which javacript client lib you are using, but things like angular do allow you to set default headers or even have interceptors that can add headers before sending.
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined,
'Authorization': 'your-scheme your-token-perhaps'
},
data: { test: 'test' }
}
DOM elements have nothing to do with authorization, they're just the internal browser's representation of the various html tags. Authorization is demanded by the server - if the page is in a protected area, then the server will demand credentials, and that has nothing to do with the form itself.
The easiest way is to serve the upload form and the upload handler from the same folder, and use .htaccess to force Basic authentication for both. Then the browser automatically requests credentials when the upload form is loaded, and the credentials would be sent automatically with the upload (I believe).
However, your best bet is not to use HTTP Basic authentication at all. It sends passwords in clear text on every request unless you're using SSL, and in general, it is a hassle to use.
If you insist on using Basic, I believe it can be done with ActionScript (compiled to an SWF). I also know a way to set an Authorization header on an AJAX call, but you can't upload a file with an AJAX call, and the browser does not remember Authorization headers sent via an AJAX call.

Categories