How to pass the credential to Translation API v3? - java

I am using Google Cloud Translate v3 API Java Client. The Java Client code samples work great. The authentication of the code samples is done using the GOOGLE_APPLICATION_CREDENTIALS environment variable.
I need to develop code that will run in an application server that I have no control over the environment variables. So I need to use another way to get the call authenticated.
Setting Up Authentication for Server to Server Production Applications, under "Passing the path to the service account key in code" has a code sample (choose the JAVA tab) that works for the Storage service, but I can't find a similar way to pass the GoogleCredentials to Translation v3 API Java Client. Does anyone know?
Also, I can't find the Java doc for v3 API. https://googleapis.dev/java/google-cloud-clients/latest/index.html shows version "0.119.0-alpha" and it does not list the package com.google.cloud.translate.v3. Is there a separate java doc page ?

I think I found a solution.
The client API javadoc doesn't list com.google.cloud.translate.v3 but it does list com.google.cloud.translate.v3beta1. In the javadoc for TranslationServiceClient, i.e. https://googleapis.dev/java/google-cloud-clients/latest/com/google/cloud/translate/v3beta1/TranslationServiceClient.html
there's a mention of setting credential, and this method worked!
TranslationServiceSettings translationServiceSettings =
TranslationServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
.build();
TranslationServiceClient translationServiceClient =
TranslationServiceClient.create(translationServiceSettings);

Related

guide to use the MASL java SDK to authenticate user in azure function developed in java

Please help me to find out the documentation on how to use java MASL SDK to get access_token for a service principal.
I am looking to find the documentation or GIT links which can guide me how to use the MASL library including the code samples.
I have gone through this link but it does not help me much : https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows
And, I am not expecting code samples to be shared here. I just want to find out where to find such data. I am struggling a lot when it comes to finding the right knowledge with respect to azure learning. What am I missing here? Is there any azure reference link available to find such information at a centralized place?
Note that, based on your requirement you can make use of Authorization code Flow if you want the user to sign-in and authenticate and if you want to access API using Application then make use of Client Credential Flow.
I tried to reproduce the same in my environment and got the results like below:
I created an Azure AD Application and added API permission:
For Client-Credential Flow, refer this GitHub blog by siddhijain.
Use the MASL java SDK to authenticate user in azure function developed in java.
Assuming that you want to authenticate user, you can make use of Authorization code Flow to generate access token.
I generated the Authorization code by using below endpoint:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
&client_id=ClientID
&response_type=code
&redirect_uri=RedirectUri
&response_mode=query
&scope=https://management.azure.com/user_impersonation
&state=12345
A sign-in screen will appear for authenticating the user:
To generate the access token, I used below parameters:
https://login.microsoftonline.com/TenantID/oauth2/v2.0/token
client_id:ClientID
client_secret:ClientSecret
scope:https://management.azure.com/user_impersonation
grant_type:authorization_code
redirect_uri:RedirectUri
code:code
I am able to call the Function by using above generated access token:
To implement the above in MSAL Java library, refer the below GitHub Blogs:
Microsoft-authentication-library-for-js/msal-node/auth-code AzureAD by derisen
Microsoft-authentication-library-for-js/samples/msal-node AzureAD by rgins16

Unable to authenticate service account - Google Cloud

