Google Admin SDK throws bad request java client - google-apps

I am trying to use the admin SDK using the java client. My requirement is for a server side application to manage the users without the explicit consent of the end user. I have followd the following steps.
I have create a service account is the Google API console.
Added the service account to the third party oauth access section the Google Apps admin console
Added the scopes for user, user.readonly for the same.
Created a super admin to be used as the service account user
I am using the java client as follows:
The same action is working in the api explorer using the service email to authenticate
HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JsonFactory JSON_FACTORY = new JacksonFactory();
GoogleCredential credential=null;
try {
credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId("xxx#developer.gserviceaccount.com")
.setServiceAccountScopes(DirectoryScopes.all())
.setServiceAccountPrivateKeyFromP12File(new File("/Users/xxx/Downloads/file-privatekey.p12"))
.setServiceAccountUser("xx#subdomain.domain.com") //Super admin account
.build();
} catch (GeneralSecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Directory directory = new Directory.Builder(HTTP_TRANSPORT,JSON_FACTORY,credential).setApplicationName("Sync Service").build();
try {
Directory.Users.List list = directory.users().list();
list.setDomain("subdomain.domain.com");
//list.setCustomer("xxx");
Users users = list.execute();
} catch (IOException e) {
e.printStackTrace();
}
I am getting the following error. Not sure why!
com.google.api.client.auth.oauth2.TokenResponseException: 400 Bad Request
{
"error" : "access_denied"
}
at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:269)
at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:858)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
at GappsClient.main(GappsClient.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Process finished with exit code 0

Have you add the client ID of your service account to Manage Third Party OAuth Access in your Cpanel?

I followed #Emily Lam answer and formed service account using old Google API console and i was able to get the expected result. Please let me know if anybody needs detailed steps i followed. Follow OAuth 2.0 client IDs part from below URL https://developers.google.com/console/help/#creatingdeletingprojects

Related

Cannot access https://dev.azure.com/<myOrg> Using TFS extended client version 15

We are migrating some code that used to run against an on premise TFS server but now needs to run against Azure DevOps (previously Team Services). The credentials I'm using have been validated to successfully authenticate to our DevOps organization instance, but running the following code after referencing the
Microsoft.TeamFoundationServer.ExtendedClient
NuGet package always results in TF30063: You are not authorized to access https://dev.azure.com/<myOrg> The code is posted below for authenticating via non-interactive authentication. Do I need to use a different authentication mechanism or different credentials type to get this working?
System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(_userName, DecryptedPassword, _domain);
try
{
// Create TeamFoundationServer object
_teamFoundationCollection = new TfsTeamProjectCollection(_serverUrl, networkCredential);
_teamFoundationCollection.Authenticate();
}
catch (Exception ex)
{
// Not authorized
throw new TeamFoundationServerException(ex.Message, ex.InnerException)
}
Since you want to use .Net Client Libraries, you could refer to the following link:
https://learn.microsoft.com/en-us/azure/devops/integrate/concepts/dotnet-client-libraries?view=azure-devops
Patterns for use:
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
const String c_collectionUri = "https://dev.azure.com/fabrikam";
const String c_projectName = "MyGreatProject";
const String c_repoName = "MyRepo";
// Interactively ask the user for credentials, caching them so the user isn't constantly prompted
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
// Connect to Azure DevOps Services
VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
// Get a GitHttpClient to talk to the Git endpoints
GitHttpClient gitClient = connection.GetClient<GitHttpClient>();
// Get data about a specific repository
var repo = gitClient.GetRepositoryAsync(c_projectName, c_repoName).Result;

GCP Pub/Sub throws "The Application Default Credentials are not available"

I am trying to publish to Google Pub/Sub topic using the following:
ProjectTopicName topicName = ProjectTopicName.of("my-project-id", "my-topic-id");
Publisher publisher = null;
try {
// Create a publisher instance with default settings bound to the topic
publisher = Publisher.newBuilder(topicName).build();
List<String> messages = Arrays.asList("first message", "second message");
for (final String message : messages) {
ByteString data = ByteString.copyFromUtf8(message);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
// Once published, returns a server-assigned message id (unique within the topic)
ApiFuture<String> future = publisher.publish(pubsubMessage);
// Add an asynchronous callback to handle success / failure
ApiFutures.addCallback(
future,
new ApiFutureCallback<String>() {
#Override
public void onFailure(Throwable throwable) {
if (throwable instanceof ApiException) {
ApiException apiException = ((ApiException) throwable);
// details on the API exception
System.out.println(apiException.getStatusCode().getCode());
System.out.println(apiException.isRetryable());
}
System.out.println("Error publishing message : " + message);
}
#Override
public void onSuccess(String messageId) {
// Once published, returns server-assigned message ids (unique within the topic)
System.out.println(messageId);
}
},
MoreExecutors.directExecutor());
}
} finally {
if (publisher != null) {
// When finished with the publisher, shutdown to free up resources.
publisher.shutdown();
publisher.awaitTermination(1, TimeUnit.MINUTES);
}
}
I have changed the default values you see here to the particulars of the account I am hitting.
The environment variable points to the JSON file containing the pub/sub authentication credentials:
GOOGLE_APPLICATION_CREDENTIALS
was set using:
export GOOGLE_APPLICATION_CREDENTIALS=path/to/file.json
and verified with echo $GOOGLE_APPLICATION_CREDENTIALS - after a reboot.
But I am still encountering:
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. See https://developers.google.com/accounts/docs/application-
default-credentials for more information.
I believe this is related to the default environment that the application is running in, or rather what GCP object thinks the context is -runningOnComputeEngine:
com.google.auth.oauth2.ComputeEngineCredentials runningOnComputeEngine
INFO: Failed to detect whether we are running on Google Compute Engine.
also, a dialog displayed:
Unable to launch App Engine Server
Cannot determine server execution context
and there are no Google Cloud Platform settings in project (Eclipse 2019-3):
This is not an App Engine application.
How to set the environment that GCP objects point to -> Non App Engine.
For reference:
Server to Server (link in error message)
Publish
Google Cloud Tools for Eclipse
Java 7 application
Mac OS (Sierra)
The file permissions are set that app can read the file.
Google's documentation on this is terrible - it does not mention this anywhere.
The answer is to use:
// create a credentials provider
CredentialsProvider credentialsProvider = FixedCredentialsProvider.create(ServiceAccountCredentials.fromStream(new FileInputStream(Constants.PUB_SUB_KEY)));
// apply credentials provider when creating publisher
publisher = Publisher.newBuilder(topicName).setCredentialsProvider(credentialsProvider).build();
The Environment variable usage is either deprecated or the documentation is flat out wrong, or I'm missing something,... which is entirely possible given the poor documentation.

authentication with Xamarin. Android and Microsoft.Azure.Mobile.Client Microsoft provider error

I had a code that worked unlit few days ago: this is an xamarin.android activity code
[Activity(Label = "AuthSample", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
Button login;
//Mobile Service Client reference
private MobileServiceClient client;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
client = new MobileServiceClient("https://XXXXXXX.azurewebsites.net");
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
login = FindViewById<Button>(Resource.Id.buttonLoginUser);
login.Click += onLoginClick;
}
private async void onLoginClick(object sender, EventArgs e)
{
// Load data only after authentication succeeds.
if (await Authenticate())
{
}
}
// Define a authenticated user.
private MobileServiceUser user;
private async Task<bool> Authenticate()
{
var success = false;
try
{
// Sign in with Microsoft login using a server-managed flow.
user = await client.LoginAsync(this,
MobileServiceAuthenticationProvider.MicrosoftAccount);
CreateAndShowDialog(string.Format("you are now logged in - {0}",
user.UserId), "Logged in!");
success = true;
}
catch (Exception ex)
{
CreateAndShowDialog(ex, "Authentication failed");
}
return success;
}
private void CreateAndShowDialog(Exception exception, String title)
{
CreateAndShowDialog(exception.Message, title);
}
private void CreateAndShowDialog(string message, string title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetMessage(message);
builder.SetTitle(title);
builder.Create().Show();
}
}
i did all the instruction in the tutorial.
the LoginAsync redirect me to the Microsoft login page, i am able to authenticate and after a successful authentication i get this error : "the page cannot be displayed because an internal server error has occured"
i am working with 3.1 azure sdk version
According to your description, I assumed that you could follow the steps below to troubleshoot this issue.
For Node.js backend
You could leverage App Service Editor or kudu for create the iisnode.yml file under root folder (D:\home\site\wwwroot) if not exists. Then add the following settings for enable logging to debug a Node.js web app in azure app service:
loggingEnabled: true
logDirectory: iisnode
Additionally, here is a similar issue about enable node.js logging, you could refer to it. Also, for more details about kudu and app service editor, you could refer to here.
For C# backend
you could edit App_Start\Startup.MobileApp.cs file and configure the IncludeErrorDetailPolicy as follows for capturing the error details:
HttpConfiguration config = new HttpConfiguration();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
For a simple way, you could access https://{your-app-name}.azurewebsites.net/.auth/login/{provider-name} via the browser, then check the detailed error message for locating the specific error.
UPDATE:
Based on your address, I checked your app and found I could log with my Microsoft Account via the browser. Then I checked with your table endpoint and found the follow error:
https://{your-app-name}.azurewebsites.net/tables/todoitem?ZUMO-API-VERSION=2.0.0
message: "An error has occurred.",
exceptionMessage: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)",
exceptionType: "System.Data.SqlClient.SqlException",
As I known, when following the quickstart to create the data store for your backend, downloading the C# backend, then deploy the backend to moible app. At this point, your created connection string via azure portal would not be exposed to your ASP.NET application, and the default connection string would use the localdb, you need to edit the Web.config file before deploying to azure mobile app as follows:
<connectionStrings>
<add name="MS_TableConnectionString" connectionString="Data Source=tcp:{your-sqlserver-name}.database.windows.net,1433;Initial Catalog={db-name};User ID={user-id};Password={password}" providerName="System.Data.SqlClient" />
</connectionStrings>
Or configure the connection string when deploy your app to azure mobile app via VS as follows:
It seems that there was a problem in azure or in Microsoft authentication.
after two days of frustration everything just started to work again!!

