Use OAuth with PyGithub to request private repo access - oauth

I am having trouble finding a way to request "repo" scope when authorizing a user in OAuth using the PyGithub library.
My team is building a "repository analyzer" website that provides insights on code in a chosen repository. We are using the PyGithub implementation of the Git API. We are using OAuth to authorize users and it works great for public repositories. However, I am unable to succesfully specify a scope. I tried "Github.oauth_scopes" below which is obviously wrong. Any tips are greatly appreciated!
In the screenshot can see that OAuth is only requesting public data, we need to prompt access to private repositories too which means using the "repo" scope: GitApiScopeDoc
from github import *
g = Github()
#request repo scope
Github.oauth_scopes = "repo"
#authorization using oauth
clientID = "enterclientidhere"
secret = "entersecrethere"
oauth = g.get_oauth_application(clientID, secret)
url = oauth.get_login_url()
#print the url, then we follow the url to github which requests a users identity
print(url)
screenshot

from github import *
g = Github()
#request repo scope
Github.scopes = "repo"
#authorization using oauth
clientID = "enterclientidhere"
secret = "entersecrethere"
oauth = g.get_oauth_application(clientID, secret)
url = oauth.get_login_url()
#print the url, then we follow the url to github which requests a users identity
print(url)
The code above should work. You sh

Related

Cloud Function & OAuth 2.0

I have a issue to use OAuth2.0 on GCP Cloud Function. I use to run this code locally. it works and it open a web browser's page to ask access to my gmail account.
I know that InstalledAppFlow is only use for local application.
SCOPES = ['https://mail.google.com/']
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES) # <-- Oauth2.0 credential
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
I then tried to do another way using /tmp repesitory to store the token but still doesn't work and I can't see where is the issue ... Do you have any idea ? thank you so much
SCOPES = ['https://mail.google.com/']
CLIENT_SECRET_FILE = 'credentials.json' #OAuth credentials
APPLICATION_NAME = 'Gmail API Python'
def get_credentials():
store = oauth2client.file.Storage("/tmp/tempcredentials.json")
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store)
return credentials
As stated in the documentation the temporary folder is just for creating temporary files that will be stored in RAM memory and only available for the instance currently executing your code, thus there's no guarantee of persistence between invocations.
You should check this tutorial as it explains how to authenticate from Cloud Functions into Gmail (you will need more than a single function).

How generate OAuth for azure vm

I installed Grafana on my Azure virtual machine. Now I want to set OAuth.
In defaults.ini I set the
name = my app
enabled = true
allow_sign_up = true
client_id = with my id
client_secret = with my client_secret
scopes = openid email name
auth_url =
token_url =
api_url =
team_ids =
allowed_organizations =
And this not work. Can anyone have some idea where I wrong.
Do not edit defaults.ini!
Use the following link to create or locate grafana.ini or custom.ini depending on your OS:
https://grafana.com/docs/grafana/latest/installation/configuration/
I would recommend that you copy the block of code for the OAuth provider you want to use to grafana.ini/custom.ini and then edit it to suit your need.
You may have to edit the URL under the [server] settings to allow for the correct redirect when using external OAuth

LinkedIn API Get Access Token Failed

We are trying to implement the LinkedIn API authentication module based on: https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin/context.
We have the redirect url for the application setup as our company's main page (https://www.{site}.com) and we are able to get the auth code from the redirect URL. However, it gives us 401 error below when exchange for access token:
b'{"error":"invalid_request","error_description":"Unable to retrieve
access token: authorization code not found"}'
The weird thing is, it works and we are able to exchange the code for access token if we switch the redirect url to a different site like https://www.example.com in the API Console. Below is the Py3 code we use:
from requests_oauthlib import OAuth2Session
from requests_oauthlib.compliance_fixes import linkedin_compliance_fix
# Credentials and redirect uri you get from registering a new application
client_id = 'client_id'
client_secret = 'client_secret'
redirect_url = 'redirect_url'
# OAuth endpoints given in the LinkedIn API documentation (check for updates)
authorization_base_url = 'https://www.linkedin.com/oauth/v2/authorization'
token_url = 'https://www.linkedin.com/oauth/v2/accessToken'
# Authorized Redirect URL (from LinkedIn config)
o2_session = OAuth2Session(client_id=client_id, redirect_uri=redirect_url, scope=['rw_ads', 'r_ads_reporting'])
linkedin = linkedin_compliance_fix(o2_session)
# Redirect user to LinkedIn for authorization
authorization_url, state = linkedin.authorization_url(authorization_base_url)
print('Please go here and authorize,', authorization_url)
# Get the authorization verifier code from the callback url
redirect_response = input('Paste the full redirect URL here:')
linkedin.fetch_token(token_url, include_client_id=client_id, client_secret=client_secret, authorization_response=redirect_response)
token = linkedin.access_token
Understood that the auth code has short life span, so tried both redirect URL seconds after the code is post back to the URL. Can anyone think of any reason could cause this weird different behaviors for different redirect URLs.

