Skip to content

Commit 855a1aa

Browse files
author
sgonzalezMSFT
committed
Update dev samples to show recommended practices
1 parent 1db4f9b commit 855a1aa

13 files changed

+447
-476
lines changed

src/samples/SSLTunnelSocketFactory.java

Lines changed: 0 additions & 157 deletions
This file was deleted.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Licensed under the MIT License.
3+
4+
import com.microsoft.aad.msal4j.ITokenCacheAccessAspect;
5+
import com.microsoft.aad.msal4j.ITokenCacheAccessContext;
6+
7+
import java.net.URL;
8+
import java.nio.file.Files;
9+
import java.nio.file.Paths;
10+
11+
public class TokenCacheAspect implements ITokenCacheAccessAspect {
12+
13+
private String data;
14+
15+
public TokenCacheAspect(String fileName) {
16+
this.data = readDataFromFile(fileName);
17+
}
18+
19+
@Override
20+
public void beforeCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) {
21+
iTokenCacheAccessContext.tokenCache().deserialize(data);
22+
}
23+
24+
@Override
25+
public void afterCacheAccess(ITokenCacheAccessContext iTokenCacheAccessContext) {
26+
data = iTokenCacheAccessContext.tokenCache().serialize();
27+
// you could implement logic here to write changes to file here
28+
}
29+
30+
private static String readDataFromFile(String resource) {
31+
try {
32+
URL path = TokenCacheAspect.class.getResource(resource);
33+
return new String(
34+
Files.readAllBytes(
35+
Paths.get(path.toURI())));
36+
} catch (Exception ex){
37+
System.out.println("Error reading data from file");
38+
throw new RuntimeException(ex);
39+
}
40+
}
41+
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
{
2+
"Account": {
3+
"uid.utid-login.windows.net-contoso": {
4+
"username": "John Doe",
5+
"local_account_id": "object1234",
6+
"realm": "contoso",
7+
"environment": "login.windows.net",
8+
"home_account_id": "uid.utid",
9+
"authority_type": "MSSTS"
10+
}
11+
},
12+
"RefreshToken": {
13+
"uid.utid-login.windows.net-refreshtoken-my_client_id--s2 s1 s3": {
14+
"target": "s2 s1 s3",
15+
"environment": "login.windows.net",
16+
"credential_type": "RefreshToken",
17+
"secret": "a refresh token",
18+
"client_id": "my_client_id",
19+
"home_account_id": "uid.utid"
20+
}
21+
},
22+
"AccessToken": {
23+
"uid.utid-login.windows.net-accesstoken-my_client_id-contoso-s2 s1 s3": {
24+
"environment": "login.windows.net",
25+
"credential_type": "AccessToken",
26+
"secret": "an access token",
27+
"realm": "contoso",
28+
"target": "s2 s1 s3",
29+
"client_id": "my_client_id",
30+
"cached_at": "1000",
31+
"home_account_id": "uid.utid",
32+
"extended_expires_on": "4600",
33+
"expires_on": "4600"
34+
}
35+
},
36+
"IdToken": {
37+
"uid.utid-login.windows.net-idtoken-my_client_id-contoso-": {
38+
"realm": "contoso",
39+
"environment": "login.windows.net",
40+
"credential_type": "IdToken",
41+
"secret": "header.eyJvaWQiOiAib2JqZWN0MTIzNCIsICJwcmVmZXJyZWRfdXNlcm5hbWUiOiAiSm9obiBEb2UiLCAic3ViIjogInN1YiJ9.signature",
42+
"client_id": "my_client_id",
43+
"home_account_id": "uid.utid"
44+
}
45+
},
46+
"AppMetadata": {
47+
"appmetadata-login.windows.net-my_client_id": {
48+
"environment": "login.windows.net",
49+
"family_id": null,
50+
"client_id": "my_client_id"
51+
}
52+
}
53+
}

src/samples/confidential-client/ClientCredentialGrant.java

