What Bearer token should I be using for Firebase Cloud Messaging testing? - firebase-cloud-messaging

I am trying to send a test notification using Firebase Cloud Messaging via Postman. I'm doing a POST to this url
https://fcm.googleapis.com/v1/projects/[my project name]/messages:send
The Authorization tab in Postman is set to No Auth and my Headers tab looks like this
Content-Type: application/json
Authorization: Bearer [server key]
[server key] is a newly generated server key in the 'Cloud Messaging' tab of my Firebase project's 'Settings' area. I keep getting this error in 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"
}
Based on everything I can find, I'm using the right token, but it seems Google disagrees. What should I be sending as the Authorization header to get past this error?

Steps to get Authentication Bearer:
Got to Google OAuth Playground: https://developers.google.com/oauthplayground
In the "Input your own scopes" for FCM use this url: https://www.googleapis.com/auth/firebase.messaging
Tap Authorize API.
Pick correct user for authorisation and allow access.
In the Step 2: Exchange authorization code for tokens tap Exchange authorisation code for tokens.
Access token is your Bearer.
Steps to send FCM using Postman:
URL to send: https://fcm.googleapis.com/v1/projects/projectid-34543/messages:send
Request Type: POST
Headers: Content-Type -> application/json & Authorization -> Bearer
In the body section enter APS payload with the right device token.
Click send.
In case you want to use cURL, for a data-notification:
curl --location --request POST 'https://fcm.googleapis.com/v1/projects/your-project-id/messages:send' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer your-access-token-*****-wqewe' \
--data-raw '{
"message": {
"token": "device-token-qwfqwee-***-qefwe",
"data": {
"Key1": "val1",
"Key2": "val2"
}
}
}'

You have to generate new access token in Postman.
First, ensure you have enabled FCM API in Google Developer Console.
Than go to Google Developer Console -> APIs & Services -> Credentials. Look at "OAuth 2.0 client IDs" section. There should be at least one item in list. Download it as json file.
In Postman open "Authorization" tab, select Type = "OAuth 2.0" than click "Get New Access Token". Dialog appears.
Fields:
Token Name - type what you want
Grant Type = Authorization Code
Callback URL = redirect_uris from downloaded json
Auth URL = auth_uri
Access Token URL = token_uri
Client ID = client_id
Client Secret = client_secret
Scope = "https://www.googleapis.com/auth/firebase.messaging"
State - leave empty
Client Authentication = default, Send As Basic Auth Header
Click "Request Token" and that's it.

The Bearer Token is the result of getting an OAuth access token with your firebase service account.
Get yourself a Firebase service account key.
Go to your firebase console > Settings > Service Accounts.
If your on Firebase Admin SDK generate new private key.
You use the service account key to authenticate yourself and get the bearer token.
Follow how to do that in Node, Python or Java here:
https://firebase.google.com/docs/cloud-messaging/auth-server.
So in Java you can get the token like this:
private static final String SCOPES = "https://www.googleapis.com/auth/firebase.messaging";
public static void main(String[] args) throws IOException {
System.out.println(getAccessToken());
}
private static String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("service-account.json"))
.createScoped(Arrays.asList(SCOPES));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
And now you can finally send your test notification with FCM.
Postman code:
POST /v1/projects/[projectId]/messages:send HTTP/1.1
Host: fcm.googleapis.com
Content-Type: application/json
Authorization: Bearer access_token_you_just_got
{
"message":{
"token" : "token_from_firebase.messaging().getToken()_inside_browser",
"notification" : {
"body" : "This is an FCM notification message!",
"title" : "FCM Message"
}
}
}

To generate an for testing push notification, you can use Google Developers OAuth 2.0 Playground
You can even send a test Push Notification using Google Developers OAuth 2.0 Playground itself.
Or if you want can use Postman / Terminal (curl command) as well.
Please find the detailed steps here, which I wrote.
Note : Instead of "Project name" in the Endpoint, you have to use "Project ID". Steps for getting the Project ID is also mentioned in the above link.

You should use definitely use Google-OAuth2.0, which can be generated using described steps in the provided link.
you can find detailed steps here, which I answered for similar question.

Related

Error 403 message seen during API testing in DUO even though valid credentials were provided. Does wrong integration type mean i need a new key?

