EzDevInfo.com

oauth2client

This is a Python library for accessing resources protected by OAuth 2.0.

OAuth2 library for Erlang

In my project I need a client OAuth2 library. The project is written in Erlang. What are the options for the language?

PS I am a newbie in Erlang, so documentation/examples are a must.


Source: (StackOverflow)

How to access OAuth 2.0, REST API in GNOME 3.0 shell extension?

How would I port the OAuth 2.0 implict grant flow from a browser environment if I wanted to access the REST API beneath it through a GNOME shell extension ? How would I redirect the user to the OAuth 2.0 decision endpoint through a login screen?

If it isn't possible with a OAuth 2.0 REST API in what other way can I integrate a web service with a shell extension?


Source: (StackOverflow)

Advertisements

Django 1.7 google oauth2 token validation failure

I'm trying to get through the process of authenticating a Google token for accessing a user's calendar within a Django application. Although I've followed several indications found on the web, I'm stuck with a 400 error code response to my callback function (Bad Request).

views.py

# -*- coding: utf-8 -*-
import os

import argparse
import httplib2
import logging

from apiclient.discovery import build
from oauth2client import tools
from oauth2client.django_orm import Storage
from oauth2client import xsrfutil
from oauth2client.client import flow_from_clientsecrets

from django.http import HttpResponse
from django.http import HttpResponseBadRequest
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.conf import settings

from apps.tecnico.models import Credentials, Flow

CLIENT_SECRETS = os.path.join(
    os.path.dirname(__file__), '../../client_secrets.json')

@login_required
def index(request):
    storage = Storage(Credentials, 'id', request.user, 'credential')
    FLOW = flow_from_clientsecrets(
        CLIENT_SECRETS,
        scope='https://www.googleapis.com/auth/calendar.readonly',
        redirect_uri='http://MY_URL:8000/oauth2/oauth2callback'
    )
    credential = storage.get()
    if credential is None or credential.invalid is True:
        FLOW.params['state'] = xsrfutil.generate_token(
            settings.SECRET_KEY, request.user)
        authorize_url = FLOW.step1_get_authorize_url()
        f = Flow(id=request.user, flow=FLOW)
        f.save()
        return HttpResponseRedirect(authorize_url)
    else:
        http = httplib2.Http()
        http = credential.authorize(http)
        service = build(serviceName='calendar', version='v3', http=http,
                        developerKey='MY_DEV_KEY_FROM_GOOGLE_CONSOLE')

        events = service.events().list(calendarId='primary').execute()
        return render_to_response('calendario/welcome.html', {
            'events': events['items'],
        })


@login_required
def auth_return(request):
    if not xsrfutil.validate_token(
            settings.SECRET_KEY, request.REQUEST['state'], request.user):
        return HttpResponseBadRequest()

    storage = Storage(Credentials, 'id', request.user, 'credential')
    FLOW = Flow.objects.get(id=request.user).flow
    credential = FLOW.step2_exchange(request.REQUEST)
    storage.put(credential)
    return HttpResponseRedirect("http://MY_URL:8000/caly")

models.py

from oauth2client.django_orm import FlowField, CredentialsField

[...]

class Credentials(models.Model):
    id = models.ForeignKey(User, primary_key=True)
    credential = CredentialsField()


class Flow(models.Model):
    id = models.ForeignKey(User, primary_key=True)
    flow = FlowField()

I've downloaded the client_secrets.json file directly from the Google Dev Console. The specified Client ID type in the Dev Console is "web application", which I think is correct. What I've noticed is, if I remove the token validation code block:

if not xsrfutil.validate_token(
        settings.SECRET_KEY, request.REQUEST['state'], request.user):
    return HttpResponseBadRequest()

everything works correctly, flow and credentials get correctly stored in the database and I'm allowed to read the calendar. What can I possibly be wrong with?

EDIT: I've also checked outgoing (to Google) and incoming (to callback) data:

