0

enter image description here我在ASP.NET中创建了REST API,并使用http://server/token作为URL。如何使客户端对ASP.NET WebAPI进行身份验证?

content-type: application/x-www-form-urlencode 

身体有grant_type作为密码,用户名和密码会得到JSON数据与令牌头。

用于进一步的数据访问令牌可以在上面方法中使用的的工作原理与邮差

我需要实现的Android Studio或Xamarin的客户端。

因为邮递员的网址是“example.com/token”; ,然后在Header Key值pais中为内容类型(“Content-Type:application/x-www-form-urlencoded)并且在body key值对中为(grant_type:password,username:email,password:pass)响应采用json格式,如下所示{“access_token”:“token”,“token_type”:“bearer”,“expires_in”:1209599,“userName”:“[email protected]”,“.issued”:“Fri ,2016年12月9日19时19分18秒“,”.expires“:”2016年12月23日星期五19:19:18 GMT“} 同样需要在android中完成

+0

你能更清楚地解释你的请求是如何做出来的吗?标记是否设置了标题或参数,或者可能是请求的主体?邮差的例子可以帮助你理解你的问题。 – Cheesebaron

+0

作为邮递员的URL是“http://example.com/token”,然后在内容类型的标题密钥值pais中(“Content-Type:application/x-www-form-urlencoded)”和主体键值对作为(grant_type:密码,用户名:email,密码:pass)并且在发送响应之后以json格式如下{ “access_token”:“token”, “token_type”:“bearer”, “expires_in”:1209599 , “userName”:“[email protected]”, “。“2016年12月9日星期五19:19:18 GMT”, “.expires”:“2016年12月23日星期五19:19:18 GMT” } – dharav

+0

我需要在android – dharav

回答

0

这个工作,看起来很丑但你可以改变它

var authCredentials = "grant_type=password&username=" + WebUtility.UrlEncode(LoginBindingModel.Email) + "&password=" + LoginBindingModel.Password; 
    string response = await Client.MakePostFormRequest("token", authCredentials); 


public static async Task<string> MakePostFormRequest(string url, string data) 
    { 
     try 
     { 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(BaseUrl + "token"); 
      // Set the Method property of the request to POST. 
      request.Accept = "*/*"; 
      request.Method = "POST"; 

      // Create POST data and convert it to a byte array. 
      byte[] byteArray = Encoding.UTF8.GetBytes(data); 
      // Set the ContentType property of the WebRequest. 
      request.ContentType = "application/x-www-form-urlencoded"; 
      // Set the ContentLength property of the WebRequest. 
      //request.ContentLength = byteArray.Length; 
      // Get the request stream. 
      Stream dataStream = await request.GetRequestStreamAsync().ConfigureAwait(false); 
      // Write the data to the request stream. 
      dataStream.Write(byteArray, 0, byteArray.Length); 
      // Close the Stream object. 
      dataStream.Dispose(); 
      // Get the response. 
      WebResponse response = await request.GetResponseAsync().ConfigureAwait(false); 
      // Display the status. 
      //Console.WriteLine(((HttpWebResponse)response).StatusDescription); 
      // Get the stream containing content returned by the server. 
      dataStream = response.GetResponseStream(); 
      // Open the stream using a StreamReader for easy access. 
      StreamReader reader = new StreamReader(dataStream); 
      // Read the content. 

      string responseFromServer = reader.ReadToEnd(); 
      // Display the content. 
      //Console.WriteLine(responseFromServer); 
      // Clean up the streams. 
      TokenViewModel TokenViewModel = JsonConvert.DeserializeObject<TokenViewModel >(responseFromServer); 
      VariablesGlobales.Token = TokenViewModel.access_token; 
      VariablesGlobales.LoginStamp = TokenViewModel.LoginStamp; 
      reader.Dispose(); 
      dataStream.Dispose(); 
      response.Dispose(); 

      return responseFromServer; 
     } 
     catch (Exception ex) 
     { 
      return ""; 
     } 
    } 

而当你想验证您的请求

public static async Task<string> MakePostRequest(string url, string data) 
    { 
     var result = ""; 
     try 
     { 
      var httpWebRequest = (HttpWebRequest)WebRequest.Create(BaseUrl + url); 
      httpWebRequest.ContentType = "application/json; charset=utf-8"; 
      httpWebRequest.Method = "POST"; 
      if (VariablesGlobales.Token != "") 
      { 
       httpWebRequest.Headers[HttpRequestHeader.Authorization] = "Bearer " + VariablesGlobales.Token; 
      } 

      using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync().ConfigureAwait(false))) 
      { 
       streamWriter.Write(data); 
       streamWriter.Flush(); 
      } 

      var httpResponse = (HttpWebResponse)(await httpWebRequest.GetResponseAsync().ConfigureAwait(false)); 

      if (httpResponse.StatusCode.ToString() == "OK") 
      { 
       result = httpResponse.StatusCode.ToString(); 
      } 
      else 
      { 
       result = ""; 
      } 

     } 

     catch (Exception ex) 
     { 
      result = ""; 
     } 
     return result; 
    } 
} 
+0

在android studio m工作不能解决HttpWebRequest的符号,以及在哪里我需要把这些方法作为它提供的错误很多,如果你不介意帮助更多 – dharav

+0

哦,对不起,这是为Xamarin.Android在C#中,我建议你删除该标签 –

0

包含在你的依赖System.Net.Http(需要Xamarin配置文件111),然后你可以使用它来创建一个HttpClient并通过HTTP POST请求令牌(类似于你在Postman中做的)。

_client = new HttpClient(); 

var uri = new Uri("http://server/token"); 
var content = new FormUrlEncodedContent(
     new List<KeyValuePair<string, string>> { 
      new KeyValuePair<string, string>("username", _username), 
      new KeyValuePair<string, string>("password", _password), 
      new KeyValuePair<string, string>("grant_type", "password") 
     }); 
HttpResponseMessage response = await _client.PostAsync(uri, content); 

其中_username和_password是字符串。

然后通过将响应转换为字典或任何其他解析JSON响应的合理替代方法来读取响应。

if (response.StatusCode == HttpStatusCode.OK) { 
     var jsonContent = await response.Content.ReadAsStringAsync(); 
     var responseDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonContent); 
     if (responseDict.ContainsKey("access_token")) 
      _token = responseDict["access_token"]; 
} 

然后,一旦拥有该令牌,就可以将该令牌包含为来自该HttpClient实例的所有头的默认授权值!

_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token); 

其中_token是其编码字符串的标记,例如, “eyJ0eXAiOiJKV1QiLC ...”

刚刚实现了这一点,并验证它的正确性 - 我将其与我已设置使用JWT进行验证的生产环境进行了对比,它运行得非常神奇。

相关问题