I'd like to create a Service Account so I'd be able to authenticate with it with my app.
All I found is this guide, but it doesn't say how to create such an account.
Can anyone assist?
Thanks
The docs aren't that clear but a Service Account == App. So if you create an app in the developer console and set authentication type to server authentication (jwt) and add your public key and get the app authorized in the admin console then you're ready to instantiate a service account with the following code:
String privateKey = new String(Files.readAllBytes(Paths.get(PRIVATE_KEY_FILE)));
JWTEncryptionPreferences encryptionPref = new JWTEncryptionPreferences();
encryptionPref.setPublicKeyID(PUBLIC_KEY_ID);
encryptionPref.setPrivateKey(privateKey);
encryptionPref.setPrivateKeyPassword(PRIVATE_KEY_PASSWORD);
encryptionPref.setEncryptionAlgorithm(EncryptionAlgorithm.RSA_SHA_256);
IAccessTokenCache accessTokenCache = new InMemoryLRUAccessTokenCache(MAX_CACHE_ENTRIES);
// BoxDeveloperAPIConnection == Service Account
BoxDeveloperEditionAPIConnection api = BoxDeveloperEditionAPIConnection.getAppEnterpriseConnection(ENTERPRISE_ID, CLIENT_ID, CLIENT_SECRET, encryptionPref, accessTokenCache);
Related
I'm trying to use Google as an IDP for my application by federation.
For user authentication part i'm using openID connect flow.
Following steps have been done already.
Created a Google application
Got client ID and client secret
Configured Google federation in my application (Login with google)
Authentication flow is successfully working
Token retrieved successfully
The problem is I want to add user roles to the user that already registered in google and fetch the user roles as a claim in token that is retrieve from the google.
Basically I want do add role based authentication to the application based on user roles.
So how to create and assign user roles to Google user, and how to fetch them as a claim in JWT token?
I am trying to access my emails through Gmail API (through AWS lambda), using service account credentials. I do not have a GSuite account, so I cannot delegate domain-wide authority and impersonate my user#gmail.com account.
I resorted to Service account authorization without OAuth, using a signed JWT directly as a bearer token. [see]: https://developers.google.com/identity/protocols/OAuth2ServiceAccount#jwt-auth
I also enabled all access to Gmail to the application and made service account an owner role in the console.
I am using google.auth.jwt module, but struggle to understand the documentation fully: [see docs]: https://google-auth.readthedocs.io/en/latest/reference/google.auth.jwt.html#module-google.auth.jwt
This is what I tried:
from googleapiclient.discovery import build
from httplib2 import Http
from google.auth import crypt
from google.auth import jwt
audience = 'https://mail.google.com/' ## full access scope
credentials = jwt.Credentials.from_service_account_file(
'credentials.json', audience=audience) # json credentials from api console - for service account
service = build('gmail', 'v1', credentials=credentials)
This gives me a 401 error:
googleapiclient.errors.HttpError: <HttpError 401 when requesting https://www.googleapis.com/gmail/v1/users/me/messages?alt=json returned "Invalid Credentials">
credentials object return appears as valid, with all necessary elements, however, I don't know how to make it "impersonate" my personal email.
Invalid credentails normally means that the credentials.json is not the correct type for the code you are using.
Make sure that you have downloaded the credentials.json for a service account.
Hi I'm trying to develop an for GSuite admin which enables to migrate their google drive data to another cloud service. But in the process of authentication i'm getting the below error.
{
"error": "unauthorized_client",
"error_description": "Client is unauthorized to retrieve access tokens using this method."
}
Below are the api's that are enabled in developer console.
1. Admin SDK
2. Contacts API
3. G Mail API
4. Calendar API
5. Drive API
Please guide me if done anything wrong in creating an app.
The main thing what i missed here is Authorizing my service account client ID with the GSUITE admin.
And I have been trying to generate access_token for the expired domain of mine.
After clearing all these i have to success in generating and getting user data.
This solution worked for me. I hope it works for you tooo....
Thank you community.
I created google app in developer console.
Enable Admin SDK
Enable API access
In "Manage OAuth Client access" i added "Authorized API client" with
"https://www.googleapis.com/auth/admin.directory.user" scope.
Further, i want to get users from my domain.
JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
ArrayList<String> scopeList = new ArrayList<>();
scopeList.add(DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY);
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("bla-bla#developer.gserviceaccount.com")
.setServiceAccountScopes(scopeList)
.setServiceAccountPrivateKeyFromP12File(new File("p12 file")))
.setServiceAccountUser("superadmin#my-domain.com")
.build();
credential.setAccessToken("access token of current google user");
Directory admin = new Directory.Builder(httpTransport, JSON_FACTORY, credential)
.setApplicationName("Capsidea")
.setHttpRequestInitializer(credential).build();
return admin.users().list().setDomain("my-domain.com").execute();
All it's working when i login into google via OAuth by superadmin#my-domain.com.
But when i logined by some-user-non-admin#my-domain.com i have the error:
"Not Authorized to access this resource/api"
Can an non admin user to get a list of all users in the domain?
When the domain change this code will work given that it is necessary to specify superadmin'a ?
Any ideas?
setServiceAccountUser needs a user capable of Admin API usage (there is a fine-grained role configuration tool).
Do state that such a user is needed for your code to work.
SOLUTION
I figured out how to solve this problem.
First of all here is my implementation with Service Account:
// Build service account credential.
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/appsmarketplace.license"))
.setServiceAccountPrivateKeyFromP12File(new File("/path/to/mykey/key.p12"))
// .setServiceAccountUser("NOT SET THIS LINE")
.build();
License build = new License.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("My Application").build();
Licenses execute = build.customerLicense().get("9999999999", "domain.test.com").execute();
This License Builder object is myself implementation based on the new google-api-client 1.17 and above. If someone could advice me how can i share with the rest of the community i will be glad to do it.
Best,
I have posted another thread, Google Apps Marketplace API customerLicense with OAuth2, explaining about my intentions to consume this API with OAuth2 Service Account strategy.
I have tried every method and officials library present and I always get Invalid OAuth header message or UNLICENSED
I am going to detail what is the scenery and what things i have tried:
I have and Google App Marketplace which use Service Account OAuth2 because all task are being perform on background.
This API Project has Service Account keys and Client Web Account keys too.
I published app restricted for my domain only because i am yet developing. So I installed App for my domain.
At this point it is suppose if I queried Customer License with API Project ID and Customer Id, which is domain name, I have to see the APP LICENSE for my domain.
I have used this jars https://developers.google.com/google-apps/marketplace/v2/developers_guide to access License API.
This is my code:
String appName = "MY APP";
AppsMarketService service = new AppsMarketService();
service.appId = "NUMBER_APP_ID";
service.appName = appName;
service.endpoint = "https://www.googleapis.com/appsmarket/v2/";
service.consumerKey = service.appId + ".apps.googleusercontent.com";
service.consumerSecret = "CLIENT_SECRET_FROM_WEB_OAUTH2_API_PROJECT";
service.authorize();
I get 403 forbidden if i use this code.
If i changed appId for prefix clientId from my API Project web OAuth2, I get 200 but with body UNLICENSED.
I have added scope to my app https://www.googleapis.com/auth/appsmarketplace.license and i still get the same result.
I have tried also getting Access Token from Admin user with Service Account handshake and then use that Oauth2 Access Token to access API License and the same result Invalid OAuth Token
My questions are:
Is there any way to access this API with Services Account keys, taking into consideration there is not consumer Secret in Service Accounts keys, only Client ID and private Key file?
Is there any updated library to use this with OAuth2 because i am seeing all this libraries are using OAuth1 with two-legged auth?
It would be great if someone can help me because we are trying to migrate our 7 Google App Old Marketplace Apps from OAuth1 to OAuth2 as per Google request but we have some black holes in our implementation if we would not be able to query what domains have our App Installed.
Best,
There is no need for any other libraries than OAuth2 lib. You can impmement this using urlfetch.
...
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.appengine.api.urlfetch.FetchOptions.Builder;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
...
String SERVICE_ACCOUNT_EMAIL = "...#developer.gserviceaccount.com";
String P12 = "...-privatekey.p12";
// appid is the same id that you have in the google cloud project that has the Google Apps Marketplace API and SDK enabled
String appid = "";
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/appsmarketplace.license"))
.setServiceAccountPrivateKeyFromP12File(new File(P12))
.build();
credential.refreshToken();
String token = credential.getAccessToken();
URL url = new URL("https://www.googleapis.com/appsmarket/v2/licenseNotification/"+appid);
HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, Builder.allowTruncate());
request.setHeader(new HTTPHeader("Authorization", "Bearer "+token));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
You need to install the OAuth2 package for this to work. In eclipse its under Google > Add Google Apis.