I used the following API in postman with integration key, client secret from the Admin API application but no luck.
GET: https://api-123abc.duosecurity.com/auth/v2/check
Furthermore,
I used basic auth for authorization
Integration key for username and created the password via
https://www.freeformatter.com/hmac-generator.html#ad-output (used
integration key for string and client secret from the duo UI)
I used the following headers:
Authorization:Basic
Integration-key:Secret-key
Date:Fri, 20 May 2022 02:26:39 +0000
Content-Type:application/x-www-form-urlencoded
Besides this I used the code
btoa('integration key:secret key')
to generate authentication code but it still gives the following error
{
"code": 40301,
"message": "Access forbidden",
"message_detail": "Wrong integration type for this API.",
"stat": "FAIL"
}
Add Postman PreRequest script
update/replace integration and secret keys in below script
follow docs
const cannon = [
new Date().toUTCString(),
pm.request.method,
pm.request.url.host.join('.'),
'/'+pm.request.url.path.join('/'),
];
if (pm.request.body.urlencoded){
cannon.push(pm.request.body.urlencoded);
}
function hmacSign(cannon, integrationKey, secretKey){
const message = cannon.join("\n");
console.log(message);
var hmac = CryptoJS.HmacSHA1(message, secretKey)
return btoa(`${integrationKey}:${hmac}`)
}
const sign = hmacSign(cannon, "DIWJ8X6AEYOR5OMC6TQ1", "Zh5eGmUq9zpfQnyUIu5OL9iWoMMv5ZNmk3zLJ4Ep")
pm.request.headers.add({
key: "authorization",
value: sign
});

how to generate auth 2.0 in karate I saw a sample in karate Demo project but in our case we need to send it as "Authorization Code"

How to generate OAuth 2.0 token via karate.
How we have tried in Postman:
On Authorization tab select OAuth 2.0
Select Header Prefix Bearer
Grant-Type is "Authorization Code"
Callback URL is selected as when we will click submit it redirects to a browser where we have to enter credentials and a user is validated once it is validated the browser redirects back to Postman
Add "Auth URL" and "Access Token URL"
Enter "Client ID" and "Client Secret"
Select "Client Authentication" as Send as Basic Auth Header.
Postman then redirects to a browser where we enter username and password and once authenticated it redirects user back to postman with access token.
Question:
When we provide grant_type as "authorization code" in Karate we are getting an error as {"error":"unsupported_grant_type","error_description":"Unsupported grant_type"}. What to provide here as when we provide "password" we are getting 401 and when we provide "authorization code" we are getting 400.
Secondly, Can we automate such scenario where a browser is invoked as well and we have to enter credentials can we achieve it via Karate as then we have to store the token and pass in the APIs?
Background:
* url 'http://localhost:8080/pathdetails'
Scenario: get all users and then get the first user by id
* path 'token'
* form field grant_type = 'authorization code'
* form field client_id = 'ourapiclient'
* form field client_secret = '324243324-3334-334-343-3432423424'
* method post
* status 200
* def accessToken = response.access_token
EDITED**********
I have now tried to send a API request to Auth URL which redirects to the browser and returns HTML page.
Given url 'http://localhost:8080/myurlpath/auth'
* form field response_type = 'code'
* form field client_id = 'abcc'
* form field scope = 'openconnect'
* form field redirect_uri = 'http://localhost:8080/redirecturlpath'
* form field state = 'cEY3R-YfsoM9232diS72COdHTA8uPv9K49pjZaPag5M.8akinzwobn8.abcd4'
* method get
* status 200
* print 'Response is........',response
This returned an HTML page which is exactly the same page I see when I send request from Postman. How to now enter username and password in karate on this html page as this page was returned as part of the response of above API.
I was expecting above will return me a code and after that I will call the request token endpoint but above redirected me to where I enter username and password and then once it is successful it redirects back to Postman and in URL I can see the code as well.
curl --request POST \
--url 'https://YOUR_DOMAIN/oauth/token' \
--header 'content-type: application/x-www-form-urlencoded' \
--data grant_type=authorization_code \
--data 'client_id=YOUR_CLIENT_ID' \
--data client_secret=YOUR_CLIENT_SECRET \
--data code=YOUR_AUTHORIZATION_CODE \
--data 'redirect_uri=https://YOUR_APP/callback'
How to get the code which is needed by the token API?
I tried sending Auth API to access like below but no code or token got returned in the response.
Given driver 'http://localhost:8080/myurlpath/auth?scope=openconnect&state=cEY3R-YfsoM9232diS72COdHTA8uPv9K49pjZaPag5M.8akinzwobn8.abcd4&response_type=code&client_id=abcc&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fauth%2Fmyurlpath'
* fullscreen()
And input('#username', 'username')
And input('#password', 'password')
When click('#login')
The above doesn't return any error but it doesn't return the code I am looking for as well
#Maddy To see grant types You need access to auth0, or ask your devs to tell You what grants are implemented here you can read more:
https://auth0.com/docs/configure/applications/application-grant-types
And here You can read how to implement autorization-code flow:
https://auth0.com/docs/login/authentication/add-login-auth-code-flow
To make Your life easier You could ask devs to implement Password-realm-grant but this is not recommended.
Here is how rectify one of oAuth 2.0 token generation
* def cid = 'client_id'
* def csec = 'token_secret'
* def AuthCode = Java.type('com.test.qa.aut.authCode')
* print AuthCode.Code()
* def authentication = 'Basic ' + AuthCode.Code(cid, csec)
* print authentication
* url 'https://acpint.online.com/default/np/oauth2/'
* header Authorization = authentication
And header Content-Type = 'application/x-www-form-urlencoded; charset=utf-8'
* form field grant_type = 'client_credentials'
Then method post
And status 200
Then print response
Java class:
package com.test.qa.aut;
import java.util.Base64;
public class authCode {
public static String Code(String clientId, String clientSecret) {
String auth = clientId + ":" + clientSecret;
String authentication = Base64.getEncoder().encodeToString(auth.getBytes());
return authentication;
}
}

