Now we need to convert the code
that we received into an access_token
-
Add a controller to response to the callback request
RestTemplate restTemplate = new RestTemplate(); @GetMapping("/callback") @ResponseBody Object callback(@RequestParam String code) { HashMap response = restTemplate.postForEntity("https://github.com/login/oauth/access_token?" + "client_id=13e67f9acf45a46a6567&" + "client_secret=dc51ddd68a03ff435a497b3023b44a37b55fbc1d&" + "code=" + code, null, HashMap.class).getBody(); return response.toString(); }
-
Go to http://localhost:8080/ and click
Login with Github
button again -
Extract
access_token
in a type safe manner, add a token classclass GithubTokenResponse { private final String accessToken; @JsonCreator public GithubTokenResponse( @JsonProperty("access_token") String accessToken) { this.accessToken = accessToken; } public String getAccessToken() { return accessToken; } @Override public String toString() { return "GithubTokenResponse{" + "accessToken='" + accessToken + '\'' + '}'; } }
-
Change callback controller
@GetMapping("/callback") @ResponseBody Object callback(@RequestParam String code) { GithubTokenResponse response = restTemplate.postForEntity("https://github.com/login/oauth/access_token?" + "client_id=13e67f9acf45a46a6567&" + "client_secret=dc51ddd68a03ff435a497b3023b44a37b55fbc1d&" + "code=" + code, null, GithubTokenResponse.class).getBody(); return response; }
-
[Optional] Register your own oauth2 app https://github.com/settings/applications/new
-
upon successful registration you will get your own
client_id
andclient_secret
, change the above code to use your own app’s info
-