@RequestMapping(value = { "/beginOauth" }, method = { RequestMethod.GET, RequestMethod.POST })
public String startOauth(HttpServletRequest request) {
logger.debug("in beginOauth");
String randomUuid = UUID.randomUUID().toString();
StringBuilder sb = new StringBuilder();
sb.append("redirect:");
sb.append("https://");
sb.append("princeton.beta.instructure.com");
sb.append("/login/oauth2/auth");
sb.append("?");
sb.append("client_id=");
sb.append(Constants.CLIENT_ID);
sb.append("&state=");
sb.append(randomUuid);
sb.append("&response_type=code");
sb.append("&redirect_uri=");
sb.append("http://localhost:3010");
sb.append("/oauthResponse");
logger.debug("returning from start oauth: " + sb.toString());
return sb.toString();
}
@RequestMapping("/oauthResponse")
public String oauthResponse(HttpServletRequest request, @ModelAttribute(value = "code") String oauthCode,
@ModelAttribute(value = "state") String state, @ModelAttribute(value = "error") String errorMsg)
throws Exception {
if (oauthCode != null && !oauthCode.trim().isEmpty()) {
try {
logger.debug("got oauth code back: " + oauthCode);
URL tokenUrl = new URL("https://princeton.beta.instructure.com" + "/login/oauth2/token");
HttpURLConnection con = (HttpURLConnection) tokenUrl.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
OutputStream out = null;
try {
out = (OutputStream) con.getOutputStream();
} catch (Exception ex) {
logger.error(ex.toString());
}
StringBuilder paramsBuilder = new StringBuilder();
paramsBuilder.append("client_id=");
paramsBuilder.append(Constants.CLIENT_ID);
paramsBuilder.append("&client_secret=");
paramsBuilder.append(Constants.CLIENT_KEY);
paramsBuilder.append("&code=");
paramsBuilder.append(oauthCode);
paramsBuilder.append("&redirect_uri=");
paramsBuilder.append("http://localhost:3010");
paramsBuilder.append("/oauthResponse");
logger.debug("sending params to get oauth token: " + paramsBuilder.toString());
out.write(paramsBuilder.toString().getBytes());
out.flush();
out.close();
int responseCode = con.getResponseCode();
logger.debug("got response code from token request: " + responseCode);
logger.debug("response message: " + con.getResponseMessage());
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
logger.debug("content: " + content.toString());
JsonObject jobj = new Gson().fromJson(content.toString(), JsonObject.class);
String accessToken = jobj.get("access_token").getAsString();
String refreshToken = jobj.get("refresh_token").getAsString();
} catch (IOException e) {
logger.error("error getting oauth token", e);
}
}
return "redirect:http://localhost:3010/hello";
}