Invalid Client with paypal api, client authentication failed using HTTPoison.post!/3

I am using HTTPoison to send request to the Paypal api. Here is the paypal documentation for using its api for logging in: https://developer.paypal.com/docs/log-in-with-paypal/integrate/
When I get the code, and try to exchange it for an access token, I get this error: "{\"error\":\"invalid_client\",\"error_description\":\"Client Authentication failed\"}",
Here is how HTTPoison.post!/3 post request:
url = "https://api-m.sandbox.paypal.com/v1/oauth2/token"
headers = [
Authorization: "Basic #{ClientID}:#{Secret}"
]
body = "grant_type=authorization_code&code=#{code}"
HTTPoison.post!(url, body, headers)
This shows the a status_code: 401 and {\"error\":\"invalid_client\",\"error_description\":\"Client Authentication failed\"}", error.. How can this issue be solved?
HTTP Basic Authentication requires the value to be base-64 encoded. Try doing that:
Authorization: "Basic " <> Base.encode64("#{ClientID}:#{Secret}")

how to login by username and password for getting token_id and access_token using postman in auth0?

When I am trying to login with username and password to get token_id and access_token using postman with auth0 by installed using Postman Collection in Postman
I get an error in login method of database:
You are correct that the /oauth/ro endpoint is being deprecated. You should be making a call to /oauth/token instead.
Your question is unclear.
Try to send the first request with login/password by standard authentication (Authorization tab > Type > Basic Auth).
As the following steps I recommend to check the relevant Postman manual: Using the Auth0 API with our Postman Collections and use the predefined collections from Auth0 API Documentation (press on "Run in Postman" button).
In addition, it's strongly recommended to use the Native Postman app, but not its deprecated Chrome extension.
I was able to get the id_token by using the /oauth/token endpoint, and passing scope=offline_access. Here is an example of my POST payload (Python code):
{
"grant_type": "http://auth0.com/oauth/grant-type/password-realm",
"scope": "offline_access",
"client_id": client_id,
"client_secret": client_secret,
"username": username,
"password": password,
"realm": database_connection,
}
Response:
{
access_token: "lK...",
expires_in: 1000,
id_token: "eyJ...",
​ refresh_token: "ym...",
}

Magento 2 rest api throws 401 Unauthorized error

I have create a user role in Magento 2 and a new user
image capture
I used in Chrome the application Postman:
In the GET box: http://example.com/php.index/rest/V1/products/
In Type use Basic Auth with Username and Password
But I get this status '401 Unauthorized' and this requests:
{
"message": "Consumer is not authorized to access %resources",
"parameters": {
"resources": "Magento_Catalog::products"
}
}
I can login in Magento backend with the user and password
Any solution?
You need to pass basic Authorization with access key in header:
Step 1:
Call API: /V1/integration/admin/token with parameters:
username=your_admin_username
password=your_admin_password
This will give you an access key like at0o6w5rhno6sltcuhf3****k0603l
Step2:
Call API : /V1/products/ with parameters
searchCriteria=*
Put **Header**
Authorization : Bearer at0o6w5rhno6sltcuhf3****k0603l
Content-Type : application/json