401 Unauthorized when calling .ajax method in rails 3 application - ruby

I'm passing a ajax call to update data in my application through twitter bootstrap modal window. The ajax code is given below:
$(document).ready(function(){
var link=$('#link_hash').val();
$("#update_link").click(function(){
console.log("I'm here");
$.ajax({
url: "profiles/update_link",
type: "POST",
dataType: "html",
data: {link: link,data: $('#link_hash').val() },
success: function(data) {
// some code
},
error: function(data1) {
// some code
}
});
});
});
I have modifies route.rb file to match it to my controllers "update_link" method.
The code in my method is given below:-
def update_link
#link=Link.find_by_link(params[:link])
#tlink=Link.find_by_link(params[:data])
logger.info "=========kkkkkkkkkkkkkk=================================#{#link.inspect}"
logger.info "=========kkkkkkkkkkkkkk=================================#{#tlink.inspect}"
logger.info "=========kkkkkkkkkkkkkk=================================#{params.inspect}"
respond_to do |format|
if #tlink.nil?
#link.update_attributes(:link => params[:data])
...some code....
else
...some code...
end
end
end
end
So in the server log it's showing -
Started POST "/profiles/update_link" for 127.0.0.1 at 2013-02-20 12:08:20 +0530
Processing by ProfilesController#update_link as HTML
Parameters: {"link"=>"9bfzjp", "data"=>"9bfzjpaaa"}
WARNING: Can't verify CSRF token authenticity
Completed 401 Unauthorized in 6ms
So clearly "logger.info" is not showing up...Now after searching I was able to solve the WARNING but still 401 is present...How to solve this??
Thanks in advance....

According to your server log, you are not passing CSRF token, so rails automatically considers request to be malicious and flags it as unverified. default handling of unverified requests is to reset session. Can you comment out protect_from_forgery or add skip_before_filter :verify_authenticity_token to your controller to see if it the case?
If you want to include authenticity token in your ajax request (highly recommended) you can add it to headers in your ajax request:
headers: {
'X-Transaction': 'POST Example',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}

Add skip_before_filter :authenticate_user! to your controller.

Related

Ajax PATCH/PUT problem 401 (Unauthorized)

I wrote an API using django and djano-ninja.
Here is my section of api.py file which is imported to URL.
class ORJSONRenderer(BaseRenderer):
media_type = "application/json"
def render(self, request, data, *, response_status):
return orjson.dumps(data)
class ApiKey(APIKeyQuery):
param_name = "api_key"
def authenticate(self, request, key):
try:
return CustomUser.objects.get(api_key=key)
except CustomUser.DoesNotExist:
pass
api_key = ApiKey()
api = NinjaAPI(
title="Good TExt",
version="0.0.1",
description="That This",
renderer=ORJSONRenderer(),
# csrf=True
)
#api.patch(
"/car/color/{new_color}", auth=api_key, tags=["Car"], summary="Does something",
description="Does something"
)
def update_team_name(request, new_color):
try:
#Do something
msg = {"success": "Done"}
except:
msg = {"error": "Problem"}
return HttpResponse(json.dumps(msg), content_type='application/json')
I have other get endpoints too. There is no problem when I request get endpoints.
But when I send a request to patch endpoints I am getting 401 (Unauthorized) only with ajax. I mean python's requests work.
import requests
load = dict(
api_key='SOME HEY'
)
r = requests.get("http://127.0.0.1:8000/api/car/color/red", params=load)
print(r.text)
But javascript doesn't:
$.ajax({
url: "/api/car/color/red",
data: {
"api_key": "some key"
},
cache: false,
type: "PATCH",
success: function(response_country) {
console.log(response_country);
},
error: function(xhr) {
console.log(xhr);
}
});
What I did try
I tried to add:
headers:{"X-CSRFToken": $crf_token},
to header of the ajax request. Even though csrf is set to False in django-ninja
I tried to change from PATCH to PUT
I tried to add a timeout to ajax request
I tried to send the api_key trough header and not the data
with no success.

Post request to selling partner API sandbox endpoint return InvalidSignature

