c# - How to get oauth2 token with the WWW API? -
i working on project requires oauth2 token communicate. backend gives me curl command, have no idea how put www form in unity because have no former experience http or json file. me access token? thanks. here how curl code looks like:
$ curl -v -u {client_id}:{client_secret} "https://api.domo.com/oauth/token?grant_type=client_credentials&scope={scope}"
and here example:
$ curl -v -u 441e307a-b2a1-4a99-8561-174e5b153fsa:f103fc453d08bdh049edc9a1913e3f5266447a06d1d2751258c89771fbcc8087 "https://api.domo.com/oauth/token?grant_type=client_credentials&scope=data%20user"
thank much!
to oauth2 token www
api, use wwwform
create form contains grant_type
, client_id
, client_secret
. when make request, token should returned in json format. use unity's jsonutility
convert string can 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 request complete yield return www; //and check 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 token:
after receive token, stored in json.access_token
variable. can use use make requests adding header of other www
requests. header stored in dictionary this:
headers.add("authorization", "bearer " + token);
here full example making request 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 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 uses unitywebrequest
. if possible start using that. here example of retrieving oauth2 unitywebrequest
.
note both functions coroutine functions , must started startcoroutine
function startcoroutine(getaccesstoken());
, startcoroutine(makerequestwithtoken("yourtoken"));
.
Comments
Post a Comment