Google OAUTH using django get access token

I'm struggling to retrieve access token using django.
I want to get access token from users using oAuth.
This is what I have setup so far.
class GoogleExhangeViewSet(viewsets.ViewSet):
queryset = User.objects.all()
#list_route(
methods=["GET"])
def auth(self,request,pk=None):
client_id = ''
client_secret = ''
flow = OAuth2WebServerFlow(client_id=client_id,
client_secret=client_secret,
scope='https://www.googleapis.com/auth/calendar',
redirect_uri='http://localhost:8001/api/googleAuth/complete')
auth_uri = flow.step1_get_authorize_url()
return HttpResponseRedirect(auth_uri)
def complete(self, request, pk=None):
client_id = ''
client_secret = ''
host = Site.objects.get_current().name
flow = OAuth2WebServerFlow(client_id=client_id,
client_secret=client_secret,
scope='https://www.googleapis.com/auth/calendar',
redirect_uri='http://localhost')
credentials = flow.step2_exchange(request.GET.get('code'))
return Response(status=200,data=credentials.access_token)
under urls.py I have
api_router.register(r'api/googleAuth', GoogleExhangeViewSet)
This is the error I get with the following code
As seen in your error, you are encountering a redirect_uri_mismatchBad Request if you are using a wrong redirect uri. From this link, the redirect_uri_mismatch will be thrown if it was not matched between auth and token requests.
Additional references:
Google oAuth2 redirect_uri_mismatch in token access
Google OAuth 2.0 redirect_uri_mismatch error
Here's a tutorial if you want to use an Access Token to authenticate users against Django’s authentication system.
You need a fully-functional OAuth2 provider which is able to release access tokens: just follow the steps in the part 1 of the tutorial. To enable OAuth2 token authentication you need a middleware that checks for tokens inside requests and a custom authentication backend which takes care of token verification.

LinkedIn RestSharp and OAuthBase Example

anyone ever used C# in combination with the library RestSharp and OAuthBase in order get some interaction with LinkedIn?
I'm looking for a working example using these tools to do proper authorization (oAuth 2.0) and to publish a post using the share API on LinkedIn.
So far I've been successful using these tools to obtain valid access tokens (I can use it to obtain profile information for example), but posting via the share API got me stuck on authentication.
Any help would be very much appreciated!!
it turned out to be much simpler than I was thinking.... (doesn't it allways?)
The main point to take into account is: oAuth 2.0 does not require signatures, nonce, timestamps, authorization headers ... none of that.
If you want to post on LinkedIn using the sahres API and using oAuth2.0 ... OAuthbase is not needed.
Simply follow the oauth 2.0 authentication flow as described here:
http://developer.linkedin.com/documents/authentication
And then you can use the following code as a starting point:
var shareMsg = new
{
comment = "Testing out the LinkedIn Share API with JSON",
content = new
{
title = "Test post to LinkedIn",
submitted_url = "http://www.somewebsite.com",
submitted_image_url = "http://www.somewebsite.com/image.png"
},
visibility = new
{
code = "anyone"
}
};
String requestUrl = "https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=" + accessToken;
RestClient rc = new RestClient();
RestRequest request = new RestRequest(requestUrl, Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("x-li-format", "json");
request.RequestFormat = DataFormat.Json;
request.AddBody(shareMsg);
RestResponse restResponse = (RestResponse)rc.Execute(request);
ResponseStatus responseStatus = restResponse.ResponseStatus;
Happy coding!!

Resources