Which Java API from the Azure SDK to delete a NetworkSecurityRule? - java

I can't find the Java API from the Azure SDK to delete a NetworkSecurityRule resource.
The REST API is documented here.
I use this Maven dependency: com.microsoft.azure:azure-mgmt-network:jar:1.31.0
In my code I hold a reference to a NetworkManager instance and I have a collection of NetworkSecurityRule objects.
Does anyone know how to do it?
Thanks,
Chris

According to my test, we can use the following code. For more details, please refer to the docuemnt
1. create a service principal and assign Reader role for the sp.
az login
az account set --subscription "<your subscription id>"
# it will assign Contributor to the sp at subscription level
az ad sp create-for-rbac -n "mysample" --role Contributor
code
public static void main(String[] args){
String clientId = "your sp appId";
String secret = "your sp password";
String domain = "your tenant domain";
ApplicationTokenCredentials credentials = new ApplicationTokenCredentials(clientId, domain, secret,
AzureEnvironment.AZURE);
Azure azure = AzureAzure.configure().withLogLevel(LogLevel.BASIC).authenticate(credentials)
.withDefaultSubscription();
NetworkSecurityGroup group = azure.networkSecurityGroups().getById(
"your nsg resource id");
for(String i : group.securityRules().keySet()){
System.out.println(i);
}
group.update().withoutRule.apply();
group = azure.networkSecurityGroups().getById(
"/subscriptions/e5b0fcfa-e859-43f3-8d84-5e5fe29f4c68/resourceGroups/testgroup/providers/Microsoft.Network/networkSecurityGroups/test0123");
System.out.println(group.Name());
for(String i : group.securityRules().keySet()){
System.out.println(i);
}
}

Related

Error code AADSTS70000121 when using One Drive through Microsoft Graph in Java

I have a Java application that integrates with One Drive through Microsoft Graph. I followed the documentation and I am able to pass the authorisation step but when interrogating the API I get this error:
"AADSTS70000121: The passed grant is from a personal Microsoft account and is required to be sent to the /consumers or /common endpoint."
What am I missing?
This is the code I am using:
Get an authorisation token using the URL bellow
private static final String RESPONSE_TYPE = "code";
private static final String SCOPE = "openid%20Files.Read%20Files.ReadWrite%20Contacts.Read%20offline_access";
String authorizeUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=" + CLIENT_ID
+ "&scope=" + SCOPE + "&response_type=" + RESPONSE_TYPE + "&redirect_uri=" + REDIRECT_URL;
Exchange the received authorization token
List<String> scopes = new LinkedList<String>();
scopes.add("https://graph.microsoft.com/.default");
AuthorizationCodeCredential authCodeCredential = new AuthorizationCodeCredentialBuilder()
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.authorizationCode(authorizationCode)
.redirectUrl(REDIRECT_URL)
.build();
TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(scopes, authCodeCredential);
GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider(tokenCredAuthProvider).buildClient();
User me = graphClient.me()
.buildRequest()
.get();
As you are using the personal account then please change the endpoint to consumers instead of common,
https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?
ref doc - https://learn.microsoft.com/en-au/azure/active-directory/develop/v2-oauth2-auth-code-flow
Hope this helps
Thanks

get instances from security group azure sdk

I want to list all my security groups but i want to check if any security group has instances or no, if yes i want to get this instances.
How can i do that in code ? I just build function to get all security group.
#Override
public List<LocalSecurityGroupV2> getSecurityGroups(final List<String> securityGroupIds) {
return securityGroupIds
.stream()
.map(this::findSecurityGroupById)
.collect(Collectors.toList());
}
Can you please elaborate what do you mean by instances?
Is this you are looking for?
Gets all network security groups in a subscription:
https://learn.microsoft.com/en-us/rest/api/virtualnetwork/networksecuritygroups/listall
Gets all network security groups in a resource group:
https://learn.microsoft.com/en-us/rest/api/virtualnetwork/networksecuritygroups/list
We could do that with Azure Java SDK. For authentication please refer to Authenticate with the Azure management libraries for Java.
The following is the demo code, I tested on my side.
String client = "clientId";
String tenant = "tenantId";
String key = "scret key";
ApplicationTokenCredentials credentials = new ApplicationTokenCredentials(client,
tenant,
key,
AzureEnvironment.AZURE);
Azure azure = Azure.configure().authenticate(credentials).withDefaultSubscription();
List <VirtualMachine> vmlist = azure.virtualMachines().list();
List<String> networkInterfaceList = new ArrayList<String>();
PagedList<NetworkSecurityGroup> list = azure.networkSecurityGroups().listByResourceGroup("resourceGroupName");
//add the networkinterface to the list
for (NetworkSecurityGroup nsg :list
) {
for (String networkInterface :nsg.networkInterfaceIds()
) {
networkInterfaceList.add(networkInterface);
}
};
List<VirtualMachine> virtualMachineList = new ArrayList<VirtualMachine>();
for (VirtualMachine vm :vmlist
) {
for (String vmInterface:vm.networkInterfaceIds()
) {
if(networkInterfaceList.contains(vmInterface))
{
if(!virtualMachineList.contains(vm))
{
virtualMachineList.add(vm);
System.out.println(vm.computerName());
}
}
}
}

