简体   繁体   English

如何使用WWW API获取oauth2令牌?

[英]How to get oauth2 token with the WWW API?

I am working on a project that requires to oauth2 token to communicate. 我正在一个需要oauth2令牌进行通信的项目中。 The backend gives me a curl command, but I have no idea how to put it into WWW form in Unity because I have no former experience with http or json file. 后端给了我一个curl命令,但是我不知道如何在Unity中将其放入WWW表单,因为我以前没有使用过http或json文件的经验。 Could you help me to access the token? 您能帮我访问令牌吗? Thanks. 谢谢。 Here how the curl code looks like: 卷曲代码如下所示:

$ curl -v -u {CLIENT_ID}:{CLIENT_SECRET} " https://api.domo.com/oauth/token?grant_type=client_credentials&scope= {SCOPE}" $ curl -v -u {CLIENT_ID}:{CLIENT_SECRET}“ https://api.domo.com/oauth/token?grant_type=client_credentials&scope= {SCOPE}”

and here is an example: 这是一个示例:

$ curl -v -u 441e307a-b2a1-4a99-8561-174e5b153fsa:f103fc453d08bdh049edc9a1913e3f5266447a06d1d2751258c89771fbcc8087 " https://api.domo.com/oauth/token?grant_type=client_credentials&scope=data%20user " $ curl -v -u 441e307a-b2a1-4a99-8561-174e5b153fsa:f103fc453d08bdh049edc9a1913e3f5266447a06d1d2751258c89771fbcc8087“ https://api.domo.com/oauth/token?grant_type=client_credentials&scope=

Thank you so much! 非常感谢!

To get oauth2 token with the WWW API, use the WWWForm to create form that contains the grant_type , client_id and client_secret . 要使用WWW API获取oauth2令牌,请使用WWWForm创建包含grant_typeclient_idclient_secret表单。 When you make the request, the token should be returned in Json format. 发出请求时,令牌应以Json格式返回。 Use Unity's JsonUtility to convert it to string you can easily obtain. 使用Unity的JsonUtility将其转换为可以轻松获取的字符串。

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. 收到令牌后,它将存储在json.access_token变量中。 You can use then use that to make requests by adding it to the Header of your other WWW requests. 您可以使用该请求,然后将其添加到其他WWW请求的标头中,以发出请求。 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 . 现在,Unity使用UnityWebRequest If possible start using that. 如果可能的话,开始使用它。 Here is an example of retrieving oauth2 with UnityWebRequest . 是使用UnityWebRequest检索oauth2的UnityWebRequest

Note that both functions are coroutine functions and must be started with the StartCoroutine function like StartCoroutine(GetAccessToken()); 请注意,这两个函数都是协程函数,必须使用StartCoroutine函数(如StartCoroutine(GetAccessToken()); and StartCoroutine(makeRequestWithToken("YourToken")); StartCoroutine(makeRequestWithToken("YourToken")); .

I got it working using the following method: Refer to Travis's fitbit code 我使用以下方法使其工作:请参阅Travis的fitbit代码

var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_clientID + ":" + _consumerSecret);  
var encoded = Convert.ToBase64String(plainTextBytes);  
var form = new WWWForm();  
form.AddField("client_id", _clientID);  
form.AddField("grant_type", "authorization_code");  
form.AddField("redirect_uri", WWW.UnEscapeURL(CallBackUrl));  
form.AddField("code", _returnCode);  
var headers = form.headers;  
headers["Authorization"] = "Basic " + encoded;  
_wwwRequest = new WWW("https://api.fitbit.com/oauth2/token", form.data, headers);  

Relate to your backend, see what kind of oauth2 they are using, you can see the oauth2 documentation Here . 有关您的后端,请查看他们使用的是哪种oauth2,您可以在此处查看oauth2文档。 Feel free to leave a comment for question. 随时发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在服务/守护程序应用程序中获取 EWS 托管 API 的 OAuth2 访问令牌 - How to get OAuth2 access token for EWS managed API in service/daemon application 如何使用C#访问Yelp Fusion Api的OAuth2令牌 - How to get access to OAuth2 token for Yelp Fusion Api using C# 如何从浏览器获取 OAuth2 不记名令牌? - How can I get an OAuth2 bearer token from the browser? 如何使用服务器端OAuth2(隐式授予)获取访问令牌? - How to get access token with Server Side OAuth2 (implicit grant)? 带有刷新令牌的协调API OAuth2身份验证 - Coordinate API OAuth2 authentication with refresh token WinRT-OAuth2获取访问令牌 - WinRT - OAuth2 get access token 从CefSharp获取OAuth2访问令牌 - Get OAuth2 access token from CefSharp 如何在Web Api OAuth中获取访问令牌? - How to get access token in Web Api OAuth? 如何将Daemon或Server的Azure AD OAuth2访问令牌和刷新令牌转换为C#ASP.NET Web API - How do I get Azure AD OAuth2 Access Token and Refresh token for Daemon or Server to C# ASP.NET Web API 无法从Google OAuth2令牌端点获取访问令牌 - Unable to get access token from Google OAuth2 Token endpoint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM