2016-07-27 42 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; 
      } 
相关问题