I'll premise that I've already googled and read the documentation before writing, I've noticed that it's a popular discussion here on StackOverflow as well, but none of the answers already given have helped me.
I created a Google Cloud account to use the API: Google Vision.
To do this I followed the steps of creating the project, adding the above API and finally creating a service account with a key.
I downloaded the key and put it in a folder in the java project on the PC.
Then, since it is a maven project I added the dependencies to the pom as described in the tutorials.
At this point I inserted the suggested piece of code to start using the API.
Everything seemed to be OK, everything was read, the various libraries/interfaces were imported.
But an error came up as soon as I tried to run the program:
The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials.
I must admit I didn't know what 'Google Compute Engine' was, but since there was an alternative and I had some credentials, I wanted to try and follow that.
So I follow the instructions:
After creating your service account, you need to download the service account key to your machine(s) where your application runs. You can either use the GOOGLE_APPLICATION_CREDENTIALS environment variable or write code to pass the service account key to the client library.
OK, I tried the first way, to pass the credentials via environment variable:
With powershell -> no response
$env:GOOGLE_APPLICATION_CREDENTIALS="my key path"
With cmd -> no response either
set GOOGLE_APPLICATION_CREDENTIALS=my key path
So I tried the second way, passing credentials using code and if I'm here something else must have gone wrong, in fact with what I have it was only possible to import io.grpc.Context, while everything else gives the error "Cannot resolve symbol ..".
import com.google.common.collect.Lists;
import io.grpc.Context;
import java.io.FileInputStream;
import java.io.IOException;
public class Main
{
static void authExplicit(String jsonPath)
{
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(jsonPath))
.createScoped( Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
Context.Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
System.out.println("Buckets:");
Page<Bucket> buckets = storage.list();
for (Bucket bucket : buckets.iterateAll()) {
System.out.println(bucket.toString());
}
}
public static void main(String[] args) throws IOException
{
OCR.detectText();
}
}
(I don't think I can upload a screen of the code to show where it gives me errors, however it is this)
PS: I also already installed the Cloud SDK and restarted the PC because some comments said to do that to fix things.
I also tried setting the environment variable manually, but nothing changes:
Solution
I don't know if it all worked out because of a series of operations I performed I for this one command line, anyway, for posterity's sake:
Fill in these fields manually using the email field in the json file and the path to the json file, both without inverted commas, then start cmd, paste the string and run!
gcloud auth activate-service-account your_account_email_id --key-file=json_file_path
It also helped me to reboot the PC afterwards.
Please, consider read the ImageAnnotationClient class level javadocs, it gives you the right guidance about how to accomplish the authentication process. I modified the provided code to give you the full example:
// Please, set the appropriate path to your JSON credentials file here
String credentialsPath = "...";
// The credentials could be loaded as well as this.getClass().getResourceAsStream(), for example
GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(credentialsPath))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
// Use that credentials to build your image annotation client
ImageAnnotatorSettings imageAnnotatorSettings =
ImageAnnotatorSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credentials))
.build()
;
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create(imageAnnotatorSettings);
// Perform the stuff you need to...
The only dependency you need to provide in your pom.xml is this:
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-vision</artifactId>
<version>2.0.18</version>
</dependency>
In any case, please, consider for reference the pom.xml provided in the Cloud Vision examples.
The Cloud Vision examples repository gives some useful code snippets as well in the Detect class for the detection process itself.
Be sure that the service account you are using to connect to Google Cloud has the necessary permissions.
Although this solution could work, it has the drawback that you probably need to store the credentials file somewhere in your machine, maybe in your source code repository, etcetera, and it can suppose a security risk. If your are running your program from Google Cloud is always advisable to grant to the VM or service you are using the necessary permissions and use the default application credentials.
The use of the GOOGLE_APPLICATION_CREDENTIALS could be preferable as well. If you are trying using this variable, initially, try configuring it using your IDE provided mechanisms instead of cmd, PS, or bash, and see if it works.
For using any of the two last mentioned solutions you don't need to provide any additional information when constructing your ImageAnnotatorClient:
ImageAnnotatorClient imageAnnotatorClient = ImageAnnotatorClient.create();
Your approach is correct.
To authenticate code, you should use a Service Account.
Google provides a useful mechanism called Application Default Credentials (ADCs). See finding credentials automatically. When you use ADCs, Google's SDKs use a predefined mechanism to try to authenticate as the Service Account:
Checking GOOGLE_APPLICATION_CREDENTIALS in your environment. As you've tried;
When running on a GCP service (e.g. Compute Engine) by looking for the service's (Service Account) credentials. With Compute Engine, this is done by checking the so-called Metadata service.
For #1, you can either use GOOGLE_APPLICATION_CREDENTIALS in the process' environment or you can manually load the file as you appear to be trying in your code.
That all said:
I don't see where GoogleCredentials is being imported by your code?
Did you grant the Service Account a suitable role (permissions) so that it can access any other GCP services that it needs?
You should be able to use this List objects example.
The link above, finding credentials automatically, show show to create a Service Account, assign it a role and export it.
You will want to perhaps start (for development!) with roles/storage.objectAdmin (see IAM roles for Cloud Storage) and refine before deployment.

How do I edit an Azure app registration from Java

I have a Java application that needs to update some fields of the manifest.json of an app registration in Azure.
I have already done this from the Linux terminal with the azure-cli tool. I then tried to google for a similar Java SDK to do this but only came up with SDKs that let you authenticate against Azure.
Is there another SDK for my use case or do I have to use some API directly via HTTP?
You can use Management SDK.
Sample code:
// skip this if you know the object id
ActiveDirectoryApplication app = azure.accessManagement().activeDirectoryApplications()
.getByName("<app_name>");
GraphRbacManagementClient client = azure.accessManagement().activeDirectoryApplications().manager().serviceClient();
client.getApplications().patch(
app.id(),
(ApplicationUpdateParameters) new ApplicationUpdateParameters()
.withGroupMembershipClaims(GroupMembershipClaimTypes.ALL));
It is a bit convoluted, because technically speaking AAD does not belong to Management. AAD is included in the SDK mainly for RBAC (role-based-access-control) for other resources.

