OneDrive
A Microsoft file hosting and synchronization service.
1,076 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
In the Code Flow stage cannot able to Redeem the code for access tokens getting 401 error my code
@RequestMapping("/oauth2/callback/microsoft")
public ResponseEntity<Response> callbackUrl(
HttpServletRequest request,
HttpSession httpSession) {
String code = request.getParameter("code");
String tokenEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
String clientId = "";
String redirectUri = "http://localhost:8080/oauth2/callback/microsoft";
String clientSecret = "";
String grantType = "authorization_code";
try {
URL url = new URL(tokenEndpoint);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Set the request method to POST
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setDoOutput(true);
// Create the request body
String requestBody = "client_id=" + clientId +
"&redirect_uri=" + redirectUri +
"&client_secret=" + clientSecret +
"&code=" + code +
"&grant_type=" + grantType;
// Write the request body to the connection
try (OutputStream os = conn.getOutputStream()) {
byte[] input = requestBody.getBytes("utf-8");
os.write(input, 0, input.length);
}
// Get the response
int responseCode = conn.getResponseCode();
Response response3 = new Response(201, "error:"+responseCode);
if (responseCode == 200) {
Scanner scanner = new Scanner(conn.getInputStream());
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println("Access Token Response: " + responseBody);
scanner.close();
conn.disconnect();
// Return a success message or data as needed
} else {
Scanner scanner = new Scanner(conn.getInputStream());
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println("Access Token Response: " + responseBody);
scanner.close();
conn.disconnect();
}
return new ResponseEntity<Response>(response3, HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
Response response3 = new Response(201, "error:"+e);
return new ResponseEntity<Response>(response3, HttpStatus.OK);
}
}