To get oauth2 token with the WWW
API, use the WWWForm
to create form that contains the grant_type
, client_id
and client_secret
. When you make the request, the token should be returned in Json format. Use Unity's JsonUtility
to convert it to string you can easily obtain.
Retrieving Token:
[Serializable]
public class TokenClassName
{
public string access_token;
}
IEnumerator GetAccessToken()
{
var url = "http://yoururl.com";
var form = new WWWForm();
form.AddField("grant_type", "client_credentials");
form.AddField("client_id", "login-secret");
form.AddField("client_secret", "secretpassword");
WWW www = new WWW(url, form);
//wait for request to complete
yield return www;
//and check for errors
if (String.IsNullOrEmpty(www.error))
{
string resultContent = www.text;
UnityEngine.Debug.Log(resultContent);
TokenClassName json = JsonUtility.FromJson<TokenClassName>(resultContent);
UnityEngine.Debug.Log("Token: " + json.access_token);
}
else
{
//something wrong!
UnityEngine.Debug.Log("WWW Error: " + www.error);
}
}
Using the Token:
After you receive the token, it will be stored in the json.access_token
variable. You can use then use that to make requests by adding it to the Header of your other WWW
requests. That header is stored in a Dictionary like this:
headers.Add("Authorization", "Bearer " + token);
Here is an full example for making a request with the received token:
IEnumerator makeRequestWithToken(string token)
{
var url = "http://yoururl.com";
Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("Authorization", "Bearer " + token);
WWWForm formData = new WWWForm();
formData.AddField("YourField", "YourVal");
formData.AddField("YourField", "YourVal");
WWW www = new WWW(url, formData.data, headers);
yield return www;
//and check for errors
if (String.IsNullOrEmpty(www.error))
{
string resultContent = www.text;
UnityEngine.Debug.Log(resultContent);
}
else
{
//something wrong!
UnityEngine.Debug.Log("WWW Error: " + www.error);
}
}
Unity now uses UnityWebRequest
. If possible start using that. Here is an example of retrieving oauth2 with UnityWebRequest
.
Note that both functions are coroutine functions and must be started with the StartCoroutine
function like StartCoroutine(GetAccessToken());
and StartCoroutine(makeRequestWithToken("YourToken"));
.