POST request done with Authenticity Token, but exception still rased - ruby-on-rails

My controller is responding to a js GET request, and in my js.erb file I am reporting back with the Fingerprint2 generated browser data of the users browser. This is done with a POST request, because of the large data string, so I have inserted a beforeSend method that adds the Authenticity Token.
However, this is rejected with ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken. When I check, the header looks like it does in the GET requests that succeed:
X-CSRF-Token:hl/TgkY7k0yBG03KX9IBrsDhk2K4tUUh8JTooT7A0yYZ0l53p8lTt0F3dZvRwyS3bIkbbkuTdElP2KisozjXjw==
The js code looks like this:
(new Fingerprint2).get(function(fingerprint, components) {
return $.ajax({
url: "/user_browser",
type: "post",
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token',
$('meta[name="csrf-token"]').attr('content'))
},
data: {
some_id: '123',
components: JSON.stringify(components),
fingerprint: fingerprint
},
dataType: "json"
}).success(function(data) {});
});

I found the root of the problem. Some days ago I changed my config/session_store.rb from:
MyApp::Application.config.session_store :cookie_store, key: '_my-app_session'
to:
MyApp::Application.config.session_store :disabled
When I changed this back the problem disappeared.

Related

Use axios post to access mediawiki API

I have been using MediaWiki API for some time using properly formatted URLs, but i need to access a wiki with a required login.
I tried using fetch to make the request, and also axios, and the result is the same: the HTML page of the API, the same I would get if i just put the URL of the api in a browser.
My axios call is this:
axios.post('/wiki/api.php', {
logintoken: "this. Token",
action: "clientlogin",
username: "xxxxx",
password: "yyyyyy",
loginreturnurl: "http://localhost/",
format: "json"
}).then(function (response) {
console.log(response. Data);
})
It is as if the post request is simply not made. I tested using the Wikipedia api, and the result is the same.
Any help?
I believe you should add a ?format=json parameter?
Even though it is a post request
In the end it all came down to the fact that the MediaWiki API was expecting the parameters in the application/x-www-form-urlencoded format, and not application/json or text/plain ones.
When I changed that, I was able to login as expected, regardless of using axios or simply fetch.
The final code looks like this (token obtained via another API call):
const opts = {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
"logintoken": this.token,
"action": "clientlogin",
"username": "username",
"password": "password",
"loginreturnurl": "http://localhost/",
"format": "json"
})
};
const res = await fetch('/wiki/api.php', opts).

Is there a way to change the Content Type for a Postman OAuth 2 Client Credentials request?

I'm trying to use the built in tool to get an OAuth 2.0 token for my requests. This seems pretty straightforward when reading the documentation and I set it up like this:
The issue is that the request for the token is sent with a content type of application/x-www-form-urlencoded. So the response I'm getting from the server is a 415 Unsupported Media Type I do not see a way to change the request content-type to application/json.
Am I missing something or is the only way to create a custom pre-request script?
https://github.com/oauthjs/node-oauth2-server/issues/92
application/x-www-form-urlencoded , is the supported content-type for Oauth
https://www.rfc-editor.org/rfc/rfc6749#section-4.1.3
If you want to create , you can use pre-requisite script something like:
https://gist.github.com/madebysid/b57985b0649d3407a7aa9de1bd327990
// Refresh the access token and set it into environment variable
pm.sendRequest({
url: pm.collectionVariables.get("zoho_accounts_endpoint") + "/oauth/v2/token",
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: "client_id", value: pm.collectionVariables.get("zoho_client_id"), disabled: false},
{key: "client_secret", value: pm.collectionVariables.get("zoho_client_secret"), disabled: false},
{key: "refresh_token", value: pm.collectionVariables.get("zoho_refresh_token"), disabled: false},
{key: "grant_type", value: 'refresh_token', disabled: false}
]
}
}, function (err, res) {
pm.collectionVariables.set("zoho_access_token", 'Zoho-oauthtoken ' + res.json().access_token);
});
Change it to JSON or what ever you want and store the value to a variable and use that as bearer {{token}}

