How to get github token using username and password - authentication

I am developing mobile apps using rhodes. I want to access private repo of github. I am having only username and password.
How to get token of given username and password.

Once you have only login and password you can use them using basic auth. First of all, check if this code shows you json data of desired repo. Username and password must be separated by a colon.
curl -u "user:pwd" https://api.github.com/repos/user/repo
If succeeded you should consider doing this request from code.
import urllib2
import json
from StringIO import StringIO
import base64
username = "user#example.com"
password = "naked_password"
req = urllib2.Request("https://api.github.com/repos/user/repo")
req.add_header("Authorization", "Basic " + base64.urlsafe_b64encode("%s:%s" % (username, password)))
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/json")
res = urllib2.urlopen(req)
data = res.read()
repository = json.load(StringIO(data))

You should use oauth instead: http://developer.github.com/v3/oauth/

Github users can create Personal Access Tokens at their application settings. You can use this token as an alternative to username/password in basic http authentication to call the API or to access private repositories on the github website.
Simply use a client that supports basic http authentication. Set the username equal to the token, and the password equal to x-oauth-basic. For example with curl:
curl -u <token>:x-oauth-basic https://api.github.com/user
See also https://developer.github.com/v3/auth/.

Send A POST request to /authorizations
With headers
Content-Type: application/json
Accept: application/json
Authorization: Basic base64encode(<username>:<password>)
But remember to take Two factor Authentication in mind
https://developer.github.com/v3/auth/#working-with-two-factor-authentication
Here You will receive a token which can be used for further request

Follow this guide at help.github.com. It describes how to find your api-token (it's under "Account Settings" > "Account Admin") and configuring git so it uses the token.

Here is the code to use GitHub Basic Authentication in JavaScript
let username = "*******";
let password = "******";
let auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var options = {
host: 'api.github.com',
path: '/search/repositories?q=google%20maps%20api',
method: 'GET',
headers: {
'user-agent': 'node.js',
"Authorization": auth
}
};
var request = https.request(options, function (res) {
}));

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;
}
}

403 access denied to the website with proper login/pass through google script

var url = "https://web-site_name/page/?format=json&var_data-organization_dates&xlsexport=true";
var payload =
{
"login" : "login",
"password" : "pass",
};
var options =
{
"method" : "post",
"payload" : payload,
"followRedirects" : false
};
var login = UrlFetchApp.fetch("https://web-site_name/page/" , options);
var sessionDetails = login.getAllHeaders()['Set-Cookie'];
Logger.log(login.getAllHeaders());
here is the part of the code I try to use, to automate export of the data from web-site, i do have proper login and password and able to download file in json (opened in xsl) manually, I've got the address to the downloaded file in network in developer tools, but i have a problem on the first stage - when trying to authorize to the web-site - access denied. I've tried the code, given in answers on stackoverflow, but it still doesn't work.
How to make an url fetch request correctly, depends on the website you want to access and the authentication they uses
In the simplest case, your website requires HTTP basic authentification, in this case the correct syntax would be
var authHeader = 'Basic ' + Utilities.base64Encode(login + ':' + pass);
var options = {
headers: {Authorization: authHeader}
}
If your website uses a different authentication form, you might need to provide an access token.
In any case: the authentication credentials go into headers, not into payload!
payload is the data that you want to post = upload to the website.
If you want export data from the website - that is download data - you do not need a payload and the correct method would be get, not post. Btw., if the method is get, you do not need to specify it.
Please see here for more information and samples.

API access to GitHub organisation repo using personal access token

I get refused access to my GitHub organisation's repos when trying to access the API using a personal token:
(Python)
GITHUB_API_TOKEN = 'XXX'
GITHUB_HEADERS = {
'Authorization': GITHUB_API_TOKEN,
}
issues = 'https://api.github.com/repos/my_org_name/my_repo_name/issues?state=all&page=1&per_page=100'
request = requests.get(issues, headers=GITHUB_HEADERS)
[{'message': 'Not Found'}]
Accessing a personal repo works.
I have full access to my org's repos.
What's the best way around this?
You need to set the Authorization header to token YOUR_TOKEN :
import requests
GITHUB_API_TOKEN = 'YOUR_TOKEN'
GITHUB_HEADERS = {
'Authorization': "token " + GITHUB_API_TOKEN,
}
issues = 'https://api.github.com/repos/my_org_name/my_repo_name/issues?state=all&page=1&per_page=100'
request = requests.get(issues, headers=GITHUB_HEADERS)
print(request.text)
Note that Bearer YOUR_TOKEN also works
Also you need the repo scope on your personnal access token

What Bearer token should I be using for Firebase Cloud Messaging testing?

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.