I want to add HTTP V1 Access Token to my firebase cloud messaging service. I'm using python fore retrieving the access token.
import firebase_admin
from firebase_admin import credentials
cred = credentials.Certificate("path/to/serviceAccountKey.json")
firebase_admin.initialize_app(cred)
I'm using this code. It's working fine but the expiry date for the access token is only one day. What is the way to increase the expiry date?
I want to get this bearer token. In the authorisation section.
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"token":"token_1",
"data":{},
"notification":{
"title":"FCM Message",
"body":"This is an FCM notification message!",
}
}
}
To get the "access token" that is needed in the "Authorization" header, you will need to authenticate using the OAuth 2.0 process. This document explains how to get it with python.
Since you are already using the admin SDK, it will do the authentication for you. And, instead of making the HTTP request yourself, you can call the SDK methods for sending messages. See this example:
import firebase_admin
from firebase_admin import credentials
cred = credentials.Certificate("path/to/serviceAccountKey.json")
firebase_admin.initialize_app(cred)
message = messaging.Message{
"token" = "token_1",
data={
'score': '850',
'time': '2:45',
}
}
response = messaging.send(message)
print('Successfully sent message:', response)
Here you can see an example with more options and details.
Related
I'm trying to retrieve mails from my organization's mailbox, and I can do that via Graph Explorer. However, when I use the same information that I used in Graph Explorer, the generated token returns an error stating '/me request is only valid with delegated authentication flow.' in me/messages endpoint.
So, how can I generate the acceptable token for the /me endpoint?
An example python code or example Postman request would be amazing.
It sounds like the endpoint you're using in Graph Explorer is something like this
https://graph.microsoft.com/v1.0/me/messages
/me is referring to the user signed into Graph Explorer. If you want to read another user's messages you would use
https://graph.microsoft.com/v1.0/users/user#domain.com/messages
When connecting to Graph API as an application with no user interaction, you can never use /me endpoints, as there's no user logged in.
Reference
https://learn.microsoft.com/en-us/graph/api/user-list-messages?view=graph-rest-1.0
Python example to list messages
import requests
def get_messages(access_token, user):
request_url = f"https://graph.microsoft.com/v1.0/users/{user}/messages"
request_headers = {
"Authorization": "Bearer " + access_token
}
result = requests.get(url = request_url, headers = request_headers)
return(result)
msgs = get_messages(access_token = token['access_token'], user = "userPrincipalName#domain.com")
print(msgs.content)
Additional example of obtaining a token, using an app registration and client secret
import msal
def get_token_with_client_secret(client_id, client_secret, tenant_id):
# This function is to obtain a bearer token using the client credentials flow, with a client secret instead of a certificate
# https://docs.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#client-credentials-provider
app = msal.ConfidentialClientApplication(
client_id = client_id,
client_credential = client_secret,
authority = f"https://login.microsoftonline.com/{tenant_id}")
scopes = ["https://graph.microsoft.com/.default"]
token = app.acquire_token_for_client(scopes = scopes)
return(token)
My requirement is that I have written a lambda function in AWS for automatically creating a repository in GitHub using the GitHub API and PAT Token authentication.
def create_automatic_repo(repo_name):
query_url = f"https://api.github.com/api/v3/orgs/{org_name}/repos"
params = {
"name": repo_name
}
headers = {
'Authorization': f'token {secret[secretKey]}',
}
response = requests.post(query_url, headers=headers, data=json.dumps(params))
print("creating new repository response ", response)
print("creating new repository response content ", response.content)
We successfully created a repo using the Github API with PAT Token. Now we need to change authentication from PAT Token to the Github Apps.
I am trying to authenticate Github Apps using AppId and PrivateKey. I have generated the jwt token with the jwt token. I am trying to hit "https://api.github.com/app/installations/installation_id/access_tokens" this GitHub api for getting access_token. I am getting a 200 response but it is redirecting to the SAML authentication page.
$ curl -i \
-H "Authorization: token YOUR_INSTALLATION_ACCESS_TOKEN" \
-H "Accept: application/vnd.github+json" \
https://api.github.com/api/v3/orgs/{org_name}/repos
This is the curl command I have found in the official document. If I have access_token, I can use the GitHub API for creating a repo through a lambda function in AWS.
I am attaching the flow which I have followed for Authentication for Github Apps. Here I am attaching the official document which I have followed : https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps
Created Github Apps by giving homepage url as GitHub Organization url
Installed Github App under the organization level
Wrote python code for generating jwt token
Here I am attaching the Python code for generating the JWT token and triggering the GitHub API for installation_Id. I am getting 200 responses but it is redirecting to the SAML authentication page.
import json
import os
import time
import jwt
import requests
from cryptography.hazmat.backends import default_backend
cert_bytes = open(r'first.txt', "r").read().encode()
print("prtinging cert_bytes ", cert_bytes)
private_key = default_backend().load_pem_private_key(cert_bytes, None)
time_since_epoch_in_seconds = int(time.time())
payload = {
# issued at time, 60 seconds in the past to allow for clock drift
"iat": time_since_epoch_in_seconds - 60,
# JWT expiration time (10 minute maximum)
"exp": time_since_epoch_in_seconds + (10 * 60),
# GitHub App's identifier
"iss": 231726,
}
encoded_payload = jwt.encode(payload, private_key, algorithm="RS256")
print("printing encoded_payload ", encoded_payload)
headers = {
'Authorization': f'Bearer {encoded_payload}'
}
resp = requests.get("https://api.github.com/app/installations/installation_id/access_tokens", headers=headers)
print('Code: ', resp.status_code)
print('Content: ', resp.content)
This is the Image which I am redirecting to the SAML Authentication Page:
I read the GitHub official documentation, and they mentioned that we needed to activate a SAML session to authenticate Github Apps:
https://docs.github.com/en/enterprise-cloud#latest/authentication/authenticating-with-saml-single-sign-on/about-authentication-with-saml-single-sign-on#about-oauth-apps-github-apps-and-saml-sso
But I didn't see the option to enable to SSO SAML authentication as mentioned in the document. : https://docs.github.com/en/enterprise-cloud#latest/organizations/managing-saml-single-sign-on-for-your-organization/enabling-and-testing-saml-single-sign-on-for-your-organization#enabling-and-testing-saml-single-sign-on-for-your-organization
This is the Image where I did not find option for enabling the SAML Authentication:
[]
Can you please help us on enabling SAML authentication for accessing Github Apps Authentication Process without PAT Token or is there any other way for GitHub authentication from lambda function in aws using GitHub api's apart from PAT Token.
that is my first try with an API, said API being called OPS.
I would like to get information using the API (OAuth 2) within my python code.
The ressource URL is :
http://ops.epo.org/3.2/rest-services/register/{publication}/{EPODOC}/{EP2814089}/biblio
I also received :
Consumer Key: O220VlTQqAmodifiedsf0YeqgM6c
Consumer Secret Key: swWmodified3edjORU
The documentation states that:
OPS uses the OAuth framework for Authentication and Authorization. At this point in
time, only the “Client Credentials” flow is supported using a Consumer key and
Consumer secret.
The actual steps to follow are:
Step 1: Client converts Consumer key and Consumer secret to
Base64Encode(Consumer key:Consumer secret).
This should be done programmatically using the language you are developing the client
application in. For the purposes of this example, a public website was used to perform
this conversion.
By entering the colon separated Client credentials, an encoded response is generated.
This response is then be used for basic Authentication.
Step 2: Client requests an access token using Basic Authentication, supplying its
Consumer key and Consumer secret with base64Encoding over encrypted HTTPS
connection:
OPS authenticates the client credentials passed in the Authorization header using basic
authentication method.
If credentials are valid, OPS responds with a valid access token.
Step 3: Client accesses OPS resources with access token in authorization header
(bearer tokens) over encrypted HTTPS connection
I tried a few samples of code with requests but, until now, nothing worked.
The client credentials flow is described in the OAuth2 RFC-6749. The client id and secret are base64 encoded in a Basic authentication scheme as described in RFC-7617
You should be able to get a token using Python code like:
import requests
import base64
url = 'https://ops.epo.org/3.2/auth/accesstoken'
data = {"grant_type": "client_credentials"}
creds = base64.b64encode("O220VlTQqAmodifiedsf0YeqgM6c:swWmodified3edjORU".encode())
headers = {'Authorization': 'Basic ' + creds.decode('UTF-8'), 'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(url, headers=headers, data=data)
access_token = response.json()["access_token"]
When using the previous response I can obtain a token. (Thanks a lot for your answer)
So I tried :
myUrl = 'http://ops.epo.org/3.2/rest-services/register/publication/EPODOC/EP2814089/biblio'
header = {'PRIVATE-TOKEN': myToken}
response = requests.get(myUrl, headers=header)
print(response.text)
but I obtained a 403 error.
I finally got a specific library to do the job :
EPO OPS Library
But I still don't know how to do it on my own...
We have our jenkins authentication setup using google oauth using OpenId Connect in Apache (Reference: https://cloudavail.com/2014/06/07/apache-auth-oidc-google-apps-2/).
In order to automate some of the jenkins jobs, we have to authenticate first.
I got the access token and refresh token using client-secrets.json in a python script during which authentication to google mail is already done.
I am using the following script to auto refresh the token using the refresh token and then use the new token to list all of the jobs or projects in Jenkins.
Why is it redirecting me to google login when I have already authorized with gmail during the authorize step while fetching the access token. It will be a great help, if anyone can help me resolve this.
Following is the script (token.json and extra.json contains token and client details)
#!/usr/bin/env python
import requests_oauthlib, json
from requests_oauthlib import OAuth2Session, TokenUpdated
protected_url='<jenkins_url>/api/json?pretty=true'
refresh_url='https://accounts.google.com/o/oauth2/token'
#Start here
TOKEN_FILE='token.json'
EXTRA_FILE='extra.json'
with open(TOKEN_FILE, 'r') as f:
token = json.load(f)
with open(EXTRA_FILE, 'r') as f:
extra = json.load(f)
client_id=extra['client_id']
def token_saver(token_temp):
token = token_temp
from requests_oauthlib import OAuth2Session
client = OAuth2Session(client_id, token=token, auto_refresh_url=refresh_url,auto_refresh_kwargs=extra, token_updater=token_saver)
token=client.refresh_token(refresh_url, **extra)
token_saver(token)
client = OAuth2Session(client_id, token=token)
r = client.get(protected_url)
print r.content
token.json contents
{
"access_token": "{access_token}",
"refresh_token": "{Refresh_token}",
"id_token": "{id_token}",
"token_type": "Bearer",
"expires_in": "5"
}
extra.json contents
{
"client_id":"{client_id}",
"client_secret":"{client_secret}"
}
I'm trying to create Circles with the Google+ API, but I'm kinda stuck, this is my code, it was more or less copied from the official API documentation (yes I know it doesn't create Circle, but the issue is the same)
import httplib2
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
import json
with open('client_secrets.json', 'r') as f:
json_data = json.load(f)
data = json_data['web']
CLIENT_ID = data['client_id']
CLIENT_SECRET = data['client_secret']
# List the scopes your app requires:
SCOPES = ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/plus.circles.write']
# The following redirect URI causes Google to return a code to the user's
# browser that they then manually provide to your app to complete the
# OAuth flow.
REDIRECT_URI = 'http://localhost/oauth2callback'
# For a breakdown of OAuth for Python, see
# https://developers.google.com/api-client-library/python/guide/aaa_oauth
# CLIENT_ID and CLIENT_SECRET come from your APIs Console project
flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=SCOPES,
redirect_uri=REDIRECT_URI)
auth_uri = flow.step1_get_authorize_url()
# This command-line server-side flow example requires the user to open the
# authentication URL in their browser to complete the process. In most
# cases, your app will use a browser-based server-side flow and your
# user will not need to copy and paste the authorization code. In this
# type of app, you would be able to skip the next 3 lines.
# You can also look at the client-side and one-time-code flows for other
# options at https://developers.google.com/+/web/signin/
print 'Please paste this URL in your browser to authenticate this program.'
print auth_uri
code = raw_input('Enter the code it gives you here: ')
# Set authorized credentials
credentials = flow.step2_exchange(code)
# Create a new authorized API client.
http = httplib2.Http()
http = credentials.authorize(http)
service = build('plusDomains', 'v1', http=http)
from apiclient import errors
try:
people_service = service.people()
people_document = people_service.get(userId='me').execute()
except errors.HttpError, e:
print e.content
My output:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
}
I searched for answer, but didn't really find any. On the API console I have Google+ API and
Google+ Domains API services added also my secret and client id are okay (otherwise the whole script would fail sooner). Also the auth is successful, my app's name is shown under https://accounts.google.com/IssuedAuthSubTokens. What did I miss?
The problem lies with your REDIRECT_URI variable. When you are using OAuth 2.0 in a purely server-side flow, the redirect URI MUST be 'urn:ietf:wg:oauth:2.0:oob'.
Try changing the variable like so (and be sure to update your client ID in the API Console):
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
Edit: Also, make sure that you are making your API call for a user within a domain. The Google+ Domains API only permits API calls that are restricted to users and content within that domain.