Hi
I am working on writing an api in java to read the calendar events from outlook calendar. I am using using grails and the azure-activedirectory-library-for-java in my application.
Following is the code I have written to get the access token
def getAuthToken(String client_id, String client_secret, def params){
private final static String AUTHORITY = "https://login.microsoftonline.com/common/oauth2/token";
JSONObject json = new JSONObject();
String authCode = params.code;
String currentUri = "http://xxxxxx.xxxxxx.in/Calendar/calendar/getAuthToken"; // this is the redirect_uri in my azure app
ClientCredential credential = new ClientCredential(client_id,
client_secret);
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newFixedThreadPool(1);
context = new AuthenticationContext(AUTHORITY, true, service);
Future<AuthenticationResult> future = context.acquireTokenByAuthorizationCode(authCode, new URI(currentUri), credential, null);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
} finally {
service.shutdown();
}
if (result == null) {
throw new ServiceUnavailableException(
"authentication result was null");
}
json.access_token = result.getAccessToken();
json.refresh_token = result.getRefreshToken();
return json;
}
I am getting the access token from this but when I am using it in my method to get the calendar events I am getting error.
My code to get the calendar events
def getEvents(String auth_token){
JSONObject result = new JSONObject();
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
isoFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Date startTime = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(startTime);
cal.add(Calendar.DATE, 1);
Date endTime = cal.getTime();
String startTimeUrl = isoFormat.format(startTime);
String endTimeUrl = isoFormat.format(endTime);
StringBuffer calendarViewUrl = new StringBuffer();
// calendarViewUrl.append("https://outlook.office365.com/api/v1.0")
calendarViewUrl.append("https://outlook.office365.com/api")
.append("/Me/CalendarView?")
.append("startDateTime=").append(startTimeUrl).append("&endDateTime=")
.append(endTimeUrl).append("&\$select=Subject,Start,End").append("&\$orderby=Start");
result = makeApiCall(auth_token, calendarViewUrl.toString());
return result;
}
def makeApiCall( String auth_token, String calendarViewUrl){
JSONObject result = new JSONObject();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(calendarViewUrl);
try {
httpGet.setHeader("User-Agent", USER_AGENT);
httpGet.setHeader("Authorization","Bearer "+auth_token);
httpGet.setHeader("Accept", "application/json");
httpGet.setHeader("client-request-id", java.util.UUID.randomUUID().toString());
httpGet.setHeader("return-client-request-id", "true");
HttpResponse response = httpClient.execute(httpGet);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
// EntityUtils to get the response content
// result = new JSONObject( (org.apache.http.util.EntityUtils.toString(respEntity)).trim() );
System.out.println(org.apache.http.util.EntityUtils.toString(respEntity).isEmpty());
}
} catch (Exception e) {
// writing exception to log
e.printStackTrace();
}
return result;
}
This is my response body from makeApiCall()
HTTP/1.1 401 Unauthorized [Content-Length: 0, Server: Microsoft-IIS/8.0, request-id: 76e71807-f4d4-4444-9f9b-f94f8bb3522f, client-request-id: 238d543c-9cd0-40a8-afea-5b4d87cc42ce, Set-Cookie: ClientId=W28GZPKKVKNKJ8LT5BVTA; expires=Tue, 29-Nov-2016 14:19:12
GMT; path=/; secure; HttpOnly, X-CalculatedBETarget: HK2PR03MB0690.apcprd03.prod.outlook.com, X-BackEndHttpStatus: 401, Set-Cookie: exchangecookie=3e6de459ef824c2da4765e80d47056bc; expires=Wed, 30-Nov-2016 14:19:13 GMT; path=/; HttpOnly, client-request-id:
238d543c-9cd0-40a8-afea-5b4d87cc42ce, x-ms-diagnostics: 2000001;reason="OAuth token submitted with the request can not be parsed.";error_category="invalid_token", X-DiagInfo: HK2PR03MB0690, X-BEServer: HK2PR03MB0690, Set-Cookie: ClientId=W28GZPKKVKNKJ8LT5BVTA;
expires=Tue, 29-Nov-2016 14:19:12 GMT; path=/; secure; HttpOnly, X-Powered-By: ASP.NET, X-FEServer: HKXPR03CA0086, WWW-Authenticate: Bearer client_id="00000002-0000-0ff1-ce00-000000000000", trusted_issuers="00000001-0000-0000-c000-000000000000@*",
token_types="app_asserted_user_v1 service_asserted_app_v1", authorization_uri="https://login.windows.net/common/oauth2/authorize", error="invalid_token",Basic Realm="",Basic Realm="", Date: Mon, 30 Nov 2015
14:19:12 GMT] org.apache.http.conn.BasicManagedEntity@6f967ae3
Please if anybody knows the problem and solution kindly help
Thanks in advance
Abhisek Sai Deo