如何使客户端对ASP.NET WebAPI进行身份验证?

时间:2016-12-09 17:27:18

标签: android android-studio asp.net-web-api http-post restful-authentication

enter image description here我在ASP.NET中创建了REST API,其中http://server/token为URL。

标题

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

正文有grant_type作为密码,用户名和密码将获得带有令牌的json数据。

对于进一步的数据访问令牌可以使用上面的方法与postman

一起使用

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

邮递员中的网址是" example.com/token" ;; ,然后在内容类型的标题键值pais中作为(" Content-Type:application / x-www-form-urlencoded)并在正文键值对中作为(grant_type:password,username:email,password:pass)发送后,响应采用json格式,如下所示{" access_token":" token"," token_type":" bearer",&# 34; expires_in":1209599," userName":" mail@gmail.com"," .issued":" Fri,2016年12月9日19:19:18 GMT"," .expires":"星期五,23十二月2016 19:19:18 GMT" } 这同样需要在android

中完成

2 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:0)

包含在您的依赖项System.Net.Http(需要Xamarin配置文件111)中,然后您可以使用它来创建HttpClient并通过HTTP POST请求令牌(类似于您在Postman中所做的事情),就像这样.. < / p>

_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是字符串。

然后通过将响应转换为Dictionary或任何其他合理的替代方法来解析响应,以解析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并且它有一定的魅力。