OUTGOING:

request.user:
admin
settings.SECRET_KEY:
I_AM_NOT_WRITING_IT_HERE
FLOW.params['state']:
SOME_OTHER_RANDOM_STUFF

INCOMING:

request.user:
admin
settings.SECRET_KEY:
I_AM_NOT_WRITING_IT_HERE
FLOW.params['state']:
SOME_OTHER_RANDOM_STUFF

Data is identical, at least to a print to console. Also, the generation/validation operations via console work correctly (xsrfutil.validate_token returns True, both with test and real data, including User model instances). I'm even more puzzled.


Source: (StackOverflow)

User Registration & Login | SSO using Spring Security OAuth 2.0

I am trying to implement user registration and log in flow | SSO using Spring Security Oauth 2.0 and Google as the authentication provider.

  • How should I initiate registration and login flow? What filter needs to be applied?
  • In registration flow, I will needs user's details (name, email) that are part of successful authorization response, to be persisted in my local database. How do I handle that?

  • What's the purpose of oauth2:client id="oauth2ClientFilter" ?

This is how my application context file looks like:-

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:c="http://www.springframework.org/schema/c"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:oauth2="http://www.springframework.org/schema/security/oauth2"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc  http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
    http://www.springframework.org/schema/security/oauth2 http://www.springframework.org/schema/security/spring-security-oauth2.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing 
    infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
    up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
    in the /WEB-INF/views directory -->
<beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<context:component-scan base-package="com.samsoft.spring" />

<!-- ================================================== SECURITY START ================================================== -->

<security:http security="none" pattern="/" />
<security:http security="none" pattern="/resources/**" />
<security:global-method-security
    secured-annotations="enabled" />

<security:http auto-config="true">
    <security:intercept-url pattern="/**"
        requires-channel="https" access="IS_AUTHENTICATED_FULLY" />
    <security:custom-filter ref="oauth2ClientFilter"
        after="EXCEPTION_TRANSLATION_FILTER" />
</security:http>
<oauth2:client id="oauth2ClientFilter" />

<oauth2:resource id="googleOauth2Resource" type="authorization_code"
    client-id="530420474177-clientid.apps.googleusercontent.com"
    client-secret="client-secret-here" access-token-uri="https://accounts.google.com/o/oauth2/token"
    user-authorization-uri="https://accounts.google.com/o/oauth2/auth"
    scope="https://www.googleapis.com/auth/calendar"
    client-authentication-scheme="form"
    pre-established-redirect-uri="https://ohad.sealdoc.com/oauth2-client/hello" />

<oauth2:rest-template id="googleOauthRestTemplate"
    resource="googleOauth2Resource" />

<security:authentication-manager>
    <security:authentication-provider>
        <security:user-service>
            <security:user name="test" authorities="ROLE_USER" password="test"/>
        </security:user-service>
    </security:authentication-provider>
</security:authentication-manager>



<!-- ================================================== SECURITY END ================================================== -->

EDIT

I did implemented same use case using Spring Security OpenID by:-

  1. Declaring openid:form tag with exchange attributed configured
  2. Extend the UserDetailsService as described here.

I am looking for equivalent configuration for Oauth 2.0.


Source: (StackOverflow)

got 'invalid_grant' in oauth2 SignedJwtAssertionCredentials

I am trying to make an oauth2 access_token in a server-to-server JSON API scenario. But it failed with invalid_grant error, please help.

from oauth2client.client import SignedJwtAssertionCredentials

KEY_FILE = 'xxxxxxxxxxxx-privatekey.p12'

with open(KEY_FILE, 'r') as fd:
    key = fd.read()

SERVICE_ACCOUNT_EMAIL = 'xxxxxx.apps.googleusercontent.com'

credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
      scope="https://www.googleapis.com/auth/datastore https://www.googleapis.com/auth/userinfo.email",
      token_uri='https://accounts.google.com/o/oauth2/token')