Java Azure SB Connection with SAS token

ServiceBusConfiguration.configureWithSASAuthentication(config.getSbNamespace(), "RootManageSharedAccessKey", SAS_KEY, ".servicebus.windows.net");
ServiceBusContract service = ServiceBusService.create();
service.getTopic(topicID);
This code snippet is used to connect to Service Bus using SAS Key. I'm looking for possibility of connection with SAS token which looks like this:
SharedAccessSignature sr=https%3a%2f%2fmynamespace.servicebus.windows.net%2fMyTestQueue&sig=fFWmdMmWjsdTqPyhyvRS9LQqLjJNPc87xhInhYai9OM%3d&se=1453286209&skn=MyQueue_Listen
I receive 401 Unauthorized using this code. I don't have possibility to go back to SAS key. Does Azure SDK for Java support this? Is there different way to connect?
The ".servicebus.windows.net" looks a bit off (the . in the beginning).
FYI: There's an ASB Java client repository repository with issue tracker. You could check there as well.
It sounds like you want to use Azure Service Bus SDK for Java to do something like to get a topic via topic id, but you didn't know how to pass the shared access key to the method configureWithSASAuthentication.
I suggested that you need to follow the offical tutorial How to use Service Bus topics and subscriptions carefully to know how to get the shared access key for a service bus instance and to use it via SDK.
The SharedAccessSignature sr=https%3a%2f%2fmynamespace.servicebus.windows.net%2fMyTestQueue&sig=fFWmdMmWjsdTqPyhyvRS9LQqLjJNPc87xhInhYai9OM%3d&se=1453286209&skn=MyQueue_Listen that you were looking for is for calling the related REST APIs, not directly used in the code with SDK.
Hope it helps.

How to return Google Drive authorization code from browser window automatically using Java?

I'm attempting to create an application for both PC (Java) and Android that utilizes Google Drive. I've been messing around with the examples to figure out how OAuth 2.0 works, and I can't find a good method of automatically returning the authorization code to my program once the user has allowed the application to access their data. The Google Drive Quickstart example uses a simple copy/paste mechanism that requires user input, but this is not convenient for the user.
It seems there are several suggested ways to retrieve the authorization code without bothering the user (running a local web server, monitoring the browser window launched for authentication, etc...), but Google doesn't strongly recommend any solution nor do they provide examples of how these solutions would work beyond basic descriptions. The following guide gives a few suggestions in Section 4 (Note: I tried to quote the section but SO wouldn't let me with the number of links/images present):
https://developers.google.com/youtube/v3/guides/authentication#installed-apps
Has anybody implemented something similar in the past, or are there best practices to do this? If possible I'd prefer a solution that would work on multiple platforms (i.e. not using any platform specific libraries).
I suppose it's not a huge deal if the user had to do this once (as I'll be storing a refresh token and using that from then on), but it'd be good to have a way around it.
In Oauth2 protocol, you have two ways of getting the authorization code : via a redirect to an url you have control over (could be pointing to a serve you own or localhost) or via copy pasting.
The first way is what you want, presumably with localhost as redirect uri, as you lauch the flow from you desktop app on the user's machine. You'll have no choice but to make your app spawn a little http server that can handle the code url parameter. However, you'll have to be hackish : how do you launch a web browser from your app, for any OS it can run on ? how do you the case where the user's machine is configured to refuse inbound http connection ?
IMO, best course of action is to go for the copy pasting : user knows what happen
I just implemented an oAuth2 solution for Google Drive. I ended up creating a service account via Google App Engine. Here is a good link to get started:
https://developers.google.com/drive/service-accounts
There is a Dr. Edit example that will work you through editing drive objects like spreadsheets.
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(scopes)
.setServiceAccountPrivateKeyFromP12File(pk12)
.setServiceAccountUser(ACCESS_DOMAIN_IMPERSONATE) // <-- set user email here
.build();
There are a few things you need to do in your Google domain admin console/cpanel for your domain.
Check the following SO answer I posted a day or so ago:
OAuth Google API for Java unable to impersonate user

Categories

Resources