Skip to content

Latest commit

 

History

History
78 lines (60 loc) · 1.95 KB

callback.adoc

File metadata and controls

78 lines (60 loc) · 1.95 KB

Implement the Callback

Now we need to convert the code that we received into an access_token

  1. 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();
    }
  2. Go to http://localhost:8080/ and click Login with Github button again

    callback access token
  3. Extract access_token in a type safe manner, add a token class

    class 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 + '\'' +
            '}';
      }
    }
  4. 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;
    }
  5. [Optional] Register your own oauth2 app https://github.com/settings/applications/new

    • upon successful registration you will get your own client_id and client_secret, change the above code to use your own app’s info