アクセストークンを要求するには、認証データを送信する要求を行うだけです。このコードは、リソースの所有者のパスワードの資格情報を使用して作業MVCアプリから抽出された付与します
using (var client = new HttpClient())
{
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("username", _user));
postData.Add(new KeyValuePair<string, string>("password", _pwd));
postData.Add(new KeyValuePair<string, string>("grant_type", "password"));
postData.Add(new KeyValuePair<string, string>("client_id", _clientId));
postData.Add(new KeyValuePair<string, string>("client_secret", _clientSecret));
HttpContent content = new FormUrlEncodedContent(postData);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var responseResult = client.PostAsync(_tokenUrl, content).Result;
return responseResult.Content.ReadAsStringAsync().Result;
}
は、私はそれが役に立てば幸い。
EDITここ
あなたはトークンをリフレッシュするコードスニペットを持っている:
using (var client = new HttpClient())
{
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("refresh_token", _refreshToken));
postData.Add(new KeyValuePair<string, string>("grant_type", "refresh_token"));
postData.Add(new KeyValuePair<string, string>("client_id", _clientId));
postData.Add(new KeyValuePair<string, string>("client_secret", _clientSecret));
HttpContent content = new FormUrlEncodedContent(postData);
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
var responseResult = client.PostAsync(_tokenUrl, content).Result;
return responseResult.Content.ReadAsStringAsync().Result;
}
そして、それを使用して:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
HttpResponseMessage result = client.GetAsync(_url).Result;
if (result.StatusCode == HttpStatusCode.Unauthorized)
{
RefreshToken(); /* Or reenter resource owner credentials if refresh token is not implemented */
if (/* token refreshed, repeat the request using the new access token */)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _newAccessToken);
result = client.GetAsync(_url).Result;
if (result.StatusCode == HttpStatusCode.Unauthorized)
{
// Process the error
}
}
}
return result;
}
感謝を!これで、トークンを取得できるようになりました(「スコープ」の追加などの少しの変更を加えて)。私はこれを答えにすることができます。だから、後続のリクエストでトークンを付けるだけでうまくいきます。しかし、毎回トークンを生成すべきかどうか疑問に思ったり、C#は期限が切れるまで同じトークンを扱い、期限切れになったら再生成します。それを行う良い方法は何ですか?どんなコード例も歓迎されます! –
401 - Unauthorizedレスポンスが得られるまで同じトークンを添付する必要があります。その後、リソース所有者の資格情報を掲示するか、認可サーバーがこの機能を実装する場合はリフレッシュトークンを使用するかによって、新しいアクセストークンを取得する必要があります。リフレッシュトークン付与要求は、資格情報1に類似していますが、資格情報を再入力する必要がない、ユーザーにとって透過的です。編集した新しいコードスニペットの回答をご覧ください。 – jumuro
ありがとうございます。私はこれを使って遊んでいます。セッションごとに鍵を生成する必要があることを理解しています。鍵が期限切れになった場合は、トークンを更新します。つまり、ユーザーがブラウザを閉じて後で戻ってくると、APIを使用するときにトークンが生成されます。あれは正しいですか? –