I have implemented some code to access an oauth 2.0 protected api. The Unity Engine freezes as soon as I hit "play" button. and I have to close it via Task Manager.
My Code:
public class importFromAPI : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
HttpClient client = new HttpClient();
Task<Token> task = GetElibilityToken(client);
//Token token = task.Result;
}
// Update is called once per frame
void Update()
{
}
// OAuth Stuff
private static async Task<Token> GetElibilityToken(HttpClient client)
{
string baseAddress = @"*REDACTED*/oauth/token";
string grant_type = "client_credentials";
string client_id = "*REDACTED*";
string client_secret = "*REDACTED*";
string audience = "*REDACTED*";
var form = new Dictionary<string, string>
{
{"grant_type", grant_type},
{"client_id", client_id},
{"client_secret", client_secret},
{"audience", audience }
};
HttpResponseMessage tokenResponse = await client.PostAsync(baseAddress, new FormUrlEncodedContent(form));
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
Debug.Log("Response: " + jsonContent);
Token tok = JsonConvert.DeserializeObject<Token>(jsonContent);
Debug.Log(tok.ToString());
return tok;
}
internal class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
override
public string ToString()
{
return "AccessToken: " + AccessToken + "; TokenType: " + TokenType + "; Expires in: " + ExpiresIn + "; Refresh Token: " + RefreshToken;
}
}
}
Removing task.Result from the Start() method stops Unity from freezing on pressing the button, but I want to get the token to access the api afterwards.
Can anyone tell me why Unity freezes?