assertion = credentials._generate_assertion()

h = httplib2.Http()
credentials._do_refresh_request(h.request)

and I got

Traceback (most recent call last):
  File "/Users/pahud/Projects/oauth2client/x.py", line 24, in <module>
    credentials._do_refresh_request(h.request)
  File "/Users/pahud/Projects/oauth2client/oauth2client/client.py", line 710, in _do_refresh_request
    raise AccessTokenRefreshError(error_msg)
oauth2client.client.AccessTokenRefreshError: invalid_grant
[Finished in 0.7s with exit code 1]

http://i.stack.imgur.com/iGGYx.png


Source: (StackOverflow)

is there a deep dive on google's oauth2 scopes?

I'm looking for some deep down detailed information on google's use of oauth scopes

My Drive app is working, so I get the simple use of scopes. However I have the following detailed questions/issues..

  1. I specify scopes twice. Once in my app and then also in the API Console. What is the respective significance of these two scope declarations?
  2. If I remove scopes, must my user re-authorise my app, or is this only required for adding additional scopes?
  3. If the answer to 2, is 'I can't silently remove scopes', will the Google libraries deal gracefully with re-authorising the user, or will I just get 403 failures? I've read How should an application add/remove scopes to an existing grant? but the accepted answer specifically references adding scopes, whereas my question is about removing scopes.
  4. Can different modules within my app request different scopes within the superset specified in the API console? To explain, my app has 3 components: a chrome extension accessing Drive, a web client using JS to access Drive and YouTube (in online mode), and a server component which accesses Drive (in offline mode)..
  5. Can my app. enquire what scopes it has been granted?

A general question, I'm sure I face the same dilemma as many app authors. If I increase functionality (a good thing since it attracts users), I also need to increase permissions/trust a user places in my app (a bad thing since it repels users). Are there any recommendations on how apps should best handle this conflict of interests?


Source: (StackOverflow)

How to share an Access Token between an MVC 5 web application and Web API 2 application

In this instance I am having the user log into the (MVC 5) Web application, which then acts as proxy to log into the (Web API 2) API (using basic over SSL) and return a Bearer/Access Token. I'm using the Thinktecture.IdentityModel.Client.OAuth2Client to handle the login and get the access token, which all works fine.

Some other stuff happens but now I want the Web application to be able to decode the Access Token to access the claims set on the API (specifically the user ID returned after login to the API).

I'm using the much demoed, UseOAuthAuthorizationServer and UseOAuthBearerAuthentication extension methods with a token endpoint pretty much out of the box but with a custom OAuthAuthorizationServerOptions.Provider to access my own repository.

I have the same MachineKey on both applications, but I am unclear how to decode the token , although I understand I would probably have to use the SecureDataFormat.Unprotect method.

The closest attempt I have in the Web application is:

Task<TokenResponse> response = client.RequestResourceOwnerPasswordAsync(model.Email, model.Password);

IDataProtector dataProtecter = Startup.DataProtectionProvider.Create("does this matter?");
TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtecter);
AuthenticationTicket ticket = ticketDataFormat.Unprotect(response.Result.AccessToken);

With the Startup.DataProtectionProvider set as follows:

public partial class Startup
{
    internal static IDataProtectionProvider DataProtectionProvider { get; private set; }

    public void Configuration(IAppBuilder app)
    {
        DataProtectionProvider = app.GetDataProtectionProvider();
        this.ConfigureAuth(app);
    }
}

My fall back plan is to offer an API method that returns the information I am interested in after login, but it seems excessive seeing as it forms part of the claims in the token (as I understand it).