How to create bulkconnection with accesstoken in salesforce

I need to create BulkConnection for bulk API into salesforce.
We can able to create BulkConnection using ConnectorConfig with basic SOAP authentication.
Code is below,
ConnectorConfig config = new ConnectorConfig();
config.setUsername("USERNAME");
config.setPassword("PASSWORD+TOKEN");
config.setCompression(true);
config.setTraceFile("traceLogs.txt");
config.setTraceMessage(true);
config.setPrettyPrintXml(true);
config.setAuthEndpoint("https://login.salesforce.com/services/Soap/u/39.0");
PartnerConnection connection = new PartnerConnection(config);
String soapEndpoint = config.getServiceEndpoint();
String apiVersion = "39.0";
String restEndpoint = soapEndpoint.substring(0, soapEndpoint.indexOf("Soap/")) + "async/" + apiVersion;
config.setRestEndpoint(restEndpoint);
bulkConnection = new BulkConnection(config);
Above code is working fine.
But in my case, I can't able to collect username & password for each of the customer's salesforce account.
Is this possible to create BulkConnection using accestoken?..
Please give me your suggestion.
Thanks,
Harish

Subject must match Issuer claim in the client assertion

I want to integrate office365 service management API for collecting events from it.I want to use client credential way to use service to service call but i am getting following error,
{
"error":"invalid_client",
"error_description":"AADSTS50048: Subject must match Issuer claim in the client assertion.
\r\nTrace ID: 1ad7acd8-3945-4fe0-a313-07638eb76e42\r\nCorrelation ID: a6c3a3c9-b737-4bfc-894f-3086c3ce8dfa\r\nTimestamp: 2016-06-09 07:20:15Z",
"error_codes":[50048
],
"timestamp":"2016-06-09 07:20:15Z",
"trace_id":"1ad7acd8-3945-4fe0-a313-07638eb76e42",
"correlation_id":"a6c3a3c9-b737-4bfc-894f-3086c3ce8dfa"
}
i use following doc to integration,
For getting client assersion,
https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx I am getting this. But for Access token,
https://msdn.microsoft.com/en-us/library/office/dn707383.aspx I not getting this as a response getting above error.
Somebody help me please :)
How did you get the client_assertion? The link you provide doesn’t describe how to get the ‘client_assertion’. It acquire the token with the app’s id and secret which is doesn’t support for the Office 365 Management API. You can refer the blog to about the ‘client_assertion’.
And here is an C# code sample which use the ADAL to get the access token for the client credentials flow:
string clientId = "{clientId}";
string certThumbprint = "‎{copy from mmc}";
certThumbprint = certThumbprint.Replace("\u200e", string.Empty).Replace("\u200f", string.Empty).Replace(" ", string.Empty);
string apiResourceId = "https://manage.office.com";
X509Certificate2 cert = null;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
string authority = "https://login.windows.net/{yourTentant}";
var authContext = new AuthenticationContext(authority);
try
{
store.Open(OpenFlags.ReadOnly);
cert = store.Certificates.Find(X509FindType.FindByThumbprint, certThumbprint, false)[0];
}
finally
{
store.Close();
}
var certCred = new ClientAssertionCertificate(clientId, cert);
AuthenticationResult result = null;
try
{
result = await authContext.AcquireTokenAsync(apiResourceId, certCred);
}
catch (Exception ex)
{
}

AWS cognito does not generate tokens when run from a serverlet

I am trying to get amazon cognito to work. If I run the code to generate a login token from a standalone java program it works.
public class cognito extends HttpServlet
{
public static void main(String[] args) throws Exception {
AWSCredentials credentials = new BasicAWSCredentials("*******", "********");
AmazonCognitoIdentityClient client =
new AmazonCognitoIdentityClient(credentials);
client.setRegion(Region.getRegion(Regions.EU_WEST_1));
GetOpenIdTokenForDeveloperIdentityRequest tokenRequest =
new GetOpenIdTokenForDeveloperIdentityRequest();
tokenRequest.setIdentityPoolId("*************");
HashMap<String, String> map = new HashMap<String, String>();
//Key -> Developer Provider Name used when creating the identity pool
//Value -> Unique identifier of the user in your <u>backend</u>
map.put("test", "AmazonCognitoIdentity");
//Duration of the generated OpenID Connect Token
tokenRequest.setLogins(map);
tokenRequest.setTokenDuration(1000l);
GetOpenIdTokenForDeveloperIdentityResult result = client
.getOpenIdTokenForDeveloperIdentity(tokenRequest);
String identityId = result.getIdentityId();
String token = result.getToken();
System.out.println("id = " + identityId + " token = " + token);
}
}
However when I run this code from a servlet on a redhat linux server, it always times out.
Any suggestion would be helpful
map.put("test", "AmazonCognitoIdentity");
are you sure your developer provider name is "test"?
you can see it in your cognito identity pool edit page.
And "AmazonCognitoIdentity" should be your own unique user-id.
Without the actual exception, it is hard to tell what is the exact issue. It could be that something else running in your servlet engine is setting a much more aggressive socket timeout than the default when it runs from the command line. You might want to explicitly set the connection and socket timeouts using methods using this class http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/ClientConfiguration.html and pass it in to the identity client constructor.

Categories