this is my first time using Google API, and i got difficulty about google-people api, can anybody here explain what needed header/body data for auth (i use https://crystal-lang.org/api/latest/OAuth2.html), and please share a simple code (vanilla / without library) in your favorite programming language ^^
Follow steps described in Get Ready to Use the People API. There you will find examples written in Java, Python, PHP, .NET.
Let's assume you finished with step 1 and 2. Here is a Crystal code to make an authorization request:
require "oauth2"
client_id = "CLIENT_ID"
client_secret = "CLIENT_SECRET"
scope = "profile"
redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
client = OAuth2::Client.new(
"accounts.google.com",
client_id,
client_secret,
authorize_uri: "/o/oauth2/v2/auth",
redirect_uri: redirect_uri
)
authorize_uri = client.get_authorize_uri(scope)
authorize_uri #=> https://accounts.google.com/o/oauth2/v2/auth?client_id=CLIENT_ID&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcontacts.readonly
Open authorize link in your browser, allow access to your data and you will get a token required for the next step.
authorization_code = code # authorization code taken from the previous step
client = OAuth2::Client.new(
"www.googleapis.com",
client_id,
client_secret,
token_uri: "/oauth2/v4/token",
redirect_uri: redirect_uri
)
access_token = client.get_access_token_using_authorization_code(authorization_code)
client = HTTP::Client.new("people.googleapis.com", tls: true)
access_token.authenticate(client)
response = client.get "/v1/people/me?personFields=names"
response.body # a json that contains my name
Related
This one has been driving me mad for a couple of days and I can't find a solution. Can someone point me towards one? Thank you in advance!
What I want:
I want to successfully use the authorization_code flow for a Power BI Extension.
What I've done:
I've setup an OAuth2 flow in Power Query M and when I target my localhost IdentityServer, I can login with the user login screen and I get an Access Token that Power BI can use. This works, but it doesn't work on a published IdentityServer (same code, same database). So what am I missing?
Here's what happens:
I have this Power Query M code (it's pretty standard, I found it online and it works on localhost):
StartLogin = (resourceUrl, state, display) =>
let
authorizeUrl = oauthUrl & "connect/authorize?" & Uri.BuildQueryString([
response_type = "code",
client_id = client_id,
redirect_uri = redirect_uri,
state = state,
scope="myscope"
])
in
[
LoginUri = authorizeUrl,
CallbackUri = redirect_uri,
WindowHeight = windowHeight,
WindowWidth = windowWidth,
Context = null
];
FinishLogin = (context, callbackUri, state) =>
let
// parse the full callbackUri, and extract the Query string
parts = Uri.Parts(callbackUri)[Query],
// if the query string contains an "error" field, raise an error
// otherwise call TokenMethod to exchange our code for an access_token
result = if (Record.HasFields(parts, {"error", "error_description"})) then
error Error.Record(parts[error], parts[error_description], parts)
else
TokenMethod("authorization_code", "code", parts[code])
in
result;
TokenMethod = (grantType, tokenField, code) =>
let
queryString = [
grant_type = grantType,
redirect_uri = redirect_uri,
client_id = client_id,
client_secret = client_secret
],
queryWithCode = Record.AddField(queryString, tokenField, code),
tokenResponse = Web.Contents(oauthUrl & "connect/token", [
Content = Text.ToBinary(Uri.BuildQueryString(queryWithCode)),
Headers = [
#"Content-type" = "application/x-www-form-urlencoded",
#"Accept" = "application/json"],
ManualStatusHandling = {400}
]),
body = Json.Document(tokenResponse),
result = if (Record.HasFields(body , {"error", "error_description"})) then
error Error.Record(body[error], body[error_description], body)
else
body
in
result;
What happens is that an IE frame pops up to prompt for my credentials:
The normal login page
Once I login on localhost, I get my AccessToken, life's good :-)
However, once I login on the deployed IdentityServer, I get this one, a 400:
Failing on deployed IdentityServer
The address is: res://ieframe.dll/http_400_webOC.htm#https://identityserverurl/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fresponse_type%3Dcode%26client_id%3DPowerBI%26redirect_uri%3Dhttps%253A%252F%252Foauth.powerbi.com%252Fviews%252Foauthredirect.html%26state%3D852bddfc-638c-44f6-90be-a04346908753%26scope%3Dmyscope
I think the problem has something to do with Internet Explorer and the way the window is being presented, but I can't figure out why it DOES work on localhost, just NOT on a deployed server. The client settings are identical on both localhost and on the deployed IdentityServer (it's on a develop server; they target the same database).
I know on a deployed IdentityServer the home page is not available, so the "https://identityserverurl/" will give a 404. Is something similar going on here?
What am I missing?
Any help is much appreciated! It's the final step to getting it all to work.
Best regards,
Remco
Update: Added IdentityServer logging and Fiddler Trace:
GET /connect/authorize?response_type=code&client_id=PowerBI&redirect_uri=https%3A%2F%2Foauth.powerbi.com%2Fviews%2Foauthredirect.html&state=d2f420fb-a98a-4327-b8f1-ebb8937f8b00&scope=openid%20profile%20offline_access%20myscope HTTP/1.1
GET /Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fresponse_type%3Dcode%26client_id%3DPowerBI%26redirect_uri%3Dhttps%253A%252F%252Foauth.powerbi.com%252Fviews%252Foauthredirect.html%26state%3Dd2f420fb-a98a-4327-b8f1-ebb8937f8b00%26scope%3Dopenid%2520profile%2520offline_access%2520myscope HTTP/1.1
There's not much else going on. It just simply stops when I click login.
I am getting the following error
Whoa there!
The request token for this page is invalid. It may have already been used, or expired because it is too old. Please go back to the site or application that sent you here and try again; it was probably just a mistake
1) The following method in which we are calling the twitter credentials to your Api
2)The callback function is static
3) i am using Oauth 1 and using google cloud for hosting
4)I have already cleared the cache 2 times still no use
.def _twitter(self):
# Get the access token supplied
oauth_token = self.test_credentials.get('oauth_token')
oauth_token_secret = self.test_credentials.get('oauth_token_secret')
if not oauth_token or not oauth_token_secret:
raise AuthenticationException('Invalid request format.', 400)
auth = tweepy.OAuthHandler(current_app.config['TWITTER_CONSUMER_KEY'], current_app.config['TWITTER_CONSUMER_SECRET'])
auth.set_access_token(oauth_token, oauth_token_secret)
api = tweepy.API(auth)
user = api.verify_credentials()
if not user:
raise AuthenticationException('Unable to verify credentials with remote server.', 500)
# Save the user
auth_string = self._auth_string(unicode(user.id_str))
stored_user = User.query(User.auth_ids == auth_string).get()
if not stored_user:
return User(name=user.name)
if stored_user and not stored_user.name:
stored_user.name = user.name
stored_user.put()
return stored_user
I forgot to add my callback function in the twitter api callbacks (these resolved my error)
Im using Google tutorial to get access token for my web application. but in the following steps:
Your web application redirects the user to Google Authorization page
User grants your web application access
Google redirects the user back to your web application and returns an authorization code
I dont know how to get this authorization code ? actually in my python code I dont know how to get "auth_code"
data = urllib.urlencode({
'code': auth_code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'grant_type': 'authorization_code'
})
I found my solution :)
I should past this url in my browser and get the code
print '%s?client_id=%s&redirect_uri=%s&scope=%s&response_type=code' % \
('https://accounts.google.com/o/oauth2/auth',
clientID,
redirect_uri,
'https://www.googleapis.com/auth/fusiontables')
I have a website built in django 1.7, python 3.4. I want to enable my users to invite their gmail contacts to my website (like linkedin & many other websites do). I am using Oauth2.0 and am able to get permission to access their contacts. But i am not getting an idea how to proceed and what steps to take.
Can somebody help me to get an overview of all the steps that i need to take and a little explanation as to how to do that.
Even a link to suitable post would be helpful.
See, When you need to implement these features in your website, you will have to understand the APIs etc to utilize it to the fullest.
Go through this https://developers.google.com/google-apps/contacts/v3/?csw=1#audience
Let's talk only about google only. The rest providers can also be managed with similar steps. Here you are using django-allauth for this task.
The basic steps involved are:
Get your app created and configured with the provider. for that you will need a developer profile in google(or facebook etc.). You will have to create an app in google developer console and you will find a plenty of tutorial for this on internet. That has been done by you as you have signup with google activated on your site. That is server side of Oauth2.0
Now you need to define the scope of authorization you need. You might only need the access to view the public profile thing. that may include first name, last name, email, id, gender, etc. For your app, you need contacts of users and for that you will have to include it in the scope too.
That is done in settings.py only.
'google': {'SCOPE': ['profile', 'email', 'https://www.googleapis.com/auth/contacts'],
'AUTH_PARAMS': {'access_type': 'online'}}
}
Now here, you have got the access to the contacts. Now, you only need to extract the contacts with the consent of data owner(user).
For this purpose,you may follow the first link in the answer. What you have to do is you have to send a get request to some url('https://www.google.com/m8/feeds/contacts/default/full' + '?access_token=' + access_token). The request goes to provider only(google) with the authorization token it has provided you for that particular user. That you will find in the db table socialtoken. Once you send proper request, the response you will get is the contacts of the user in xml format.
Once you get it, you can easily parse it to extract the required information.
Things are simple if you understand the flow. django-allauth only helpy you upto signup & signin where you can get different permissions through defining the scope.
For extracting the contacts, you can write your own code.
A simple example is:
def get_email_google(request):
# social = request.user.social_auth.get(provider='google-oauth2')
user =request.user
# Code dependent upon django-allauth. Will change if we shift to another module
# if request.user.userprofile.get_provider() != "google":
a = SocialAccount.objects.get(user=user)
b = SocialToken.objects.get(account=a)
# access = b.token
access_token = b.token
url = 'https://www.google.com/m8/feeds/contacts/default/full' + '?access_token=' + access_token + '&max-results=100'
req = urllib2.Request(url, headers={'User-Agent' : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.30 (KHTML, like Gecko) Ubuntu/11.04 Chromium/12.0.742.112 Chrome/12.0.742.112 Safari/534.30"})
contacts = urllib2.urlopen(req).read()
contacts_xml = etree.fromstring(contacts)
# print
# return render(request, 'search/random_text_print.html', locals())
result = []
for entry in contacts_xml.findall('{http://www.w3.org/2005/Atom}entry'):
for address in entry.findall('{http://schemas.google.com/g/2005}email'):
email = address.attrib.get('address')
result.append(email)
return render(request, 'search/random_text_print.html', locals())
user =request.user
a = SocialAccount.objects.get(user=user)
b = SocialToken.objects.get(account=a)
# access = b.token
access_token = b.token
SCOPES = ['SCOPE_URL']
creds = client.AccessTokenCredentials(access_token, 'USER_AGENT')
service = build('calendar', 'v3', credentials=creds)
I getting back into Python and wanted to use the pyfoursquare package to access the Foursquare API. I'm trying to get information about venues using the venues method in the API class. I'm primarily trying to find out whether a venue page is verified with Foursquare or not. When I provide my client id, client secret, and venue id I keep getting back an error that states "Authentication required", which doesn't makes sense because I'm providing that information. Any help would be great. Thank you.
import pyfoursquare as foursquare
client_id = ""
client_secret = ""
callback = ""
auth = foursquare.OAuthHandler(client_id, client_secret, callback)
api = foursquare.API(auth)
result = api.venues("4e011a3e62843b639cfa9449")
print result[0].name
Let me know if you would like to see the error message. Thanks again.
I believe you are skipping the step of grabbing your OAuth2 access token, so you're not technically authenticated.
Have a look at the following instructions, under "How to Use It":
https://github.com/marcelcaraciolo/foursquare
The lines that might be useful to you are:
#First Redirect the user who wish to authenticate to.
#It will be create the authorization url for your app
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
#If the user accepts, it will be redirected back
#to your registered REDIRECT_URI.
#It will give you a code as
#https://YOUR_REGISTERED_REDIRECT_URI/?code=CODE
code = raw_input('The code: ').strip()
#Now your server will make a request for
#the access token. You can save this
#for future access for your app for this user
access_token = auth.get_access_token(code)
print 'Your access token is ' + access_token