Spring Boot OAuth2 인증서버 적용기 - 3

황남욱·2021년 12월 14일
0
post-thumbnail

지난편에서 curl 로 access_token을 받아보았는데요

이번에는 redirect_uri로 설정한 /oauth2/callback 컨트롤러를 구성해서 화면에서 access_token 을 볼 수 있도록 만들어보려고합니다.

/oauth/token의 response를 담을 Class가 필요합니다.

OAuthToken


@Getter
@Setter
public class OAuthToken {
    private String access_token;
    private String token_type;
    private String refresh_token;
    private long expires_in;
    private String scope;
}

그리고 /oauth/token에서 받아온 데이터를 파싱하기위해 Gson 의존성을 추가합니다.

build.gradle

implementation 'com.google.code.gson:gson'

이제 컨트롤러를 구성해봅시다.

OAuthTestController


@RequiredArgsConstructor
@RestController
@RequestMapping("/oauth2")
public class OAuthTestController {

    private final Gson gson;
    private final RestTemplate restTemplate;

    @GetMapping(value="/callback")
    public OAuthToken callbackSocial(@RequestParam("code")String code) {
        String credentials = "foo:bar";
        String encodedCredentials = new String(Base64.encodeBase64(credentials.getBytes()));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Authorization", "Basic "+ encodedCredentials);

        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("code", code);
        params.add("grant_type", "authorization_code");
        params.add("redirect_uri", "http://localhost:1995/oauth2/callback");

        HttpEntity<MultiValueMap<String,String>> request = new HttpEntity<>(params, headers);
        ResponseEntity<String> response = restTemplate.postForEntity("http://localhost:1995/oauth/token", request, String.class);
        if(response.getStatusCode() == HttpStatus.OK) {
            return gson.fromJson(response.getBody(), OAuthToken.class);
        }
        return null;
    }
}

파라미터로 code를 받아오는 컨트롤러를 생성했습니다.

credentials : client_id:client_secret 암호화 값

이 상태에서 지난번 테스트 한 url을 다시 접속해보면

위 와 같이 화면에서 access_token을 확인할 수 있습니다.

profile
안녕하세요👋 주니어 백엔드 개발자입니다.

0개의 댓글