Lines changed: 46 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,50 +5,66 @@
55
import com.microsoft.aad.msal4j.ClientCredentialParameters;
66
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
77
import com.microsoft.aad.msal4j.IAuthenticationResult;
8+
import com.microsoft.aad.msal4j.IClientCredential;
9+
import com.microsoft.aad.msal4j.MsalException;
810
import com.microsoft.aad.msal4j.SilentParameters;
911

1012
import java.util.Collections;
11-
import java.util.concurrent.CompletableFuture;
12-
import java.util.function.BiConsumer;
13+
import java.util.Set;
1314

1415
class ClientCredentialGrant {
1516

17+
private final static String CLIENT_ID = "";
18+
private final static String AUTHORITY = "https://login.microsoftonline.com/<tenant>/";
19+
private final static String CLIENT_SECRET = "";
20+
private final static Set<String> SCOPE = Collections.singleton("");
21+
1622
public static void main(String args[]) throws Exception {
17-
getAccessTokenByClientCredentialGrant();
23+
IAuthenticationResult result = acquireToken();
24+
System.out.println("Access token: " + result.accessToken());
1825
}
1926

20-
private static void getAccessTokenByClientCredentialGrant() throws Exception {
21-
22-
ConfidentialClientApplication app = ConfidentialClientApplication.builder(
23-
TestData.CONFIDENTIAL_CLIENT_ID,
24-
ClientCredentialFactory.createFromSecret(TestData.CONFIDENTIAL_CLIENT_SECRET))
25-
.authority(TestData.TENANT_SPECIFIC_AUTHORITY)
26-
.build();
27+
private static IAuthenticationResult acquireToken() throws Exception {
2728

28-
ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
29-
Collections.singleton(TestData.GRAPH_DEFAULT_SCOPE))
30-
.build();
29+
// Load token cache from file and initialize token cache aspect. The token cache will have
30+
// dummy data, so the acquireTokenSilently call will fail.
31+
TokenCacheAspect tokenCacheAspect = new TokenCacheAspect("sample_cache.json");
3132

32-
CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
33+
// This is the secret that is created in the Azure AD portal
34+
IClientCredential credential = ClientCredentialFactory.createFromSecret(CLIENT_SECRET);
35+
ConfidentialClientApplication cca =
36+
ConfidentialClientApplication
37+
.builder(CLIENT_ID, credential)
38+
.authority(AUTHORITY)
39+
.setTokenCacheAccessAspect(tokenCacheAspect)
40+
.build();
3341

34-
BiConsumer<IAuthenticationResult, Throwable> processAuthResult = (res, ex) -> {
35-
if (ex != null) {
36-
System.out.println("Oops! We have an exception - " + ex.getMessage());
37-
}
38-
System.out.println("Returned ok - " + res);
39-
System.out.println("Access Token - " + res.accessToken());
40-
System.out.println("ID Token - " + res.idToken());
41-
};
42+
IAuthenticationResult result;
43+
try {
44+
SilentParameters silentParameters =
45+
SilentParameters
46+
.builder(SCOPE)
47+
.build();
4248

43-
future.whenCompleteAsync(processAuthResult);
44-
future.join();
49+
// try to acquire token silently. This call will fail since the token cache does not
50+
// have a token for the application you are requesting an access token for
51+
result = cca.acquireTokenSilently(silentParameters).join();
52+
} catch (Exception ex) {
53+
if (ex.getCause() instanceof MsalException) {
4554

46-
SilentParameters silentParameters =
47-
SilentParameters.builder(Collections.singleton(TestData.GRAPH_DEFAULT_SCOPE)).build();
55+
ClientCredentialParameters parameters =
56+
ClientCredentialParameters
57+
.builder(SCOPE)
58+
.build();
4859

49-
future = app.acquireTokenSilently(silentParameters);
50-
51-
future.whenCompleteAsync(processAuthResult);
52-
future.join();
60+
// Try to acquire a token. If successful, you should see
61+
// the token information printed out to console
62+
result = cca.acquireToken(parameters).join();
63+
} else {
64+
// Handle other exceptions accordingly
65+
throw ex;
66+
}
67+
}
68+
return result;
5369
}
5470
}

0 commit comments

Comments
 (0)