악의적인 접근 또는 공격을 방지하기 위해 가급적 state, code를 검증해주세요.
private String requestedState = "RandomChars"; //saved state
@GetMapping("/callbak")
public String index(HttpServletRequest request) throws Exception{
String state = request.getParameter("state");
String code = request.getParameter("code");
if(!requestedState.equals(state)){
throw new Exception("Invalid state");
}
if(!StringUtils.hasText(code)) {
throw new Exception("Invalid code");
}
//... process call api
}
private string requestedState = "RandomChars"; //saved state
[Route("/callback")]
public IActionResult Index(string code, string state)
{
if (!requestedState.Equals(state))
{
throw new Exception("Invalid state");
}
if (string.IsNullOrEmpty(code))
{
throw new Exception("Invalid code");
}
//... process call api
}
final private static String apiBaseURL = "https://auth.smtown.com";
final private static String tokenEndPoint = "oauth/token";
final private static String basicAuthorization = "MGYxOWYxNG==";
public static void main(String[] args){
//implementation 'org.apache.httpcomponents:httpclient'
String code = "Hs56CB";
if(!StringUtils.hasText(code)){ //전달 받은 코드가 없으면 에러처리
return;
}
try (CloseableHttpClient client = HttpClients.createDefault()) {
List<NameValuePair> data = new ArrayList<>(Arrays.asList(
new BasicNameValuePair( "code", code ),
new BasicNameValuePair( "grant_type", "authorization_code" ),
new BasicNameValuePair( "scope", "profile.info" ),
new BasicNameValuePair( "redirect_uri", "http://localhost:8080/popup/callback" )
));
HttpPost post = new HttpPost(String.format("%s/%s", apiBaseURL, tokenEndPoint));
post.setHeader("Authorization", String.format("Basic %s", basicAuthorization));
post.setEntity(new UrlEncodedFormEntity(data, StandardCharsets.UTF_8));
try(CloseableHttpResponse response = client.execute(post)) {
if(response.getStatusLine().getStatusCode() == 200) {
String responseData = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
System.out.println(responseData);
/**
* {
* "access_token":"2a324609ec94f18",
* "token_type":"bearer",
* "refresh_token":"0f244a6ff13c8fcf2",
* "expires_in":35274,
* "scope":"profile.info"
* }
*/
}
}
} catch (IOException e){
throw new RuntimeException();
}
}
private readonly string ApiBaseURL = "https://auth.smtown.com";
private readonly string TokenEndPoint = "oauth/token";
private readonly string BasicAuthorization = "MGYxOWYxNG==";
private async void GetAccessToken()
{
string code = "Hs56CB";
if(string.isNullOrEmpty(code)){ //전달 받은 코드가 없으면 에러처리
return;
}
var data = new Dictionary<string, string> {
{ "code", code },
{ "grant_type", "authorization_code" },
{ "scope", "profile.info" },
{ "redirect_uri", "http://localhost:8080/popup/callback" }
};
using System.Net.Http.HttpClient client = new(); System.Net.Http.HttpRequestMessage tokenRequest = new()
{
Method = HttpMethod.Post,
RequestUri = new Uri(string.Format("{0}/{1}", ApiBaseURL, TokenEndPoint)),
Content = new FormUrlEncodedContent(data)
};
tokenRequest.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded") { CharSet = "UTF-8" };
tokenRequest.Headers.TryAddWithoutValidation("Authorization", string.Format("Basic {0}", BasicAuthorization));
var response = await client.SendAsync(tokenRequest);
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseData);
/**
* {
* "access_token":"2a324609ec94f18",
* "token_type":"bearer",
* "refresh_token":"0f244a6ff13c8fcf2",
* "expires_in":35274,
* "scope":"profile.info"
* }
*/
}
}