|
| 1 | +package com.baeldung.spring.controller.scribe; |
| 2 | + |
| 3 | +import com.github.scribejava.apis.GitHubApi; |
| 4 | +import com.github.scribejava.core.builder.ServiceBuilder; |
| 5 | +import com.github.scribejava.core.model.*; |
| 6 | +import com.github.scribejava.core.oauth.OAuth20Service; |
| 7 | +import org.springframework.stereotype.Controller; |
| 8 | +import org.springframework.web.bind.annotation.GetMapping; |
| 9 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 10 | +import org.springframework.web.bind.annotation.RequestParam; |
| 11 | +import org.springframework.web.bind.annotation.ResponseBody; |
| 12 | +import org.springframework.web.servlet.view.RedirectView; |
| 13 | + |
| 14 | +import javax.servlet.http.HttpServletRequest; |
| 15 | +import java.io.IOException; |
| 16 | +import java.util.Random; |
| 17 | +import java.util.concurrent.ExecutionException; |
| 18 | + |
| 19 | +@Controller |
| 20 | +@RequestMapping("github") |
| 21 | +public class GithubController { |
| 22 | + private OAuth20Service createService(String state) { |
| 23 | + return new ServiceBuilder("e1f8d4f1a5c71467a159") |
| 24 | + .apiSecret("4851597541a8f33a4f1bf1c70f3cedcfefbeb13b") |
| 25 | + .state(state) |
| 26 | + .callback("http://localhost:8080/spring-mvc-simple/github/callback") |
| 27 | + .build(GitHubApi.instance()); |
| 28 | + } |
| 29 | + |
| 30 | + @GetMapping(value = "/authorization") |
| 31 | + public RedirectView authorization(HttpServletRequest servletReq) throws InterruptedException, ExecutionException, IOException { |
| 32 | + String state = String.valueOf(new Random().nextInt(999_999)); |
| 33 | + OAuth20Service githubService = createService(state); |
| 34 | + servletReq.getSession().setAttribute("state", state); |
| 35 | + |
| 36 | + String authorizationUrl = githubService.getAuthorizationUrl(); |
| 37 | + RedirectView redirectView = new RedirectView(); |
| 38 | + redirectView.setUrl(authorizationUrl); |
| 39 | + return redirectView; |
| 40 | + } |
| 41 | + |
| 42 | + @GetMapping(value = "/callback", produces = "text/plain") |
| 43 | + @ResponseBody |
| 44 | + public String callback(HttpServletRequest servletReq, @RequestParam("code") String code, @RequestParam("state") String state) throws InterruptedException, ExecutionException, IOException { |
| 45 | + String initialState = (String) servletReq.getSession().getAttribute("state"); |
| 46 | + if(initialState.equals(state)) { |
| 47 | + OAuth20Service githubService = createService(initialState); |
| 48 | + OAuth2AccessToken accessToken = githubService.getAccessToken(code); |
| 49 | + |
| 50 | + OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.github.com/user"); |
| 51 | + githubService.signRequest(accessToken, request); |
| 52 | + Response response = githubService.execute(request); |
| 53 | + |
| 54 | + return response.getBody(); |
| 55 | + } |
| 56 | + return "Error"; |
| 57 | + } |
| 58 | +} |
0 commit comments