Ajax Request Error when application Deployed to IIS7

I've deployed my MVC project application to IIS 7, and it seems to work fine till I execute an ajax request with the following format:
$.ajax({
type: 'POST',
url: "/ControllerName/ActionMethodName",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: dataToSend,
success: function (data) {
//Do Something
}
});
Then It eliminates the application name assigned by IIS and directly access the contoller/actionMethod path from the host!
Can anyone help me solve this?
Thanks

HTML5 FormData file upload with RubyOnRails

I using this script to upload file (one by one) with HTML5 FormData in Rails 3.2.8 application.
http://jsfiddle.net/RamPr/
$('.uploader input:file').on('change', function() {
$this = $(this);
$('.alert').remove();
$.each($this[0].files, function(key, file) {
$('.files').append('<li>' + file.name + '</li>');
data = new FormData();
data.append(file.name, file);
$.ajax({
url: $('.uploader').attr('action'),
contentType: 'multipart/form-data',
type: 'POST',
dataType: 'json',
data: data,
processData: false
});
});
});
But when I upload a file, I get this error in console:
webrick/server.rb:191:in `block in start_thread' ERROR ArgumentError: invalid %-encoding ("filename.jpeg" Content-Type: image/jpeg
How can I solve this error?
Have you seen this issue? Sending multipart/formdata with jQuery.ajax
It looks like you might be running into jQuery adding content-type headers, which causes the boundary string to be missing. From the above linked issue:
It’s imperative that you set the contentType option to false, forcing jQuery not to add a Content-Type header for you, otherwise, the boundary string will be missing from it. Also, you must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Based on that, give this a try:
$.ajax({
url: $('.uploader').attr('action'),
contentType: false,
cache: false,
processData: false,
type: 'POST',
dataType: 'json',
data: data
});
I haven't tried this myself, but I suspect this might be the droids you're looking for :)

Asp.net MVC Controller Action string parameter doesn't get passed

In my controller I have
public JsonResult GetInfo(string id)
in my js
$.ajax({
contentType: 'application/json, charset=utf-8',
type: "POST",
url: "/Incidents/GetInfo",
data: { id: "777" },
cache: false,
dataType: "json",
success: function (response) {
//etc....
jquery ajax error delegate gets executed. If I use
data: { "777" },
no error, but the value doesn't get passed. This should be easy but I am beating my head against the wall. Maybe I am not allowed to pass strings to controller's actions?
What am I doing wrong here?
You are indicating application/json request and you are sending a application/x-www-form-urlencoded request. So you will have to choose between one of the two ways to encode parameters and not mix them.
application/x-www-form-urlencoded:
$.ajax({
type: "POST",
url: "/Incidents/GetInfo",
data: { id: "777" },
cache: false,
dataType: "json",
...
});
application/json:
$.ajax({
type: "POST",
url: "/Incidents/GetInfo",
contentType: 'application/json, charset=utf-8',
data: JSON.stringify({ id: "777" }),
cache: false,
dataType: "json",
...
});
The JSON.stringify method is natively built into modern browsers and is used to convert the javascript literal into a JSON string which is what we indicated that we are going to send the request as. If you are having to support legacy browsers you could include the json2.js script to your page which contains this method.
As a side note the dataType: "json" setting is not needed since the server will set the proper Content-Type header to application/json and jQuery is smart enough to use that.
And as a second side note you really don't want to be hardcoding an url like this in your javascript file: url: "/Incidents/GetInfo". What you want is to use url helpers when generating urls: url: "#Url.Action("GetInfo", "Incidents")".
Are you missing HttpPost attribute in your action? If not, use something like firebug or chrome dev tools to see http request/response and get more details...
[HttpPost]
public JsonResult GetInfo(string id)

Resources