Vue.js+Firebase: 401 error, 'unauthorized' - firebase

When I try to use post method in my Vue project:
this.$http.post("https://vuejs-blog-b91df.firebaseio.com/posts.json", this.blog).then(function(data) {
console.log(data);
this.submitted = true;}
the console throws me an error:
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Uncaught (in promise)
Response
body: {error: "Permission denied"}
bodyText: "{↵ "error" : "Permission denied"↵}↵"
headers: Headers {map: {…}}
ok: false
status: 401
statusText: "Unauthorized"
url: "https://project-name.firebaseio.com/posts.json"
data: (...)
__proto__: Object
Where and how should I put firebase project apiKey and other authorization data to succeed?

Authentication with access_token
Based on firbase authentication documentation, I think you must change your request URL to smth like this:
const token = 'token'; // get token somewhere
this.$http
.post(`https://vuejs-blog-b91df.firebaseio.com/posts.json?access_token=${token}`, this.blog)
.then((data) => {
console.log(data);
this.submitted = true;
});
Authentication with ID token
Or you may use ID token authentication like this:
const token = 'token'; // get token somewhere
this.$http
.post(`https://vuejs-blog-b91df.firebaseio.com/posts.json?auth=${token}`, this.blog)
.then((data) => {
console.log(data);
this.submitted = true;
});
Here you can find how to get ID token on client

Related

Error while making request: incorrect header check. Error code: Z_DATA_ERROR

i am really struggling with firebase-admin on vue.
I am getting Error: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: incorrect header check. Error code: Z_DATA_ERROR".
`const apps = getApps();
if (!apps.length) {
initializeApp({
credential: cert(serviceAccount)
});
}
await getMessaging().sendToTopic("test", {
notification: {
title: "Test",
body: "Test"
}
});`
what am I missing..

how to send HTTP request with APIKEY

I have an API Gateway created to trigger my lambda function. I am trying to secure the invoke URL. I understand that we can use the Lambda Authorizer or the APIKEY. I am trying to use the API key but not sure how to pass the API key using fetch.
I have also linked the API to the API Keys and the usage Plans.
I am trying to access the URL from the client-side.
invokeurl is referring to my Invoke URL which will return the JSON object.
egkeyname is my key value which I am not able to share.
Client.py:
onMount(async () => {
const res = await fetch('invokeurl',{
method:'get',
headers: new Headers ({
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods':'OPTIONS,POST,GET',
'X-API-KEY' :'egkeyname'
})
}); //wait until the promise return result
data = await res.json();
});
But I get an error:
Access to fetch at '..invoke ur...' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
Uncaught (in promise) TypeError: Failed to fetch
GET https:invokeurl net::ERR_FAILED
My lambda function:
responseObject = {}
responseObject['statusCode'] = 200
responseObject['headers']={}
responseObject['headers']['Content-Type'] = 'application/json'
responseObject['headers']['Access-Control-Allow-Origin'] = '*'
responseObject['headers']['Access-Control-Allow-Methods'] = 'OPTIONS,POST,GET'
return responseObject
How do I access the URL with the APIkey?
Solved it on my own. I was using the wrong information in the Header.
It should be:
onMount(async () => {
const res = await fetch('invokeurl',{
method:'get',
headers: new Headers ({
'Access-Control-Request-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
'Origin' : '*',
'Access-Control-Request-Method':'OPTIONS,POST,GET',
'X-API-KEY' :'egkeyname'
})
}); //wait until the promise return result
data = await res.json();
});

Getting Request had invalid authentication credentials error FCM

Am trying to test my web push notification from postman
my app id is thepostman-2018 so I am sending post requests to the url
https://fcm.googleapis.com/v1/projects/thepostman-2018/messages:send
event though I have set Authentication header and passed my Server key
i am getting this response
{
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
FCM v1 requests do not use the API key from the Firebase console to authorize requests. Instead, they use credentials retrieved by authenticating using the Service Account Key downloaded from the Firebase console. For example, this is how you generate the token using Node.js:
function getAccessToken() {
return new Promise(function(resolve, reject) {
var key = require('./service-account.json');
var jwtClient = new google.auth.JWT(
key.client_email,
null,
key.private_key,
SCOPES,
null
);
jwtClient.authorize(function(err, tokens) {
if (err) {
reject(err);
return;
}
resolve(tokens.access_token);
});
});
}
See the guide for more details.

Why is this core package being called?

I am trying to authenticate with Google through OAuth, and this is my server code
my.fetchTokens = function(code) {
var endpoint = 'https://accounts.google.com/o/oauth2/token';
var params = {
code: code,
client_id: Meteor.settings.google.CLIENT_ID,
client_secret: Meteor.settings.google.CLIENT_SECRET,
redirect_uri: Meteor.settings.google.REDIRECT_URL,
grant_type: 'authorization_code',
};
try {
response = HTTP.post(endpoint, { params: params });
} catch (err) {
throw _.extend(new Error("Failed to complete OAuth handshake with Google. " + err.message),
{response: err.response});
}
if (response.data.error) { // if the http response was a json object with an error attribute
throw new Error("Failed to complete OAuth handshake with Google. " + response.data);
}
var tokens = {
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token,
expiresIn: response.data.expires_in,
idToken: response.data.id_token
};
console.log(tokens);
return tokens;
};
But when I invoke this method, I get the following warnings
W20150316-10:30:05.853(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150316-10:30:05.854(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150316-10:30:05.855(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150316-10:30:05.855(1) (oauth_server.js:398) Error in OAuth Server: Match error: Expected string, got undefined
But I dont get why oauth_server.js:71 is being referenced
any ideas?
Probably because you're calling OAuth.openSecret or OAuth._redirectUri('google', config).
I assume one of these calls parses the current URL.

invalid_grant Google OAuth

I am trying to authentiate through Google's OAuth, but I'm having problems establishing a connection to their API
My client code:
'click #addChannel': function (event) {
event.preventDefault();
var userId = Meteor.userId();
var options = {
requestPermissions: [
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/youtube.upload',
'https://www.googleapis.com/auth/youtubepartner',
'https://www.googleapis.com/auth/youtubepartner-channel-audit',
],
requestOfflineToken: true
};
Google.requestCredential(options, function(token) {
Meteor.call('userAddOauthCredentials', userId, token, function(error, result) {
if (error) {
throw error;
}
console.log(result);
});
});
My server code:
userAddOauthCredentials: function(userId, token) {
check(userId, String);
check(token, String);
var config = ServiceConfiguration.configurations.findOne({service: 'google'});
if (!config) {
throw new ServiceConfiguration.ConfigError();
}
console.log(token, config);
var endpoint = 'https://accounts.google.com/o/oauth2/token';
var params = {
code: token,
client_id: config.clientId,
client_secret: OAuth.openSecret(config.secret),
redirect_uri: OAuth._redirectUri('google', config),
grant_type: 'authorization_code',
};
try { <------------------------------------------------------ this fails
response = HTTP.post(endpoint, { params: params });
} catch (err) {
throw _.extend(new Error("(first) Failed to complete OAuth handshake with Google. " + err.message),
{response: err.response});
}
if (response.data.error) { // if the http response was a json object with an error attribute
throw new Error("(second) Failed to complete OAuth handshake with Google. " + response.data);
} else {
return {
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token,
expiresIn: response.data.expires_in,
idToken: response.data.id_token
};
}
The above throws a [400] { "error" : "invalid_grant" } error.
Most of the above code I got from how the meteor accounts-google packages logs in a user (which works fine in my application). Link to that:
https://github.com/meteor/meteor/blob/87e3c6499d5eacce62f10faefe9ce49c77bb03ee/packages/google/google_server.js
Any advice on how to proceed from here?
Much appreciated
UPDATE1:
I get these warnings in my log
W20150318-09:11:42.532(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150318-09:11:42.532(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150318-09:11:42.533(1) (oauth_server.js:71) Unable to base64 decode state from OAuth query: undefined
W20150318-09:11:42.534(1) (oauth_server.js:398) Error in OAuth Server: Match error: Expected string, got undefined
You have to parse your var params to application/x-www-form-urlencoded. Please find the below code to parse as i done in php
$fields_string="";
foreach($params as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
Now the $filed_string will contained the parse of params array.

Resources