2016-06-21 13 views
1

クライアントは、私たちが開発しているWebサイトにAPIを統合する必要がありました。また、API認証はoAuth 2.0経由で行われます。彼らは、(クライアントID、クライアントシークレット、トークンウリなど)に関するすべての必要な情報を提供しています。oAuth 2.0 APIの消費量(C#経由)

しかし、C#でこれを呼び出すコードスニペットを理解するのは苦労します。要求トークンを要求し、それを後続の要求のヘッダーに添付する必要があることはわかっています。私たちはDotNetOpenAuthとOwinを試しましたが、これを実装するための実際のコードを見つけることができず、これまで成功していませんでした。 これを達成するための小さなコードのC#コードを手伝ってもらえますか?

答えて

3

アクセストークンを要求するには、認証データを送信する要求を行うだけです。このコードは、リソースの所有者のパスワードの資格情報を使用して作業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; 
} 
+0

感謝を!これで、トークンを取得できるようになりました(「スコープ」の追加などの少しの変更を加えて)。私はこれを答えにすることができます。だから、後続のリクエストでトークンを付けるだけでうまくいきます。しかし、毎回トークンを生成すべきかどうか疑問に思ったり、C#は期限が切れるまで同じトークンを扱い、期限切れになったら再生成します。それを行う良い方法は何ですか?どんなコード例も歓迎されます! –

+1

401 - Unauthorizedレスポンスが得られるまで同じトークンを添付する必要があります。その後、リソース所有者の資格情報を掲示するか、認可サーバーがこの機能を実装する場合はリフレッシュトークンを使用するかによって、新しいアクセストークンを取得する必要があります。リフレッシュトークン付与要求は、資格情報1に類似していますが、資格情報を再入力する必要がない、ユーザーにとって透過的です。編集した新しいコードスニペットの回答をご覧ください。 – jumuro

+0

ありがとうございます。私はこれを使って遊んでいます。セッションごとに鍵を生成する必要があることを理解しています。鍵が期限切れになった場合は、トークンを更新します。つまり、ユーザーがブラウザを閉じて後で戻ってくると、APIを使用するときにトークンが生成されます。あれは正しいですか? –

関連する問題