2016-07-27 67 views
1

我將WebApi2添加到我的MVC應用程序中,並且可以通過瀏覽器成功調用我的API。如果用戶未通過身份驗證,則會顯示我的標準登錄屏幕,然後運行。如何登錄並將令牌傳遞給WebAPI2

但我真的很想把api稱爲一個來自移動應用的REST 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; 
      } 
相關問題