Unauthorized response with valid token - laravel

I get unauthorized as response on every request after login successfully
this is some of my code (let me know if you need to see anything else):
Data provider on ionic
this.storageProvider.getToken().then(results => {
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + results,
'Accept': 'application/json',
})
};
});
public getTodayReservations() {
//all reservations (not todays only)
let _url = this.url + '/guides/reservations/all';
return this.http.get(_url, this.httpOptions);
}
an this the config of my laravel api routes:
Route::prefix('v1')
->group(function () {
Route::post('login', 'Api\UsersController#login');
Route::middleware('auth:api')
->prefix('guides')
->group(function () {
Route::get('/show', 'Api\UsersController#show');
Route::get('/reservations/today', 'Api\ReservationsController#today');
Route::get('/reservations/all', 'Api\ReservationsController#allRes');
});
});
Request Headers:
Accept: application/json
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI.....
Content-Type: application/json
Origin: http://localhost:8100
Referer: http://localhost:8100/

As you can this.storageProvider.getToken() return a promise and not a token.
try something like this :
export class HttpService {
private httpOptions;
constructor(){
this.storageProvider.getToken().then(results => {
this.httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + results,
'Accept': 'application/json',
})
};
});
}

Check response of this.storageProvider.getToken(), usually it has access_token key which you are supposed to use in order to authroize your app so your code, not the full promise so your code will be like:
this.storageProvider.getToken().then(tokenObject => {
private httpOptions = {
headers: new HttpHeaders(
{
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + tokenObject.access_token,
'Accept': 'application/json',
}
)
};
});
Of course, in your case, it might be some other key, that is why you should have a look at this.storageProvider.getToken() first and only send the actual access token when sending Authorization header.

Related

How work https api in React-native-android? [duplicate]

This question already has answers here:
React-native POST request in android over https return network error
(3 answers)
Closed 2 years ago.
in reactnavtive app we work with 'http' for url in axios and evry things is ok , now we change 'http' to 'https' but Apis failed ... and app don't work ... why ? please help me.
This call will work for both HTTP and HTTPS
Try this example for POST CALL
fetch('http://mywebsite.com/endpoint/', {
method: "POST",
headers: {
// Authorization: "Bearer " + Token,
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
// sending data userID username, password, etc
}),
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});
Try this example for GET CALL
fetch('http://mywebsite.com/endpoint/', {
method: "GET",
headers: {
// Authorization: "Bearer " + Token,
// OR USER name PASSworrd
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});
i found answer this question , my url was : 'https://185.305.1.13/index.image.png' , we add domin for images , and url chaghed :'https://image.com/index.image.png'... and revso

Google Drive API v3 & Google Picker: Change the download permission of file

I've used Google Picker API to retrieve My Drive videos URLs and publish them in my app. So I want to change their sharing permission (as public) and disabled the download button with the copyRequiresWriterPermission option.
This is my code for change the permissions in the Picker callback function;
function pickerCallback(data, e) {
if (data.action == google.picker.Action.PICKED) {
var docs = data[google.picker.Response.DOCUMENTS];
var type = "anyone";
var role = "reader";
var urls = new Array();
for (var d = 0; d < docs.length; d++) {
var request1 = gapi.client.request({
'path': '/drive/v3/files/' + docs[d].id + '/permissions',
'method': 'POST',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + oauthToken
},
'body':{
'role': role,
'type': type
}
});
request1.execute(function(resp) {
console.log(resp);
});
urls.push(docs[d].url);
}
elements.push({name: 'url', value: urls});
// continue with an ajax funtion ...
}
};
That works fine, so I decided add a new request for change the donwload restriction:
var request2 = gapi.client.request({
'path': '/drive/v3/files/' + docs[d].id,
'method': 'POST',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + oauthToken
},
'body':{
'copyRequiresWriterPermission': true
}
});
request2.execute(function(resp) {
console.log(resp);
});
But only I obtained a 404 status. Also, I've tried with:
'/upload/drive/v3/files/' + docs[d].id
But the same problem.
I've tried the request with the File Id in the Drive API Demo and works. What is the error in the request2 code?
Scopes used:
var scope = [
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.metadata",
"https://www.googleapis.com/auth/drive.readonly",
];
Updated code:
var request2 = gapi.client.request({
'path': '/drive/v3/files/' + docs[d].id ,
'method': 'PATCH',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + oauthToken
},
'body':{copyRequiresWriterPermission: true}
});
request2.execute(function(resp) {
console.log(resp);
});
This code execute without problems, but nothing happens because I need to uncheck this parameter:
Is it possible?
If you want to update a File in drive, the request method should be PATCH not POST.
Example:
var request2 = gapi.client.request({
'path': '/drive/v3/files/' + docs[d].id,
'method': 'PATCH',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + oauthToken
},
'body': {
copyRequiresWriterPermission: true
}
});
request2.execute(function(resp) {
console.log(resp);
});
References:
Drive API Files: update

Authorization failed on a fetch request to the Brawl Stars API

I'm trying to send a get request with fetch API to ask the brawl stars API server. I've created an API KEY associated with my IP address. I've tried everything, but I got a 403 response from the server.
Here is my code :
const url = 'https://api.brawlstars.com/v1/players/...';
const token = '...';
const headers = new Headers({
'Accept': 'application/json',
'Authorization': 'Bearer ' + token
});
const options = {
method: 'GET',
headers: headers,
mode: 'cors',
cache: 'default'
};
fetch(url, options)
.then(response => response.json())
.then(console.log)
.catch(console.error);
In the console there is the message : No 'Access-Control-Allow-Origin' header is present on the requested resource because of cors policy.
When I test the request on Insomnia, it works well !
I had a problem with the Brawlstars API a little while back when I was making a Brawlstars command for my Discord bot. I was able to get the API to work however with the following code.
const playerurl = 'https://api.brawlstars.com/v1/players/';
const getJSON = async url => {
try {
const response = await fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'Bearer <yourapitoken>',
},
});
if(!response.ok) {throw new Error(response.statusText);}
const data = await response.json();
return data;
}
catch(error) {
return error;
}
};
getJSON(playerurl).then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});
I hope this works for you!

nativescript global http header

Is there a way to set global header to http module with Nativescript ?
Instead doing this :
const http = require('http')
return http.request({
url : ...,
method: 'GET',
headers: {
'Authorization' : 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',
'Content-Type': 'application/json'
}
});
I would like to have something like this:
const http = require('http')
http.headers = {
'Authorization' : 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',
'Content-Type': 'application/json'
}
return http.request({
url : ...,
method: 'GET'
});
I use a global function for common http headers like
function getCommonHeaders() {
return {
"Content-Type": "application/json",
"Authorization": "Bearer " + config.token
}
}
And then use them in all HTTP requests
const http = require('http');
return http.request({
url : ...,
method: 'GET',
headers: getCommonHeaders()
});
You may also want to consider storing your key/token in a configuration setting or in application-settings.

Issue in AJAX request in reactjs

I am trying to develop an application using reactjs as front end framework and laravel 5.6 as back end framework. I am trying to send AJAX request like below
import Auth from '../services/Auth';
var address_data = {
name :'foysal',
address :'foysal',
telephone_no:'foysal',
email :'foysal',
}
fetch('http://127.0.0.1:8000/api/addresses/store/',address_data, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + Auth.getToken(),
},
body: JSON.stringify()
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
})
I am getting below errors
Try changing your fetch request to initiate POST action verb like this
fetch('http://127.0.0.1:8000/api/addresses/store/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + Auth.getToken(),
},
body: JSON.stringify(address_data)
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));

Resources