I'm trying to subscribe to an Azure service bus topic in java. To do that, I need to create a ServiceBusContract instance. In every example I found, they do it like this:
String issuer = "<obtained from portal>";
String key = "<obtained from portal>";
Configuration config =
ServiceBusConfiguration.configureWithWrapAuthentication(
“HowToSample”,
issuer,
key);
ServiceBusContract service = ServiceBusService.create(config);
from: link
However if you take a look at the javadoc, there is no configureWithWrapAuthentication method with 3 String parameters!
I'm using the 0.3.1 version jar of the azure api.
How do I create a ServiceBusContract using these new(?) configureWithWrapAuthentication methods? Or is there something I overlooked?
Here are the parameters that we included in the configuration method.
String namespace, namespace is the name of your service bus subscription, such as johndoeservicebus.
String authenticationName, authentication name is the name of the login for WRAP, typically, it is called owner.
String authenticationPassword, authentication password is the key which you can obtain from your Azure Portal.
String serviceBusRootUri, service bus root URI is the root of the service bus service, for united states, it is “.servicebus.windows.net”.
String wrapRootUri, WRAP root Uri is the root of the WRAP authentication service, in united states, it is “-sb.accesscontrol.windows.net/WRAPv0.9”.
Apprently there is an issue with the above, tried it and it no longer works. According to github there is an open issue now:
https://github.com/Azure/azure-sdk-for-java/issues/437
The team has triaged this issue and worked on it. We've also reached out to the service bus team on the change from ACS to SAS, and to our documentation team so that we have a full-stop plan for dealing with this change, as it's not just a code issue, it's a communication issue.
This fix will be in the next release of the Java SDK, based on everything I'm hearing from the team.
Related
I am writing application that need to read mailbox using IMAP, but as daemon, without user interaction. I need to use OAuth2 to get access.
Because I need it without user interaction, I need to use client credentials flow. This was added this June.
I have done everything from official documentation. Registered application, added permissions, added mailbox permission using PowerShell.
When I get request access token with scope https://outlook.office365.com/.default, the one that I receive has role IMAP.AccessAsApp, so I believe that is correct. I used https://jwt.ms/ to parse JWT.
The problem is when I try to authenticate using this access token in Java, for example
Properties props = new Properties();
props.put("mail.imap.ssl.enable", "true");
props.put("mail.imap.auth.mechanisms", "XOAUTH2");
props.put("mail.debug", "true");
Session session = Session.getInstance(props);
Store store = session.getStore("imap");
store.connect("outlook.office365.com", 993, "testing#mydomain.com", "accessToken");
I receive AUTHENTICATE failed. I tried same code with access token received using authorization code flow, which requires user interaction. Using that access code I was able to connect to mailbox. So the code is correct.
I even tried using client id and service id instead of email address as username, but without success.
I am not sure where I made the mistake and if I am using correct username. Any help is appreciated.
I wrote same answer here, so I am coping it here.
I think I made some progress.
I read documentation few times, tried few times from the start with same error. I even have tried using client and object ids instead of email as username, in lack of better ideas.
So this is where I think I have made mistake previous times.
On the part where it is needed to register service principal, I needed to execute
New-ServicePrincipal -AppId <APPLICATION_ID> -ServiceId <OBJECT_ID> [-Organization <ORGANIZATION_ID>]
Here I have put enterprise application object id as ServiceId argument. And that is ok.
But on
Add-MailboxPermission -Identity "email address removed for privacy reasons" -User
<SERVICE_PRINCIPAL_ID> -AccessRights FullAccess
I have put my registered application object id as User argument. I also tried setting object id of enterprise application, but it did not have success.
When I executed
Get-ServicePrincipal -Organization <ORGANIZATION_ID> | fl
I did not pay attention to ServiceId property, even with documentation specifying it and saying it will be different.
Now I cleared everything and started fresh.
I have executed all the steps again, but on the step for creating new service principal I used data from enterprise application view. When I need to add mail permission, I list service principals, and then use ServiceId value from the output, as argument for user.
With that, I was able to authorise.
Thanks everyone for sharing your experience. This has proved to be a little confusing. :)
To sum everything up, to access a mailbox with IMAPS and OAuth2 (as opposed to using Graph API which is another method Microsoft recommends):
Create an Azure App Registration
Add API permission Office 365 Exchange Online - IMAP.AccessAsApp and grant admin consent
Create a service principal, which will be used to grant mailbox permissions to in Exchange Online
Connect-AzureAD
Connect-ExchangeOnline
$azapp = Get-AzureADApplication -SearchString 'App Registration Name'
$azsp = Get-AzureADServicePrincipal -SearchString $azapp.DisplayName
# GOTCHA: You need the ObjectId from 'Enterprise applications' (Get-AzureADServicePrincipal), not 'Application registrations' (Get-AzureADApplication) for ServiceId (thanks #[jamie][1])
$sp = New-ServicePrincipal -AppId $azapp.AppId -ServiceId $azsp.ObjectId -DisplayName "EXO Service Principal for $($azapp.DisplayName)"
Grant access rights to mailboxes for the service principal
$mbxs = 'mymbx1#yourdomain.tld',`
'mymbx2#yourdomain.tld',`
'mymbx3#yourdomain.tld'
$mbxs | %{ Add-MailboxPermission -Identity $_ -User $sp.ServiceId -AccessRights FullAccess } | fl *
Get-MailboxPermission $mbxs[-1] | ft -a
You can use Get-IMAPAccessToken.ps1 to test your setup
.\Get-IMAPAccessToken.ps1 -TenantID $TenantId -ClientId $ClientId -ClientSecret $ClientSecret -TargetMailbox $TargetMailbox
Other parameters you may need:
Authority: https://login.microsoftonline.com/<YourTenantId>/
Scope: https://outlook.office365.com/.default
I'm finding a way to programatically list Google Cloud projects inside an organization. I'm trying to use a service account exported json credential to achieve such purpose in this way:
// More info on the endpoint here:
// https://cloud.google.com/resource-manager/reference/rest/v1/projects/list
final CloudResourceManager cloudResourceManagerService = createCloudResourceManagerService();
final CloudResourceManager.Projects.List listRequest = cloudResourceManagerService
.projects()
.list()
.setFilter("labels.it-restoring:false name:IT-TEST-*");
final ListProjectsResponse listResponse = listRequest.execute();
if (listResponse.isEmpty()) {
throw new RuntimeException("The API did not get any response"); // I never get past here
}
log.info("Listing projects returned: {}", listResponse);
The problem I find is that I always get an empty response. Even though I assigned the service account the role of owner. According to docs, I could use roles/
resourcemanager.organizationAdmin which I also set but with no luck. I create the CloudResourceManagement api object using getApplicationDefault.
However if I do gcloud beta auth application-default login which triggers an auth flow in the browser and authenticate with the user which is the owner of the organization this works and lists all the projects that I have.
Can anybody explain to me what I should do to store a proper credential which would emulate he user owner? I already set the service account with the Owner role which in theory gives virtually access to all resources and still no luck.
In order to list the projects on your organization, you need the permission resourcemanager.projects.get. Please find more information in this link The service account might have the owner role of 1 project, and not enought to list them all.
An alternative solution is to grant the account the cloudasset.assets.searchAllResources permission at org level by using one of the following roles:
roles/cloudasset.viewer
roles/cloudasset.owner
roles/viewer
roles/editor
roles/owner
With this permission, you can list all the projects within an organization 456:
gcloud asset search-all-resources \
--asset-types="cloudresourcemanager.googleapis.com/Project"
--scope=organizations/456
Documentation: https://cloud.google.com/asset-inventory/docs/searching-resources
Related post: How to find, list, or search resources across services (APIs) and projects in Google Cloud Platform?
What is the best and correct way to list Azure Database for PostgreSQL servers present in my Resource Group using Azure Java SDK?
Currently, we have deployments that happen using ARM templates and once the resources have been deployed we want to be able to get the information about those resources from Azure itself.
I have tried doing in the following way:
PagedList<SqlServer> azureSqlServers = azure1.sqlServers().listByResourceGroup("resourceGrpName");
//PagedList<SqlServer> azureSqlServers = azure1.sqlServers().list();
for(SqlServer azureSqlServer : azureSqlServers) {
System.out.println(azureSqlServer.fullyQualifiedDomainName());
}
System.out.println(azureSqlServers.size());
But the list size returned is 0.
However, for virtual machines, I am able to get the information in the following way:
PagedList<VirtualMachine> vms = azure1.virtualMachines().listByResourceGroup("resourceGrpName");
for (VirtualMachine vm : vms) {
System.out.println(vm.name());
System.out.println(vm.powerState());
System.out.println(vm.size());
System.out.println(vm.tags());
}
So, what is the right way of getting the information about the Azure Database for PostgreSQL using Azure Java SDK?
P.S.
Once I get the information regarding Azure Database for PostgreSQL, I would need similar information about the Azure Database for MySQL Servers.
Edit: I have seen this question which was asked 2 years back and would like to know if Azure added Support for Azure Database for PostgreSQL/MySQL servers or not.
Azure Java SDK for MySQL/PostgreSQL databases?
So, I kind of implemented it in the following way and it can be treated as an alternative way...
Looking at the Azure SDK for java repo on Github (https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/postgresql), looks like they have it in beta so I searched for the pom in mvnrepository. I imported the following pom in my project (azure-mgmt-postgresql is still in beta):
<!-- https://mvnrepository.com/artifact/com.microsoft.azure.postgresql.v2017_12_01/azure-mgmt-postgresql -->
<dependency>
<groupId>com.microsoft.azure.postgresql.v2017_12_01</groupId>
<artifactId>azure-mgmt-postgresql</artifactId>
<version>1.0.0-beta-5</version>
</dependency>
In the code, Following is the gist of how I did it:
I already have a service principal created and have its information with me.
But, anyone trying this will require clientId, tenantId, clientSecret, and subscriptionId with them, the way #Jim Xu explained.
// create the credentials object
ApplicationTokenCredentials credentials = new ApplicationTokenCredentials(clientId, tenantId, clientSecret, AzureEnvironment.AZURE);
// build a rest client object configured with the credentials created above
RestClient restClient = new RestClient.Builder()
.withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER)
.withCredentials(credentials)
.withSerializerAdapter(new AzureJacksonAdapter())
.withResponseBuilderFactory(new AzureResponseBuilder.Factory())
.withInterceptor(new ProviderRegistrationInterceptor(credentials))
.withInterceptor(new ResourceManagerThrottlingInterceptor())
.build();
// use the PostgreSQLManager
PostgreSQLManager psqlManager = PostgreSQLManager.authenticate(restClient, subscriptionId);
PagedList<Server> azurePsqlServers = psqlManager.servers().listByResourceGroup(resourceGrpName);
for(Server azurePsqlServer : azurePsqlServers) {
System.out.println(azurePsqlServer.fullyQualifiedDomainName());
System.out.println(azurePsqlServer.userVisibleState().toString());
System.out.println(azurePsqlServer.sku().name());
}
Note: Server class refers to com.microsoft.azure.management.postgresql.v2017_12_01.Server
Also, if you take a look at the Azure class, you will notice this is how they do it internally.
For reference, you can use SqlServerManager sqlServerManager in the Azure class and look at how they have used it and created an authenticated manager in case you want to use some services that are still in preview or beta.
According to my test, we can use java sdk azure-mgmt-resources to implement your need. For example
Create a service principal
az login
# it will create a service pricipal and assign a contributor rolen to the sp
az ad sp create-for-rbac -n "MyApp" --scope "/subscriptions/<subscription id>" --sdk-auth
code
String tenantId = "<the tenantId you copy >";
String clientId = "<the clientId you copy>";
String clientSecret= "<the clientSecre you copy>";
String subscriptionId = "<the subscription id you copy>";
ApplicationTokenCredentials creds = new
ApplicationTokenCredentials(clientId,domain,secret,AzureEnvironment.AZURE);
RestClient restClient =new RestClient.Builder()
.withBaseUrl(AzureEnvironment.AZURE, AzureEnvironment.Endpoint.RESOURCE_MANAGER)
.withSerializerAdapter(new AzureJacksonAdapter())
.withReadTimeout(150, TimeUnit.SECONDS)
.withLogLevel(LogLevel.BODY)
.withResponseBuilderFactory(new AzureResponseBuilder.Factory())
.withCredentials(creds)
.build();
ResourceManager resourceClient= ResourceManager.authenticate(restClient).withSubscription(subscriptionId);
ResourceManagementClientImpl client= resourceClient.inner();
String filter="resourceType eq 'Microsoft.DBforPostgreSQL/servers'"; //The filter to apply on the operation
String expand=null;//The $expand query parameter. You can expand createdTime and changedTime.For example, to expand both properties, use $expand=changedTime,createdTime
Integer top =null;// The number of results to return. If null is passed, returns all resource groups.
PagedList<GenericResourceInner> results= client.resources().list(filter, null,top);
while (true) {
for (GenericResourceInner resource : results.currentPage().items()) {
System.out.println(resource.id());
System.out.println(resource.name());
System.out.println(resource.type());
System.out.println(resource.location());
System.out.println(resource.sku().name());
System.out.println("------------------------------");
}
if (results.hasNextPage()) {
results.loadNextPage();
} else {
break;
}
}
Besides, you also can use Azure REST API to implement your need. For more details, please refer to https://learn.microsoft.com/en-us/rest/api/resources/resources
How to fetch the user's other details from AD after logging into the application using LDAP registry configured in WebSphere server. I have Java EE application, which is using the single sign on. I want to get the other details like email, office location of the user which is configured in Active Directory. How do I get that?
// Retrieves the default InitialContext for this server.
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
// Retrieves the local UserRegistry object.
com.ibm.websphere.security.UserRegistry reg = (com.ibm.websphere.security.UserRegistry) ctx
.lookup("UserRegistry");
From this registry, is there chance to get it?
In WebSphere Application Server you can access User Registry information -and modify it- thorugh the Virtual Member Manager componente an its API.
There's plenty of documentation and samples on IBM Infocenter. From there, the code snippet to get the properties of an entity like a user:
DataObject root = SDOHelper.createRootDataObject();
DataObject entity = SDOHelper.createEntityDataObject(root, null, DO_PERSON_ACCOUNT);
entity.createDataObject(DO_IDENTIFIER).set(PROP_UNIQUE_NAME,
"uid=SalesManager,cn=users,dc=yourco,dc=com");
DataObject propCtrl = SDOHelper.createControlDataObject(root, null, DO_PROPERTY_CONTROL);
propCtrl.getList(PROP_PROPERTIES).add("sn");
propCtrl.getList(PROP_PROPERTIES).add("uid");
propCtrl.getList(PROP_PROPERTIES).add("cn");
propCtrl.getList(PROP_PROPERTIES).add("telephoneNumber");
propCtrl.getList(PROP_PROPERTIES).add("createTimestamp");
root = service.get(root);
To get the service instance that communicates with the registry you need first to execute the Programming Prerequisites of the API. I stringly suggest you to review the Infocenter documentation.
I wrote an article about exactly that question:
http://veithen.github.io/2012/12/13/retrieving-custom-user-attributes-from.html
Note that the conclusion is compatible with what Carlos wrote: you have to use VMM.
I want to receive XMPP message with app engine, and then use a look up table to find the corresponding glass's userid and push timeline cards. I saw the service was created in OAuth. Do I need to create a new service each time? Or I can get the service with userid? Is there any references on service?
Thanks
This is the code I'm using. Currently I'm creating a new mirror service each time I got a message. Will that cause any trouble or there is a better way to do that? Is there and reference to "util.create_service"?
class XmppHandler(xmpp_handlers.CommandHandler):
def push_command(self, message=None):
if message.arg:
id=XMPP_addr_access.get_id_from_addr(bare_jid(message.sender))
if id is not None:
creds=StorageByKeyName(Credentials, id, 'credentials').get()
mirror_service = util.create_service('mirror', 'v1', creds)
body = {'notification': {'level': 'DEFAULT'}}
body['text'] = message.arg
mirror_service.timeline().insert(body=body).execute()
In my Glassware, notification responses (what I believe you are calling a service) run similar code to what you have, I generate a new Credential using the java helper method AuthUtil.getCredential(String userId) every time I need to make another Mirror API request based on an incoming notification in App Engine.
This credential is used in a MirrorClient object that uses the same userId and does the insert back into the timeline.
I get the userId by looking it up in a persisted store referenced by the userToken that the notification provides.