Java Microsoft OAuth2 get Access Token

private String getAccessToken(String authorizationCode, String clientId, String clientSecret, String redirectUri)  throws Exception {
        String accessToken = "";
        try {

            LOGGER.info("GET MSFT Access Token---code---" + code);

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost("https://login.live.com/oauth20_token.srf");

            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            urlParameters.add(new BasicNameValuePair("grant_type", "authorization_code"));
            urlParameters.add(new BasicNameValuePair("client_id", clientId));
            urlParameters.add(new BasicNameValuePair("client_secret", clientSecret));
            urlParameters.add(new BasicNameValuePair("code", code));
            urlParameters.add(new BasicNameValuePair("redirect_uri", redirectUri));

            postRequest.setEntity(new UrlEncodedFormEntity(urlParameters));

            HttpResponse response = httpClient.execute(postRequest);

            if (response.getStatusLine().getStatusCode() != 200) {
                 throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuilder sb = new StringBuilder();
            String output;

            while ((output = br.readLine()) != null) {
                sb.append(output);
            }
            br.close();
            LOGGER.info("MSFT JSON Object" + sb);

            JSONObject jsonObject = new JSONObject(sb.toString());
            accessToken = jsonObject.getString("access_token");

            httpClient.getConnectionManager().shutdown();

        } catch (IOException | JSONException e) {
            LOGGER.error("Error in MSFT getAccessToken()", e);
        }
        return accessToken;
    }

No comments:

Post a Comment