Does anyone know how to use 2-legged OAuth with google-api-java-client?
I'm trying to access the Google Apps Provisioning API to get the list of users for a particular domain.
The following does not work
HttpTransport transport = GoogleTransport.create();
GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders;
headers.setApplicationName(APPLICATION_NAME);
headers.gdataVersion = GDATA_VERSION;
OAuthHmacSigner signer = new OAuthHmacSigner();
signer.clientSharedSecret = CONSUMER_SECRET;
OAuthParameters oauthParameters = new OAuthParameters();
oauthParameters.version = OAUTH_VERSION;
oauthParameters.consumerKey = CONSUMER_KEY;
oauthParameters.signer = signer;
oauthParameters.signRequestsUsingAuthorizationHeader(transport);
I get the "com.google.api.client.http.HttpResponseException: 401 Unknown authorization header".
The header looks something like this
OAuth oauth_consumer_key="...", oauth_nonce="...", oauth_signature="...", oauth_signature_method="HMAC-SHA1", oauth_timestamp="...", oauth_version="1.0"
I also tried following without success
GoogleOAuthDomainWideDelegation delegation = new GoogleOAuthDomainWideDelegation();
delegation.requestorId = REQUESTOR_ID;
delegation.signRequests(transport, oauthParameters);
Any ideas?
Thanks in advance.
It seems that there was nothing wrong with the code. It actually works.
The problem was with the our Google Apps setup.
When you visit the "Manage OAuth key and secret for this domain" page (https://www.google.com/a/cpanel/YOUR-DOMAIN/SetupOAuth),
and enable "Two-legged OAuth access control" and select
"Allow access to all APIs", it doesn't actually allow access to all APIs.
If you visit the "Manage API client access" page after that
(https://www.google.com/a/cpanel/YOUR-DOMAIN/ManageOauthClients),
you'll see that there is an entry like:
YOR-DOMAIN/CONSUMER-KEY "This client has access to all APIs"
It seems that this doesn't include Provisioning API.
Only after we explicitly added the Provisioning API, the code started to work.
So to enable Provisioning API, you should also have something like the following entry in your list:
YOR-DOMAIN/CONSUMER-KEY Groups Provisioning (Read only) https://apps-apis.google.com/a/feeds/group/#readonly
User Provisioning (Read only) https://apps-apis.google.com/a/feeds/user/#readonly
Somone else had the same problem:
http://www.gnegg.ch/2010/06/google-apps-provisioning-two-legged-oauth/
Sasa
Presumably you are trying to get an unauthorised request token here? I Haven't used the Google implementation, but the OAuth 1.0a spec says you need a callback URL, which you don't have. This might be a red herring as the spec says a missing param should return HTTP code 400 not 401.
See http://oauth.net/core/1.0a/#auth_step1
Related
My Guidelines
If followed this Google documentation about verifying Google-Account-Tokens on the server side, but I am kinda confused.
My Problem
GoogleIdTokenVerifier googleIdTokenVerifier = new GoogleIdTokenVerifier.Builder(new NetHttpTransport(), new JacksonFactory())
.setAudience(Collections.singletonList(CLIENT_ID))
.build();
In this piece of code I figured out that the transport and jsonFactory arguments can be filled as new NetHttpTransport() and new JacksonFactory() here. It also describes how to get AudienceString, but I couldn't figure out what it is for. I couldn't test it, but my question is if I can use it without .setAudience() or if I need it and what it is for.
In .setAudience() you have to pass all client ID's. You can get the ID for your client from the Credentials Page. It's explained here.
Thanks to #StevenSoneff.
If you didn't get the basic concept
For every client you want your server to accept, you need to create a project in the `Developer Console`. Clients are differentiated by their `SHA-1` fingerprint. You can for example have a debug project (will take your debug fingerprint) and a release one. To make both work, you have to add both `ID`'s to your server's `GoogleIdTokenVerifier`'s `.setAudience()`.
In my case, If you're using Firebase to get the id token on Android or iOS. You should follow these instructions to verify it on your backend server.
Verify ID tokens using a third-party JWT library
For me, I'm using Google OAuth Client as the third-party library so it's easy to use.
But it's a little bit different from this document.
Verify the Google ID token on your server side
The CLIENT_ID is your firebase project ID.
The Issuer has to be set as https://securetoken.google.com/<projectId>.
You need to use GooglePublicKeysManager and call setPublicCertsEncodedUrl to set it as https://www.googleapis.com/robot/v1/metadata/x509/securetoken#system.gserviceaccount.com
GooglePublicKeysManager manager = new GooglePublicKeysManager.Builder(HTTP_TRANSPORT, JSON_FACTORY)
.setPublicCertsEncodedUrl(PUBLIC_KEY_URL)
.build();
GoogleIdTokenVerifier verifier = new GoogleIdTokenVerifier.Builder(manager)
.setAudience(Collections.singletonList(FIREBASE_PROJECT_ID))
.setIssuer(ISSUER)
.build();
If you have multiple issuers, then you have to create GoogleIdTokenVerifier for each one.
I have a dot net application that call a java web service. I am trying to implement authentication by passing credentials to the java service. Here is the dot net code setting the credentials. How can I get these credentials in my java application? They aren't set in the headers...
System.Net.NetworkCredential serviceCredentials = new NetworkCredential("user", "pass");
serviceInstance.Credentials = serviceCredentials;
serviceInstance is an instance of SoapHttpClientProtocol.
I've tried injecting the WebServiceContext like so
#Resource
WebServiceContext wsctx;
and pulling the crentials from the headers but they aren't there.
You are not passing the credentials to your service the correct way. In order to get the Authorize http request header do the following:
// Create the network credentials and assign
// them to the service credentials
NetworkCredential netCredential = new NetworkCredential("user", "pass");
Uri uri = new Uri(serviceInstance.Url);
ICredentials credentials = netCredential.GetCredential(uri, "Basic");
serviceInstance.Credentials = credentials;
// Be sure to set PreAuthenticate to true or else
// authentication will not be sent.
serviceInstance.PreAuthenticate = true;
Note: Be sure to set PreAuthenticate to true or else authentication will not be sent.
see this article for more information.
I had to dig-up some old code for this one :)
Update:
After inspecting the request/response headers using fiddler as suggested in the comments below a WWW-Authenticate header was missing at the Java Web Service side.
A more elegant way of implementing "JAX-WS Basic authentication" can be found in this article here using a SoapHeaderInterceptor (Apache CXF Interceptors)
I'm trying to use the Google Drive API through the App Identity interface provided with Google App Engine. This basically allows my web application to communicate with Google's APIs from server to server.
I don't need my users to login, I simply need to display my own Google Drive documents.
However, after I set all the appropriate values and scopes, and enable all the right Google Drive knobs on the console page, I still get this for a simple GET request to https://www.googleapis.com/drive/v2/files:
{ "error": { "errors": [ { "domain": "usageLimits", "reason": "dailyLimitExceededUnreg", "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.", "extendedHelp": "https://code.google.com/apis/console" } ], "code": 403, "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." }}
What's wrong? What am I missing? Here's the code that actually does the request - funny thing is that it works great if I use other APIs such as the URL shortener API:
var scopes = new java.util.ArrayList();
scopes.add("https://www.googleapis.com/auth/drive");
var appIdentity = AppIdentityServiceFactory.getAppIdentityService();
var accessToken = appIdentity.getAccessToken(scopes);
var url = new URL("https://www.googleapis.com/drive/v2/files");
var connection = url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET");
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Authorization", "OAuth " + accessToken.getAccessToken());
EDIT
If I simply change the API to use the urlshortner API for example, it works:
var url = new URL("https://www.googleapis.com/urlshortener/v1/url/history");
And output:
{ "kind": "urlshortener#urlHistory", "totalItems": 0, "itemsPerPage": 30}
So there must be something not working with Google Drive and App Identity?
EDIT 2
I've found some help from the correct answer here: https://stackoverflow.com/a/12526286/50394
But it's talking about setting Client API scopes on Google Apps, and I'm not using Google Apps, I'm simply using Google App Engine's domain foo.appspot.com
The 403 error you are getting means that there was no Authorization header in your GET. The logic is that without an Authorization header, you are anonymous (you are legion blah blah :-)). The Drive quota for anonymous use is zero, hence the message. URL shortener has a higher quota for anonymous so it works.
I suggest you change the URL to point to an http server of your own, and check what headers you are actually sending.
AFAICT you should be using Bearer in the Authorization header.
Probably what's happening is, Drive API doesn't recognize the service account (because of the wrong header?) and thus taking it as an anonymous request since no key parameter wasn't provided either (see common query params).
Try this:
connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());
Or you could try adding the token as access_token query param.
I think you should at least setup an API console entry with Drive API enabled at https://code.google.com/apis/console
Once you create this you'll get an ID you can use in your GoogleCredential object. From the GoogleCredential object you can get the access token which you can than add to your request.
What I read here (Google drive via service accounts) was that you use a slightly different style that uses an API KEY that you retrieve from the Developer Console.
The pertinent parts for me were to generate a "Key for Server Applications", then use this technique, which I hadn't read anywhere else!
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
AppIdentityCredential credential =
new AppIdentityCredential.Builder(DriveScopes.DRIVE).build();
// API_KEY is from the Google Console as a server API key
GoogleClientRequestInitializer keyInitializer =
new CommonGoogleClientRequestInitializer(API_KEY);
Drive service = new Drive.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential)
.setGoogleClientRequestInitializer(keyInitializer)
.build();
This answer claims that:
Service Accounts are not supported by the Drive SDK due to its
security model.
If that's still true, one workaround is to perform a regular OAuth dance once with a regular Google Account, and persist the access and refresh token in the datastore.
I'm using scribe for making an app that has oauth support. I didn't found problems With Twitter, but when using facebook I have problems...
This is the code that works on twitter oauth
OAuthService s = /* ... Facebook oauth init ... */
final Token requestToken = s.getRequestToken();
final String authURL = s.getAuthorizationUrl(requestToken);
It gives me an error at the second line:
12-20 10:01:31.475: E/AndroidRuntime(5405): java.lang.UnsupportedOperationException: Unsupported operation, please use 'getAuthorizationUrl' and redirect your users there
12-20 10:01:31.475: E/AndroidRuntime(5405): at org.scribe.oauth.OAuth20ServiceImpl.getRequestToken(OAuth20ServiceImpl.java:45)
I know that it says that I might use getAuthorizationUrl... But I have to pass a requestToken...
Could you please help me?
It would be helpful any example with Scribe and Facebook
Thanks!
PS: Same problem with Windows Live ! =(
EDIT:
I have been looking at the source code of the Scribe library and I found something
https://github.com/fernandezpablo85/scribe-java/blob/master/src/main/java/org/scribe/oauth/OAuth20ServiceImpl.java
Here we can see that I can call the getAuthorizationUrl(...) with null parameter because it doesn't use it.... But I think the prioblem now is that the config isn't filled...
here is how I initialize facebook service:
new ServiceBuilder()
.provider(FacebookApi.class)
.apiKey(....)
.apiSecret(....)
.scope("email,offline_access")
.callback("oauth://facebook")
.build();
Is this correct?
Thanks!
private static final Token EMPTY_TOKEN = null;
OAuthService service = new ServiceBuilder()
.provider(FacebookApi.class)
.apiKey(apiKey)
.apiSecret(apiSecret)
.callback("http://www.example.com/oauth_callback/")
.build();
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
All you now need to redirect user to this URL and let him verify them self to get code from facebok.
There are a good amount of example with very good documentation for almost all major Oath
system
here is for Facebook
FacebookExample
For all major providers
Scribe Example Directory
Edit
After looking at the discussion my suggestion is to get a full understanding about Oauth1 and Oauth2.
You've got it all wrong. OAuth 2 Protocol never returns a request token like OAuth 1.
Oauth 1 does an HTTP POST request and returns an unauthorized request token. Then, you will have to authorize your unauthorized token to receive an authorized token (That's 2 HTTP call).
Oauth 2, on the other hand, doesn't have a request token flow, you will need to do an HTTP GET for an authorization token (1 HTTP call only). Hence why Scribe says that you need to call getAuthorizedUrl.
See this Facebook Example, to see how to retrieve an authorized token using OAuth 2.
I have been trying this for quite a while now. I am able to fetch the request token no problem. But when i try to exchange it for the access token I get the following error:
2011-07-17 22:19:19,649 [http-8080-1] ERROR oauth.OauthService -
Unable to fetch access token! (consumerName=google,
requestToken=[key:4/Azm6wQDW85iYVmeb4ogCAl70D_89,
secret:Zrh9saEDJcgCo83QejOu28sU,
authUrl:https://www.google.com/accounts/OAuthAuthorizeToken?oauth_token=4%2FAzm6wQDW85iYVmeb4ogCAl70D_89,
isOAuth10a:true])
oauth.signpost.exception.OAuthCommunicationException: Communication
with the service provider failed: Service provider responded in error:
400 (Bad Request
Here is the code in the controller:
def OauthService
if (session.oauthToken == null) {
flash.message = "The token could no be retrieved... Please try again"
redirect(uri:"/")
}
def requestToken = OauthService.fetchRequestToken('google')
def accessToken = OauthService.fetchAccessToken('google', requestToken)
I have been playing about with it but it never seems to work any way I do it. Has anybody got any ideas?
If you look at the OAuth plugin docs, it mentions that some Google APIs require the scope attribute to be set in the OAuth config (in Config.groovy). Might be worth double-checking, considering the Google server is returning 400 Bad Request.
Also, enabling debug logging for the grails.app.service.org.grails.plugins.oauth and grails.app.controller.org.grails.plugins.oauth packages might provide some more clues.