I'm currently trying to create a document and upload it to the SP-API sandbox environment using ruby and HTTP.rb gem. My steps are:
Request the LWA access token by a refresh token
Assume the role and request the STS token
Sign the request header using AWS::SignV4 SDK
Send the POST request to the endpoint /feeds/2020-09-04/documents with body json: { 'contentType' => 'text/tab-separated-values; charset=UTF-8' }
However, SP-API keeps returning "code": "InvalidSignature" to me. But all my other 'GET' requests like get_orders, get_order_items are working correctly.
Here is how I send my request:
#url = '/feeds/2020-09-04/documents'
#body = if sandbox
{ 'contentType' => 'text/tab-separated-values; charset=UTF-8' }
else
{ 'contentType' => 'text/xml; charset=UTF-8' }
end
#request_type = 'POST'
response = http.headers(headers).send(#request_type.downcase.to_sym, request_url, json: #body)
I checked the AWS::Signer::V4 document, turns out I should pass the body into the signer as well.
signer.sign_request(http_method: #request_type, url: request_url, body: #body)
I published the amz_sp_api rubygem that does this, but I would welcome a contribution of the ruby code for encrypting the feed submissions as required by SP-API: https://github.com/ericcj/amz_sp_api/issues/1

POST request doesn't get response from server in chrome but work in postman

I'am making a POST request to spring boot endpoint and wanna get data return from server.With testing my API in Postman,it works good.but when testing it in
chrome,it doesn't even get a response and chrome NETWORK bar even did't have record.
so code is simple,I can't find any problem,RestController
#PostMapping("/signup")
public User signup(#RequestBody ModelUser user){
//fetch data from DTO and craft a user
User userData=user.adapter();
//...code here omit for sake of brevity
return userData;
}
it indeed get data from ajax,when I use logger(slf4j) to debug.
and ajax:
$("#sign-up").submit(function () {
var userInfo={}
userInfo["phone"]=$("#phone").val()
userInfo["password"]=$("#password").val()
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
}).then(
function(){
//this doesn't print in console
console.log("Hello Callback is executed")
}
)
})
weird as it is,I never encounter this when I use GET request,since ajax callback is successfully called when I use GET to test a GetMapping endpoint.
oh,with lots of similar questions
AJAX POST request working in POSTMAN but not in Chrome
Angular 4 POST call to php API fails, but GET request work and POST requests work from Postman
POST response arrives in Postman, but not via Ajax?
I don't get any response status code in chrome and completely not involved CORS in question
Have you tried adding a consumes and produces media type of Json in the Java
#PostMapping(path="/signup", consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
And explicitly set the Accept header in the javascript
$.ajax({
//ajax successful send to spring boot endpoint
type:"POST",
headers: {Accept : "application/json"},
contentType:"application/json",
url:"http://localhost:8080/signup",
data:JSON.stringify(userInfo)
})
I'am sorry for my poor front end skill,the main reason is that I don't understand Javascript event.
$("#sign-up").submit(function (e) {
//e.preventDefault();
var user={};
user["phone"]="187308";
user["name"]="icywater";
$.ajax({
type:'POST',
contentType:'application/json',
data:JSON.stringify(user),
url:"http://localhost:8080/test"
}).done(function(data){
console.log("Hello Callback is executed");
console.log(data)
});
});
here when I click submit It actually already submit the form and don't wait ajax code to be executed,so I should use e.preventDefault()to suppress default behavior.It's nothing
related about POST or postman ,it is about the form submit default behavior,ahh,Oolong event.
I got it when I found this page

Ember acceptance test not working with AJAX

I'm starting to add acceptance tests to my Ember project. Starting off with one which tries to log-in to my app:
import { test } from 'ember-qunit';
import moduleForAcceptance from '../helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | login');
test('logging in', function(assert){
visit('/login');
andThen(function(){
assert.equal(currentURL(), '/login');
});
fillIn('#login input[name=email]', 'my#email.com');
fillIn('#login input[name=password]', 'password');
click('#login button[type=submit]');
andThen(function(){
assert.equal(currentURL(), '/dashboard');
});
});
But it fails because the AJAX call to my REST API for authentication fails. This works fine when the app is running normally, but not when done through an acceptance test.
I've traced it back to the following error being returned by ember-ajax:
Ember AJAX Request POST https://127.0.0.1:8081/login returned a 0\nPayload (Empty Content-Type)\n""
My API isn't even getting the call, so this seems to be an error with sending the REST request. I've checked the hash object in node_modules/ember-ajax/addon/mixins/ajax-request.js just before it's sent through to the jQuery AJAX method:
{ type: 'POST',
data: { email: 'my#email.com', password: 'password' },
url: 'https://127.0.0.1:8081/login',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
headers: { Authorization: 'Bearer undefined; PublicKey Ab732Jte883Jiubgd84376HhhndikT6' } }
contentType is defined. This is also exactly how hash looks when making the same AJAX call with the app running normally.
So what is there about Ember acceptance tests which would specifically prevent AJAX calls from working? I suspect there's a config or environment property I'm unaware of that I need to change/set to get it working.
I'm running:
ember-cli: 2.8.0
node: 4.5.0
ember-ajax: 2.5.1
ember-cli-qunit: 3.0.1
phantomjs: 2.1.7
What an eejit! My local REST API has an invalid SSL certificate. So I just needed to tell PhantomJS to ignore SSL errors in my testem.js file:
"phantomjs_args": [
"--ignore-ssl-errors=true"
],

dojo ---> django POST

I'm trying to send a json from the client using the method xhrPost dojo. But I'm getting a 403 errors. Any help?
var str_json = dojo.toJson(arr_markers);
console.log('json elements: '+str_json);
dojo.xhrPost({postData: str_json,
headers: { "Content-Type": "application/json"},
//content:{'prueba': 'HOLA'},
url:'/up_position_elements/',
handleAs: 'text',
load: function(response, ioArgs){alert('response');},
error: function(errorMessage){}
});
And how to read the json in the django view?
Which method should I use?
403 means "forbidden" which means that the view wants a password, cookie, or other form of authentication. Could you show us the view that serves /up_position_elements/ so that we can see what security-related decorators or logic it might contain?

Resources