Laravel 8 api how to send token via Authorization - javascript

I am using Laravel 8 as a APIrest and I am trying to send my token in the ajax petition but in laravel I get null, I cannot see why. I do not have problems with log in or petitions without token.
In JavaScript I have an AJAX petition like this: (Before sending token is not null, I save it in localStorage)
var settings = {
"url": apiUrl+"bookings/"+userIdentified.id,
"method": "GET",
"timeout": 0,
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": token
},
};
$.ajax(settings).done((response) => {
console.log(response);
});
In Laravel, I have a middleware with the following:
// Check user identified
$token = $request->header('Authorization');
$jwtAuth = new \JwtAuth();
$checkToken = $jwtAuth->checkToken($token);
// If it is continue
if ($checkToken) return $next($request);
// If it is not then return an error
$data = array(
'status' => 'error',
'code' => '400',
'message' => $token, // I tested that and it return null
'test' => $request->all()
);
return response()->json($data, $data['code']);
The route:
Route::get('/bookings/{id}', [BookingController::class, 'getBookingsByUser'])->middleware('auth');
And this is the response:
{
code: "400",
status: "error",
message: null, // that have to be the token for testing that exists and is not null
test: []
}
In web console:
GET https://my-url/api/bookings/4 400 (Bad Request)
In laravel, I commented VerifyCsrfToken in kernel.php to not have problems with it.
I have the api in a subdomain but I do not have problem doing register and log in, that works without token. For some reason the token is not arriving to my api :(
There is something that I am missing?

You are missing bearer which specifies the token type.
Change:
"Authorization": token
To:
"Authorization": "bearer token"
Also, if you are making an API request add this header:
"accept": "application/json"

Related

Next Auth authentication in production

I finished developing my application with Next.js.
I used Next Auth to handle user authentication.
I use the Credential Provider for authentication with email and password.
In development everything works fine when I log in the session is well created and a JWT token is well generated.
On the other hand when putting in production it does not work, I have the following error:
[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error invalid json response body at https://my-site.fr/api/auth/csrf reason: Unexpected token < in JSON at position 0 {
I really don't understand why the error only appears in production.
Here is the code of my Credential Provider
CredentialProvider({
async authorize(credentials, req) {
// console.log(credentials);
const url = `${process.env.NEXT_PUBLIC_API}/auth/login`;
const res = await fetch(url, {
method: "POST",
body: JSON.stringify(credentials),
headers: {
"Content-Type": "application/json",
Accept: "application/json, text/plain, */*'",
"User-Agent": "*",
},
});
// console.log(res);
const user = await res.json(res);
if (res.ok && user) {
return user;
}
return null;
},
}),
Thanks for your help.

Can anyone suggest how to handle the error which i was facing when using to call an Post and get Http methods through protractor?

I am Trying to execute a GET API request from protractor for which I have to Use the bearer token generated from another POST response . I am able to run the POST request successfully ,but unable to use the generated token in GET request in headers . Below is the code-snippet which I tried , Can anyone provide the proper syntax on this approach .
Note : URL and credentials are masked as they are confidential
var Request = require("request");
describe('post user request', () => {
it('create user test', (done) => {
//1. create user (POST)
Request.post({
// method: 'POST',
"url": "http://example.com",
"body" : {
"username": "abc",
"password": "abc1",
}
   
}).then((res)=>{
console.log(JSON.stringify(res))
}).then((res) =>{
const token1 = res.token
//2. get user (GET)
Request.get({
// method: 'GET',
"url": "http://example.com`[enter code here][1]`/xyz",
"headers": {
"Authorization" : "Bearer " + token1
}
}).then((res)=>{
console.log(res)
done();
})
})
  })
})
Error message :
F
post user request
× create user test
- Failed: Argument error, options.body.
Failures:
1) post user request create user test
Message:
Failed: Argument error, options.body.
Stack:
Error: Argument error, options.body.
at setContentLength (D:\Protractor\node_modules\request\request.js:437:28)
at Request.init (D:\Protractor\node_modules\request\request.js:442:5)
at new Request (D:\Protractor\node_modules\request\request.js:127:8)
at request (D:\Protractor\node_modules\request\index.js:53:10)
at Function.post (D:\Protractor\node_modules\request\index.js:61:12)
at UserContext.<anonymous> (D:\Protractor\Specs_Map\APIfile.spec.js:8:21)
at D:\Protractor\node_modules\jasminewd2\index.j
}).then((res)=>{ console.log(JSON.stringify(res)) this is where your error comes from.
Here you log the result, but don't return it, so the following then won't get any value.
Try the following:
}).then((res)=>{ console.log(JSON.stringify(res)); return res;

VM101:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I am using Sandbox for payment testing. Everything works fine till payment and the console throws an error:
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
The error points to:
fetch(url, {
. I am not sure what's wrong with the Django app. I even have initialized URL at the top:
var url = "{% url 'payments' %}"
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
console.log(details);
sendData();
function sendData(){
fetch(url, {
method : "POST",
headers: {
"Content-type": "application/json",
"X-CSRFToken": csrftoken,
},
body: JSON.stringify({
orderID: orderID,
transID: details.id,
payment_method: payment_method,
status: details.status,
}),
})
.then((response) => response.json())
.then((data) => {
window.location.href = redirect_url + '?order_number='+data.order_number+'&payment_id='+data.transID;
})
}
});
}
Either there is an internal server error, or you the server is not sending a Json response. You can check the status by using .then((response)=>console.log(response.status) to check if there is an internal server error, if the console.log shows 500 error code, then it is server error. else the server is not sending proper json response.
You are probably not returning json from the server, try doing res.text() instead of res.json(), and see if that fixes it, if it does, you are not returning proper json from your server.

axios delete method gives 403

I am calling delete method from my node-js application.
Its working fine from Postman but giving me 403 while calling this API
from code.
Below is my sample code snippet:
const instance = axios.create();
instance.interceptors.request.use((config) => {
config.baseURL = 'https://test-dev.com/api/portfolio'
config.headers = { 'Authorization' : 'Bearer ' + <TOKEN>}
return config;
});
instance.delete('/admin?users=<VALUE>').then(function(response) {
console.log("Deleted: "+<VALUE>);
}).catch(function (error) {
console.log("Deletion failed with error:" + error);
});
EDIT:
Response (Coming from spring security APP):
Could not verify the provided CSRF token because your session was not found
I thought this is already handled by axios.
How can i pass this value in headers while calling delete method?
Any help?
You could either:
1 - Use the withCredentials property:
withCredentials: true
so:
axios.delete({
url: 'https://test-dev.com/api/portfolio/admin?users=' + <VALUE>,
headers: { 'Authorization' : 'Bearer ' + <TOKEN>},
withCredentials: true
}).then(function(response) {
console.log("Deleted: "+<VALUE>);
}).catch(function (error) {
console.log("Deletion failed with error:" + error);
});
The XMLHttpRequest.withCredentials property is a Boolean that
indicates whether or not cross-site Access-Control requests should be
made using credentials such as cookies, authorization headers or TLS
client certificates. Setting withCredentials has no effect on
same-site requests.
2 - Set CSRF headers
Either:
headers: {'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content')}
or
headers: {'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': 'your token here'}
or just:
headers: {'X-Requested-With': 'XMLHttpRequest'}
3 - Disable at own risk and if possible
Have a look at this article
So after a number of tries, I found it working.
Please follow the order sequence it's very important else it won't work
axios.delete(
URL,
{headers: {
Authorization: authorizationToken
},
data:{
source:source
}}
);

You are not authorized for this operation. Invalid access token DialogFlow v2

I am trying to use DialogFlow v2 endpoint but for some reason I am getting not authorized message, eventhou I am able to generate access token using the following command:
Initially I am running this to authorize the service for my local machine to be able to authorize to the service: gcloud auth activate-service-account --key-file=<service-account-key-file.json> then I get access token by following command: gcloud auth print-access-token and this access token I am attaching on the following code:
fetch(configs.baseUrl + "query?v=20150910", {
body: JSON.stringify({query: text, lang: "en", sessionId: "somerandomthing"}),
headers: {
'content-type': 'application/json',
"Authorization": "Bearer " + accessToken,
},
method: 'POST',
})
.then(response => response.json())
.then(data => {
console.log(data.result.fulfillment.speech);
return data.result.fulfillment.speech;
})
.catch(error => console.error(error))
I dont know if this is the right way to achieve a communication with DialogFlow V2?
Please if you could let me know what I am doing wrong and why I it says I am not authorised since I am authorizing by the above commands and been able to get access token!
Edit:
After few changes my code finally looks like this:
fetch("https://dialogflow.googleapis.com/v2beta1/projects/xxx/agent/sessions/xxx/:detectIntent", {
body: JSON.stringify({queryInput: "Hello"}),
headers: {
'content-type': 'application/json',
"Authorization": "Bearer xxxx",
},
method: 'POST',
})
.then(response => response.json())
.then(data => {
console.log(data.result.fulfillment.speech);
return data.result.fulfillment.speech;
})
.catch(error => console.error(error))
and the new error message I get is:
{
"error": {
"code": 400,
"message": "Invalid value at 'query_input' (type.googleapis.com/google.cloud.dialogflow.v2beta1.QueryInput), \"Hello\"",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "query_input",
"description": "Invalid value at 'query_input' (type.googleapis.com/google.cloud.dialogflow.v2beta1.QueryInput), \"Saanko yhteystiedot?\""
}
]
}
]
}
}
You don't show the baseUrl you're using, but that looks like the V1 API rather than the V2 API. You should migrate your code to V2.
Keep in mind, also, that the access token expires, so you will need to generate a new one periodically. You cannot request a "long lived" token (this is considered insecure), but should have your code call gcloud auth print-access-token (or use a library to do the same thing) before the previous one expires.
Update based on your code once you've moved it to V2:
The queryInput parameter doesn't take a string directly. It must be set to a QueryInput object. This is an enum, so can only have one of the fields specified set. It looks like you want the text field which requires a TextInput object.
So your body parameter might be setup something like this:
var body = {
queryInput: {
text: {
text: "Hello",
language: "en-US"
}
}
};
var bodyStr = JSON.stringify(body);
and then set in your request() options.
Because you have put wrong URL in your project.
Open below image and see which URL use for posturl in your project
https://i.stack.imgur.com/3ym9n.png

Categories