Skip to content
This repository was archived by the owner on Mar 16, 2021. It is now read-only.

Commit 3355d8c

Browse files
Merge pull request #8 from microsoftgraph/core-auth-integration
Core auth integration
2 parents 2ffcbee + 9a3d4ec commit 3355d8c

File tree

8 files changed

+163
-119
lines changed

8 files changed

+163
-119
lines changed

README.md

Lines changed: 54 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
1-
# Microsoft Graph Auth SDK for Java
1+
# Microsoft Graph Auth Preview SDK for Java
22

33
Get started with the Microsoft Graph SDK for Java by integrating the [Microsoft Graph API](https://graph.microsoft.io/en-us/getting-started) into your Java application!
44

5+
## Important Note about the Microsoft Graph Auth Preview SDK for Java
6+
7+
During the preview we may make changes to the API, and other mechanisms of this library, which you will be required to take along with bug fixes or feature improvements. This may impact your application. An API change may require you to update your code. When we provide the General Availability release we will require you to update to the General Availability version within six months, as applications written using a preview version of library may no longer work.
8+
59
## 1. Installation
610

711
### 1.1 Install via Gradle
812

9-
Add the repository and a compile dependency for `microsoft-graph` to your project's `build.gradle`:
13+
Add the repository and a compile dependency for `microsoft-graph-auth` to your project's `build.gradle`:
1014

1115
```gradle
1216
repository {
@@ -57,46 +61,42 @@ Add in `project`
5761

5862
Register your application by following the steps at [Register your app with the Azure AD v2.0 endpoint](https://developer.microsoft.com/en-us/graph/docs/concepts/auth_register_app_v2).
5963

60-
### 2.2 Create an IAuthenticationProvider object
64+
### 2.2 Create an authentication provider object
6165

6266
#### 2.3.1 Confidential client authentication provider
6367

6468
##### a. Authorization code provider
6569
```java
66-
IAuthenticationProvider authorizationCodeProvider = new AuthorizationCodeProvider(CLIENT_ID, SCOPES_LIST, AUTHORIZATION_CODE, REDIRECT_URL, NATIONAL_CLOUD, TENANT, SECRET);
70+
AuthorizationCodeProvider authProvider = new AuthorizationCodeProvider(CLIENT_ID, SCOPES, AUTHORIZATION_CODE, REDIRECT_URL, NATIONAL_CLOUD, TENANT, CLIENT_SECRET);
6771
```
6872

6973
##### b. Client credential provider
7074
```java
71-
IAuthenticationProvider iAuthenticationProvider = new ClientCredentialProvider(CLIENT_ID, SCOPES_LIST, CLIENT_SECRET, tenantGUID, NationalCloud.Global);
75+
ClientCredentialProvider authProvider = new ClientCredentialProvider(CLIENT_ID, SCOPES, CLIENT_SECRET, TENANT_GUID, NATIONAL_CLOUD);
7276
```
7377
#### 2.3.2 Public client authentication provider
7478
##### a. Username password provider
7579
```java
76-
IAuthenticationProvider authenticationProvider = new UsernamePasswordProvider(CLIENT_ID, SCOPES_LIST, USERNAME, PASSWORD, NATIONAL_CLOUD, TENANT, CLIENT_SECRET);
80+
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(CLIENT_ID, SCOPES, USERNAME, PASSWORD, NATIONAL_CLOUD, TENANT, CLIENT_SECRET);
7781
```
7882
### 2.3 Get a HttpClient object and make a call
7983

84+
#### Using [msgraph-sdk-java](https://github.com/microsoftgraph/msgraph-sdk-java)
8085
```java
81-
import com.microsoft.graph.httpcore.HttpClients;
82-
import org.apache.http.HttpResponse;
83-
import org.apache.http.client.methods.HttpGet;
84-
import org.apache.http.client.protocol.HttpClientContext;
85-
import org.apache.http.impl.client.CloseableHttpClient;
86-
import org.apache.http.util.EntityUtils;
86+
IGraphServiceClient graphClient = GraphServiceClient
87+
.builder()
88+
.authenticationProvider(authProvider)
89+
.buildClient();
90+
91+
User user = graphClient.me().buildRequest().get();
8792
```
8893

94+
#### Using [msgraph-sdk-java-core](https://github.com/microsoftgraph/msgraph-sdk-java-core)
8995
```java
90-
CloseableHttpClient httpclient = HttpClients.createDefault(authenticationProvider);
91-
HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/");
92-
HttpClientContext localContext = HttpClientContext.create();
93-
try {
94-
HttpResponse response = httpclient.execute(httpget, localContext);
95-
String responseBody = EntityUtils.toString(response.getEntity());
96-
System.out.println(responseBody);
97-
} catch (IOException e) {
98-
e.printStackTrace();
99-
}
96+
OkHttpClient client = HttpClients.createDefault(authProvider);
97+
Request request = new Request.Builder().url("https://graph.microsoft.com/v1.0/me").build();
98+
Response response = client.newCall(request).execute();
99+
System.out.println(response.body().string());
100100
```
101101

102102
## 3. Make requests against the service
@@ -105,43 +105,54 @@ After you have a GraphServiceClient that is authenticated, you can begin making
105105

106106
### 3.1 Get the user's drive
107107

108-
To retrieve the user's drive:
108+
#### To retrieve the user's drive:
109+
##### Using [msgraph-sdk-java](https://github.com/microsoftgraph/msgraph-sdk-java)
110+
```java
111+
IGraphServiceClient graphClient =
112+
GraphServiceClient
113+
.builder()
114+
.authenticationProvider(authProvider)
115+
.buildClient();
116+
117+
Drive drive = graphClient.me().drive().buildRequest().get();
118+
```
119+
120+
##### Using [msgraph-sdk-java-core](https://github.com/microsoftgraph/msgraph-sdk-java-core)
109121

110122
```java
111-
CloseableHttpClient httpclient = HttpClients.createDefault(authenticationProvider);
112-
HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/drive");
113-
HttpClientContext localContext = HttpClientContext.create();
114-
try {
115-
HttpResponse response = httpclient.execute(httpget, localContext);
116-
String responseBody = EntityUtils.toString(response.getEntity());
117-
System.out.println(responseBody);
118-
} catch (IOException e) {
119-
e.printStackTrace();
120-
}
123+
OkHttpClient httpclient = HttpClients.createDefault(authenticationProvider);
124+
Request request = new Request.Builder().url("https://graph.microsoft.com/v1.0/me/drive").build();
125+
Response response = client.newCall(request).execute();
126+
System.out.println( respose.body().string() );
121127
```
122128

123129
## 4. Sample
124130
### 4.1 Authorization code provider
125131

126132
[Steps to get authorizationCode](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code)
127133
```java
128-
IAuthenticationProvider authenticationProvider = new AuthorizationCodeProvider("6731de76-14a6-49ae-97bc-6eba6914391e",
134+
AuthorizationCodeProvider authProvider = new AuthorizationCodeProvider("6731de76-14a6-49ae-97bc-6eba6914391e",
129135
Arrays.asList("https://graph.microsoft.com/user.read"),
130136
authorizationCode,
131137
"http://localhost/myapp/",
132138
NationalCloud.Global,
133139
"common",
134140
"JqQX2PNo9bpM0uEihUPzyrh");
135141

136-
CloseableHttpClient httpclient = HttpClients.createDefault(authenticationProvider);
137-
HttpGet httpget = new HttpGet("https://graph.microsoft.com/v1.0/me/messages");
138-
HttpClientContext localContext = HttpClientContext.create();
139-
try {
140-
HttpResponse response = httpclient.execute(httpget, localContext);
141-
String responseBody = EntityUtils.toString(response.getEntity());
142-
System.out.println(responseBody);
143-
} catch (IOException e) {
144-
e.printStackTrace();
142+
IGraphServiceClient graphClient =
143+
GraphServiceClient
144+
.builder()
145+
.authenticationProvider(authProvider)
146+
.buildClient();
147+
148+
IMessageCollectionPage page = graphClient.me().messages().buildRequest().get();
149+
while(page != null) {
150+
for(Message message : page.getCurrentPage()) {
151+
System.out.println(message.subject);
152+
}
153+
IMessageCollectionRequestBuilder builder = page.getNextPage();
154+
if(builder == null)break;
155+
page = builder.buildRequest().get();
145156
}
146157
```
147158

build.gradle

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,10 @@ dependencies {
2020
implementation 'com.google.guava:guava:23.0'
2121
// Use JUnit and mockito test framework
2222
testImplementation 'junit:junit:4.12'
23-
compile 'org.mockito:mockito-core:2.9.0'
23+
testImplementation 'org.mockito:mockito-core:2.9.0'
2424
compile 'org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2'
2525
compile 'com.microsoft.graph:microsoft-graph-core:0.1.0-SNAPSHOT'
26+
compile 'com.microsoft.graph:microsoft-graph:1.1.0'
2627
}
2728

2829
def pomConfig = {

src/main/java/com/microsoft/graph/auth/confidentialClient/AuthorizationCodeProvider.java

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import java.util.List;
44

5-
import org.apache.http.HttpRequest;
65
import org.apache.oltu.oauth2.client.OAuthClient;
76
import org.apache.oltu.oauth2.client.URLConnectionClient;
87
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
@@ -14,10 +13,14 @@
1413
import com.microsoft.graph.auth.AuthConstants;
1514
import com.microsoft.graph.auth.BaseAuthentication;
1615
import com.microsoft.graph.auth.enums.NationalCloud;
17-
import com.microsoft.graph.httpcore.IAuthenticationProvider;
16+
import com.microsoft.graph.authentication.IAuthenticationProvider;
17+
import com.microsoft.graph.http.IHttpRequest;
18+
import com.microsoft.graph.httpcore.ICoreAuthenticationProvider;
1819

20+
import okhttp3.Request;
1921

20-
public class AuthorizationCodeProvider extends BaseAuthentication implements IAuthenticationProvider{
22+
23+
public class AuthorizationCodeProvider extends BaseAuthentication implements IAuthenticationProvider, ICoreAuthenticationProvider{
2124

2225
/*
2326
* Authorization code provider initialization
@@ -68,7 +71,13 @@ public AuthorizationCodeProvider(
6871
}
6972

7073
@Override
71-
public void authenticateRequest(HttpRequest request) {
74+
public Request authenticateRequest(Request request) {
75+
String tokenParameter = AuthConstants.BEARER + getAccessTokenSilent();
76+
return request.newBuilder().addHeader(AuthConstants.AUTHORIZATION_HEADER, tokenParameter).build();
77+
}
78+
79+
@Override
80+
public void authenticateRequest(IHttpRequest request) {
7281
String tokenParameter = AuthConstants.BEARER + getAccessTokenSilent();
7382
request.addHeader(AuthConstants.AUTHORIZATION_HEADER, tokenParameter);
7483
}

src/main/java/com/microsoft/graph/auth/confidentialClient/ClientCredentialProvider.java

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import java.util.List;
44

5-
import org.apache.http.HttpRequest;
65
import org.apache.oltu.oauth2.client.OAuthClient;
76
import org.apache.oltu.oauth2.client.URLConnectionClient;
87
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
@@ -14,9 +13,13 @@
1413
import com.microsoft.graph.auth.AuthConstants;
1514
import com.microsoft.graph.auth.BaseAuthentication;
1615
import com.microsoft.graph.auth.enums.NationalCloud;
17-
import com.microsoft.graph.httpcore.IAuthenticationProvider;
16+
import com.microsoft.graph.authentication.IAuthenticationProvider;
17+
import com.microsoft.graph.http.IHttpRequest;
18+
import com.microsoft.graph.httpcore.ICoreAuthenticationProvider;
1819

19-
public class ClientCredentialProvider extends BaseAuthentication implements IAuthenticationProvider{
20+
import okhttp3.Request;
21+
22+
public class ClientCredentialProvider extends BaseAuthentication implements IAuthenticationProvider, ICoreAuthenticationProvider{
2023

2124
/*
2225
* Client credential provider instance using client secret
@@ -42,20 +45,31 @@ public ClientCredentialProvider(String clientId,
4245
}
4346

4447
@Override
45-
public void authenticateRequest(HttpRequest request) {
48+
public void authenticateRequest(IHttpRequest request) {
49+
String accessToken = getAcccessToken();
50+
request.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BEARER + accessToken);
51+
}
52+
53+
@Override
54+
public Request authenticateRequest(Request request) {
55+
String accessToken = getAcccessToken();
56+
return request.newBuilder().addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BEARER + accessToken).build();
57+
}
58+
59+
String getAcccessToken() {
60+
String accessToken = "";
4661
try {
47-
String accessToken = null;
4862
long duration = System.currentTimeMillis() - getStartTime();
4963
if(getResponse()!=null && duration>0 && duration< getResponse().getExpiresIn()*1000) {
5064
accessToken = getResponse().getAccessToken();
5165
} else {
5266
OAuthClientRequest authRequest = getTokenRequestMessage();
5367
accessToken = getAccessTokenNewRequest(authRequest);
5468
}
55-
request.addHeader(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BEARER + accessToken);
5669
} catch (Exception e) {
5770
e.printStackTrace();
5871
}
72+
return accessToken;
5973
}
6074

6175
/*

src/main/java/com/microsoft/graph/auth/publicClient/UsernamePasswordProvider.java

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import java.util.List;
44

5-
import org.apache.http.HttpRequest;
65
import org.apache.oltu.oauth2.client.OAuthClient;
76
import org.apache.oltu.oauth2.client.URLConnectionClient;
87
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
@@ -14,9 +13,13 @@
1413
import com.microsoft.graph.auth.AuthConstants;
1514
import com.microsoft.graph.auth.BaseAuthentication;
1615
import com.microsoft.graph.auth.enums.NationalCloud;
17-
import com.microsoft.graph.httpcore.IAuthenticationProvider;
16+
import com.microsoft.graph.authentication.IAuthenticationProvider;
17+
import com.microsoft.graph.http.IHttpRequest;
18+
import com.microsoft.graph.httpcore.ICoreAuthenticationProvider;
1819

19-
public class UsernamePasswordProvider extends BaseAuthentication implements IAuthenticationProvider{
20+
import okhttp3.Request;
21+
22+
public class UsernamePasswordProvider extends BaseAuthentication implements IAuthenticationProvider, ICoreAuthenticationProvider{
2023

2124
private String Username;
2225
private String Password;
@@ -40,16 +43,27 @@ public UsernamePasswordProvider(
4043
super( scopes,
4144
clientId,
4245
GetAuthority(nationalCloud == null? NationalCloud.Global: nationalCloud, tenant == null? AuthConstants.Tenants.Organizations: tenant),
43-
null,
46+
null,
4447
nationalCloud == null? NationalCloud.Global: nationalCloud,
45-
tenant,
48+
tenant == null? AuthConstants.Tenants.Organizations: tenant,
4649
clientSecret);
4750
this.Username = username;
4851
this.Password = password;
4952
}
53+
54+
@Override
55+
public Request authenticateRequest(Request request) {
56+
String accessToken = getAccessToken();
57+
return request.newBuilder().addHeader("Authorization", AuthConstants.BEARER + accessToken).build();
58+
}
5059

5160
@Override
52-
public void authenticateRequest(HttpRequest request) {
61+
public void authenticateRequest(IHttpRequest request) {
62+
String accessToken = getAccessToken();
63+
request.addHeader("Authorization", AuthConstants.BEARER + accessToken);
64+
}
65+
66+
String getAccessToken() {
5367
String accessToken = getAccessTokenSilent();
5468
if(accessToken == null) {
5569
try {
@@ -59,7 +73,7 @@ public void authenticateRequest(HttpRequest request) {
5973
e.printStackTrace();
6074
}
6175
}
62-
request.addHeader("Authorization", AuthConstants.BEARER + accessToken);
76+
return accessToken;
6377
}
6478

6579
OAuthClientRequest getTokenRequestMessage() throws OAuthSystemException {

0 commit comments

Comments
 (0)