I have tried to wrap my head around JWT (I've looked at Thinktecture, Microsoft source code and various other forums), but not sure if that would help (although claims being available in plain text us useful). I have yet to find an example that allows sign in with basic authentication and returns a custom JWT containing an access token.

Anyway I hope thats enoguh information and any help would be much appreciated... cheers


Source: (StackOverflow)

Spring security Oauth2 client ClientAuthenticationProcessingFilter

I'm working on spring-security-oauth2-1.0.3.RELEASE, trying to set up an oauth client to get user authenticated with google.

I spent quit a while on this and still don't find much good article explaining very clearly.

What I'm doing is to put an OAuth2ClientAuthenticationProcessingFilter into the filter chain like this:

<http xmlns="http://www.springframework.org/schema/security"
    use-expressions="true" pattern="/oauth.html" auto-config="true">
    <sec:intercept-url pattern="/**" access="isFullyAuthenticated()" />
    <custom-filter ref="oauth2ClientFilter" position="CAS_FILTER" />
    <sec:custom-filter ref="googleAuthFilter" after="CAS_FILTER" />
</http>

A custom-filter: googleAuthFilter is there to protect my URL.

Reading the source code of OAuth2ClientAuthenticationProcessingFilter, it requires a reference to

  1. an OAuth2RestOperations (rest template) which refers to an Oauth server resource (information about google)
  2. ResourceServerTokenServices (from Spring-security-oauth libary provider packages).

Now I'm confused. Spring-security-oauth is divided into 2 parts: client and provider.

Since I'm just setting up an Oauth client, why do I need to have a reference of a class from Oauth provider packages?

Also, How should I set up the ResourceServerTokenServices? Now I'm trying to use the defualt implementaiton. Because DefaultTokenServices again requires reference to

  1. TokenStore
  2. ClientDetailsService
  3. TokenEnhancer

So far I tried all the default implementations:

  • TokenStore: InMemoryTokenStore
  • ClientDetailsService: InMemoryClientDetailsService
  • TokenEnhancer: TokenEnhancerChain

and it seems not to work...

Thanks!


Source: (StackOverflow)

Please confirm: SignedJwtAssertionCredentials only works with SpreadsheetsClient, not SpreadsheetsService?

After a week of Googling and trial & error, I finally got my Python script that adds a row to a Google spreadsheet to work with OAuth2. For the benefit of others who may suffer the same trauma, here's my working code:

script_dir  = os.path.dirname(os.path.realpath (sys.argv[0]))
private_key = open(script_dir + "\\myClient.pem").read()
ssClient    = gdata.spreadsheets.client.SpreadsheetsClient()

credentials = SignedJwtAssertionCredentials(CLIENT_EMAIL, private_key, SCOPE)
http        = Http()
http        = credentials.authorize(http)
auth2token  = gdata.gauth.OAuth2TokenFromCredentials(credentials)
ssClient    = auth2token.authorize(ssClient)

ssClient.GetSpreadsheets()

Two notes:

  1. This does NOT work if I use gdata.spreadsheet.service.SpreadsheetsService(), but does work with gdata.spreadsheets.client.SpreadsheetsClient()
  2. This does NOT work using the .p12 files downloaded from the Google Developer Console, I needed to convert it to a .pem file with:

    openssl pkcs12 -nodes -nocerts -in myClient.p12 -out myClient.pem
    

Could someone please confirm that there is indeed no way to use SignedJwtAssertionCredentials with SpreadsheetsService, or if there is, please explain the correct procedure? I've pretty much tried every combination I could think of.

Thanks!


Source: (StackOverflow)

How to obtain oauth 2.0 token from google plus api in android?

I have a problem with obtaining oauth 2.0 token from google API. I am currently writing app for android, where I want to have three methods of signing in - via facebook (done), via custom oauth 2.0 provider (also done) and via google plus - it makes many problems for me. I need to get access token on the device, and pass it further to backend application.

I tried using GoogleApiClient (PlusClient is deprecated - via http://developer.android.com/reference/com/google/android/gms/plus/PlusClient.html), but cannot see a method like getAccessToken or something similar.

Currently i try to use socialauth library, but I'm stuck due to lack of documentation (here is some code)

private SocialAuthAdapter mSocialAdapter;
... in onCreate()
mSocialAdapter = new SocialAuthAdapter(new GooglePlusSocialAuthListener());
try {
    mSocialAdapter.addConfig(Provider.GOOGLEPLUS, key_from_google_developers_console, secret, 
    "https://www.googleapis.com/auth/userinfo.profile+https://www.googleapis.com/auth/userinfo.email");
    mSocialAdapter.addCallBack(Provider.GOOGLEPLUS, 
   "http://localhost:3000/api/auth/gplus/callback");
}
catch (Exception e) {
   e.printStackTrace();
}

mSocialAdapter.authorize(LoginActivity.this, Provider.GOOGLEPLUS);
Log.e("TOKEN HERE ", mSocialAdapter.getCurrentProvider().getAccessGrant().getKey());

Can anybody help me to get this token? It doesn't matter if it is via socialauth or via GoogleApiClient.


Source: (StackOverflow)

Google App Engine - Endpoints API - Consuming from another App Engine App -python

I am trying to execute a function provided by one app engine app that I have written (python) that uses Endpoints, in a second similar app engine app.

I currently have both app engine applications running on appspot using endpoints with oauth2. I have a working javascript client that consumes the endpoint, executes the functions with authorization and authentication. So I know the backend app engine servers are working and are a properly exposed endpoint. I can also browse the API using the api explorer and the discovery service.

Since this is a server to server link, I think that Service Accounts are what I want to use for the oauth2 authentication. So I created the Service account in the client app on the app engine console.

Here is the code that runs on the caller:

f = file('key2.pem', 'rb')
key = f.read()
f.close()

credentials = SignedJwtAssertionCredentials(
     'my-service-account-email-from-caller-app@developer.gserviceaccount.com',
      key,
      scope='https://my-app-id.appspot.com/_ah/api/my-api/v1')
http = credentials.authorize(httplib2.Http())
service = build("my-api", "v1", http=http)

When I run this code, I get an error: AccessTokenRefreshError: invalid_grant

I have tried many other things, adding a developerKey or a discoveryUrl parameter to the credentials, still invalid grant. I looked at other people who have seen this error and have tried messing with the clocks, although this is a server to server call so I don't think that is the problem. I have added the caller's service account email address to the permissions of the callee app.

I have not found a sample app or a post about using service accounts to call a custom Endpoints API, only to call Google APIs such as Youtube or Plus, most of which have a method for registering a calling app engine application.

Has anyone been able to call an endpoint api function on one app engine application with another app engine application using oauth2?

Thanks in advance, -mat


Source: (StackOverflow)

What is the OAuth scope for the Google Translation API?

Surely someone else is using the API, I've looked and searched, I cannot seem to find the correct value to place for the scope parameter when authenticating:

I've looked at all these scope lists, nothing, tried the OAuth 2.0 playground, translation is not there.

oauth playground v1

oauth playground v2

oath supported scopes

auth scopes

Any clues welcomed, thank you.

Error message:

Error: invalid_request

Missing required parameter: scope

Learn more
Request Details

Update

User Ezra explained that OAuth2 authentication is not needed for the Translation API.

I got down this road by this path:

I was trying to make the sample code here work:

translation api sample code

And didn't have the apiclient.discovery module

from apiclient.discovery import build

I went off looking for that which landed me here to this quick-start configurator which gave me an autogenerated translation api project here:

This starter project which is supposed to be tailored for Translation API includes a whole bunch of OAuth configuration and so I wound up asking the question because of the error mentioned here

 exception calling translation api: <HttpError 400 when requesting    https://www.googleapis.com/language/translate/v2?q=zebra&source=en&alt=json&target=fr&key=MYSECRETKEYWENTHERE returned "Bad Request">

The code I'm using to make said call which errors out in this way is:

   service = build('translate', 'v2',
        developerKey='MYSECRETKEYWENTHERE')
result = service.translations().list(
  source='en',
  target=lang,
  q='zebra'
).execute()

If I make the same call directly that the error complains about, it works ok

https://www.googleapis.com/language/translate/v2?key=MYSECRETKEYWENTHERE&q=zebra&target=fr&alt=json&source=en

Updated Again

Okay, I removed all the OAuth code from the sample project and then ran it again and then finally noticed that I had a typo in my secret key... donk

Thanks for the answers!

.

Thank you


Source: (StackOverflow)

oauth2client Credentials refresh_token becomes null

Backgound

  1. I got access_token to Google API using the google-api-python-client django_sample.
  2. To have offline access, I've added FLOW.params['access_type'] = 'offline'.
  3. Stored credentials_json = credentials.to_json(). It contains a refresh_token.
  4. Restored the credentials Credentials.new_from_json(credentials_json).
  5. Used this credentials to gain access by credentials.authorize(http).
  6. Worked perfectly =)

The problem

  1. I did the the same every 5 minutes.
  2. In each iteration I stored the credentials and printed it.
  3. After 1 hour and 45 minutes, the "refresh_token" became null.
  4. At this point the code stopped working =(

My questions

  1. Does Credentials class refresh it's token automatically?
  2. If not, at what point of should I call credentials.refresh(http)?

Thanks!


Source: (StackOverflow)

Facebook OAuth redirect_uri isn't an absolute URI. Check RFC 3986.\",\"type\":\"OAuthException\",\"code\":191

I've been struggling this afternoon to put my application using facebook oauth. I am getting an error while trying to get the access token: {\"error\":{\"message\":\"redirect_uri isn't an absolute URI. Check RFC 3986.\",\"type\":\"OAuthException\",\"code\":191}}

Here is my resquest: provider_%253dfacebook%2526_sid_%253d19cdb2fdc733479fa3c2df14531064a7">https://graph.facebook.com/oauth/access_token?code=AQD0Ojpio6TXsVZ1wgtMNoAl7G2HQ8b5Yk0IhfgYxom0ALWdGceeE3BEsBJfrQQYIYDiCaxAvkW_vJNOM1xk7PVUgWC9SwnJCFl408K9ZJMhiz9ypQwHbsfo_oX11WsCin3o0PzZ7bpnlTrqIF59O04mqCPLucnMThohvIPL63tWz9H9yeCx3k0POpjOkNgfu0Sk-rRMxfGynJJRGUKd3ziLjA1IVqFSsuIoCAurYReeoufMsBWw-naCknQ5vQvasbb06pifg31tz6qekMaMcB6FWP1Wo2U4XKMrlobzs7fIksrV-OFgo5jC8go3X0v5EKU&client_id=XXXXX&client_secret=XXXX&redirect_uri=http%253a%252f%252flocalhost%252fMySite.Web%252fAccount%252fExternalLoginCallback%253fReturnUrl%253d%252fMySite.Web%252fAbout%252fIndex%2526_provider_%253dfacebook%2526_sid_%253d19cdb2fdc733479fa3c2df14531064a7

I appreciate any help. Thanks in advance


Source: (StackOverflow)

The signing fingerprint you specified is already used by another Android OAuth2 client

Some time ago I created an example project (lets call it "example project") with Oauth2 client id for android application in Google APIs console. I also added SHA1 fingerprint and package name (for example com.package.name).

My mistake was that an application with same package name already existed. Now I need to create an Oauth2 client id for android application in the "valid project" with package name com.package.name and with SHA1 fingerprint which I added before. Obviously when I tried to add this fingerprint I got an error.

The signing fingerprint you specified is already used by another Android OAuth2 client.

After that I remembered about "example project" and deleted client id from this project. The problem is that I still not able to add this fingerprint for package name com.package.name. Client id is deleted but still I have the same error as above.

So do I have a possibility to use this fingerprint for the same package name in another project?


Source: (StackOverflow)