2016-07-27 16 views
1

WebApi2をMVCアプリケーションに追加しました。ブラウザからAPIを正常に呼び出すことができます。ユーザーが認証されていない場合は、標準のログイン画面が表示されてから動作します。WebAPI2にログインしてトークンを渡す方法

しかし、私は本当にモバイルアプリからREST APIとしてAPIを呼び出したいと思います。検索中に見つけたスタートアップに次のコードを追加しました。しかし、私は実際にどのようにURLを介してログインするか、または通話中にトークンを渡して使用する方法はわかりません。

myurl/api/Account/ExternalLoginを試しましたが、無効なリクエストがあります。

 PublicClientId = "self"; 
     OAuthOptions = new OAuthAuthorizationServerOptions 
     { 
      TokenEndpointPath = new PathString("/Token"), 
      Provider = new ApplicationOAuthProvider(PublicClientId), 
      AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 
      // Note: Remove the following line before you deploy to production: 
      AllowInsecureHttp = true 
     }; 

そこで問題は、私が実際にREST API呼び出しを使用するか、私は私のコントローラに追加のコードを配置する必要がありますか、です。

答えて

1

あなたのAPIはOAuthのを使用するように設定したら..あなたは

 /// <summary> 
     /// This method uses the OAuth Client Credentials Flow to get an Access Token to provide 
     /// Authorization to the APIs. 
     /// </summary> 
     /// <returns></returns> 
     private static async Task<string> GetAccessToken() 
     { 
      if (accessToken == null) 
      using (var client = new HttpClient()) 
      { 
       var email = "xyz" 
       var password = "abc"; 
       var clientId = "123" 
       var clientSecret = "456"; 

       client.BaseAddress = new Uri(baseUrl); 

       // We want the response to be JSON. 
       client.DefaultRequestHeaders.Accept.Clear(); 
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

       // Build up the data to POST. 
       List<KeyValuePair<string, string>> postData = new List<KeyValuePair<string, string>>(); 

       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)); 
       postData.Add(new KeyValuePair<string, string>("username",  email)); 
       postData.Add(new KeyValuePair<string, string>("password",  password)); 

       FormUrlEncodedContent content = new FormUrlEncodedContent(postData); 

       // Post to the Server and parse the response. 
       HttpResponseMessage response = await client.PostAsync("Token", content); 
       string jsonString   = await response.Content.ReadAsStringAsync(); 
       object responseData   = JsonConvert.DeserializeObject(jsonString); 

       // return the Access Token. 
       accessToken = ((dynamic)responseData).access_token; 
      } 

      return accessToken; 
     } 

アクセストークンを取得するには、次のコードを使用することができますし、アクセストークンを持っていたら、あなたはトークンAPIへのアクセスを渡すために、次のようなものを使用することができます電話

  using (var client = new HttpClient()) 
      { 
       client.BaseAddress = new Uri(baseUrl); 
       client.DefaultRequestHeaders.Accept.Clear(); 
       client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

       // Add the Authorization header with the AccessToken. 
       client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken); // accessToken is returned from GetAccessToken function 

       // create the URL string. 
       string url = string.Format("API url goes here"); 

       // make the request 
       HttpResponseMessage response = await client.GetAsync(url); 

       // parse the response and return the data. 
       string jsonString = await response.Content.ReadAsStringAsync(); 
       object responseData = JsonConvert.DeserializeObject(jsonString); 
       return (dynamic)responseData; 
      } 
関連する問題