How can I use the service fabric actor model from MVC project?

I used the stateful actor template in visual studio 2015 to create a service fabric service. In the same solution I created an MVC app and in the about controller I attempted to copy the code from the sample client. When I run the web app and execute about action it just hangs. I don't get an exception or anything that indicates why it didn't work. Running the sample client console app where I got the code works just fine. Any suggestions on what may be wrong?
public ActionResult About()
{
var proxy = ActorProxy.Create<IO365ServiceHealth>(ActorId.NewId(), "fabric:/O365Services");
try
{
int count = 10;
Console.WriteLine("Setting Count to in Actor {0}: {1}", proxy.GetActorId(), count);
proxy.SetCountAsync(count).Wait(); /* Hangs here */
Console.WriteLine("Count from Actor {0}: {1}", proxy.GetActorId(), proxy.GetCountAsync().Result);
}
catch (Exception ex)
{
Console.WriteLine("{0}", ex.Message);
}
ViewBag.Message = "Your application description page.";
return View();
}
Is the MVC app hosted within Service Fabric? If not then it won't be able to access Service Fabric information unless it's exposed in some way (e.g. through an OwinCommunicationListener on a service).

Registering User using Smack 4.1.3

We are building a chat client in java and using smack 4.1.3. What I noticed is there is huge change in smack APIs after smack 4.0 and registrations examples available on the internet are not working for smack 4.1.3. I am not getting write APIs to register user. May anybody give sample codes.
Thanks in advance...
This connects ejabberd server with smack 4.1.3.
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("testuser", "pass")
.setServiceName("example.com")
.setHost("example.com")
.setResource("test")
.setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.disabled)
.setPort(5222)
.build();
SASLMechanism mechanism = new SASLDigestMD5Mechanism();
SASLAuthentication.registerSASLMechanism(mechanism);
SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
SASLAuthentication.unBlacklistSASLMechanism("DIGEST-MD5");
AbstractXMPPConnection con = new XMPPTCPConnection(config);
try {
con.connect();
con.login();
} catch (Exception ex) {
System.out.println(ex.getCause() + " " + ex.getMessage());
Logger.getLogger(redcore.class.getName()).log(Level.SEVERE, null, ex);
}
Do you have any problem or restriction that you are not allowed to user simple REST api's, plugins provided by openfire for registering user's, retrieving, deleting etc.
Refer here for the official docs.