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

Android 如何使客户端根据ASP.NET WebAPI进行身份验证?,android,android-studio,asp.net-web-api,http-post,restful-authentication,Android,Android Studio,Asp.net Web Api,Http Post,Restful Authentication,我已经在ASP.NET中使用http://server/token作为URL 头具有 content-type: application/x-www-form-urlencode 主体具有grant_type作为密码,用户名和密码将获得带有令牌的json数据 对于进一步的数据访问令牌,可以使用上面的方法与邮递员一起工作 我需要在Android Studio或Xamarin中实现一个客户端 因为postman中的URL是“example.com/token”,然后在内容类型为(“内容类型:app

我已经在ASP.NET中使用
http://server/token
作为URL

头具有

content-type: application/x-www-form-urlencode
主体具有
grant_type
作为密码,用户名和密码将获得带有令牌的json数据

对于进一步的数据访问令牌,可以使用上面的方法与邮递员一起工作

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

因为postman中的URL是“example.com/token”,然后在内容类型为(“内容类型:application/x-www-form-urlencoded”)的报头键值pai和正文键值对为(grant_type:password,username:email,password:pass),发送后,响应以json格式,如下{“access_token”:“token”,“token_type”:“bearer”,“expires_in”:1209599,“username”:mail@gmail.com", ".发布“:”2016年12月9日星期五19:19:18 GMT“,”到期“:”2016年12月23日星期五19:19:18 GMT”}
这同样需要在android中完成这项工作,它看起来很难看,但你可以改变它

    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 "";
        }
    }
var authCredentials=“grant_type=password&username=“+WebUtility.UrlEncode(LoginBindingModel.Email)+”和password=“+LoginBindingModel.password;
字符串响应=等待客户端.MakePostFormRequest(“令牌”,authCredentials);
公共静态异步任务MakePostFormRequest(字符串url、字符串数据)
{
尝试
{
HttpWebRequest请求=(HttpWebRequest)WebRequest.Create(BaseUrl+“令牌”);
//将请求的Method属性设置为POST。
request.Accept=“*/*”;
request.Method=“POST”;
//创建POST数据并将其转换为字节数组。
byte[]byteArray=Encoding.UTF8.GetBytes(数据);
//设置WebRequest的ContentType属性。
request.ContentType=“application/x-www-form-urlencoded”;
//设置WebRequest的ContentLength属性。
//request.ContentLength=byteArray.Length;
//获取请求流。
Stream dataStream=await request.GetRequestStreamAsync().ConfigureAwait(false);
//将数据写入请求流。
写入(byteArray,0,byteArray.Length);
//关闭流对象。
Dispose();
//得到回应。
WebResponse-response=await request.GetResponseAsync().ConfigureAwait(false);
//显示状态。
//Console.WriteLine(((HttpWebResponse)response.StatusDescription);
//获取包含服务器返回的内容的流。
dataStream=response.GetResponseStream();
//使用StreamReader打开流以便于访问。
StreamReader=新的StreamReader(数据流);
//阅读内容。
字符串responseFromServer=reader.ReadToEnd();
//显示内容。
//Console.WriteLine(responseFromServer);
//清理溪流。
TokenViewModel TokenViewModel=JsonConvert.DeserializeObject(responseFromServer);
VariablesGlobales.Token=TokenViewModel.access\u Token;
VariablesGlobales.LoginStamp=TokenViewModel.LoginStamp;
reader.Dispose();
Dispose();
response.Dispose();
返回responseFromServer;
}
捕获(例外情况除外)
{
返回“”;
}
}
当您想要验证您的请求时

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;
    }
}
公共静态异步任务MakePostRequest(字符串url、字符串数据)
{
var结果=”;
尝试
{
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;
}
使用(var streamWriter=newstreamwriter(wait httpWebRequest.GetRequestStreamAsync().configurewait(false)))
{
streamWriter.Write(数据);
streamWriter.Flush();
}
var httpResponse=(HttpWebResponse)(等待httpWebRequest.GetResponseAsync().ConfigureAwait(false));
如果(httpResponse.StatusCode.ToString()=“确定”)
{
结果=httpResponse.StatusCode.ToString();
}
其他的
{
结果=”;
}
}
捕获(例外情况除外)
{
结果=”;
}
返回结果;
}
}

包含在依赖项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);
其中_token是编码字符串形式的令牌,例如“EYJ0EXAIIOIJKV1QILC…”


刚刚实现了这个并验证了它的正确性-我在一个生产环境中运行了它,我已经设置了使用JWTs进行验证,它非常有效。

您能更清楚地解释一下您的请求是如何产生的吗?令牌集是否带有头或参数,或者请求的主体?postman提供的一个示例将有助于理解g您的问题。由于邮递员中的URL为“”,那么在标题中,内容类型为(“内容类型:application/x-www-form-urlencoded”)的键值对为(“内容类型:application/x-www-form-urlencoded”),在正文中,键值对为(“grant_type:password,username:email,password:pass”),发送后,响应为json格式,如下{“access_token”:“token”,“token_type”:“Bear”,在:1209599,“用户名”中过期mail@gmail.com“,”.issued:“Fri,2016年12月9日19:19:18 GMT”,“.expires:“Fri,2016年12月23日19:19:18 GMT”}我需要在Android中做同样的事情。请用您在评论中写的内容更新问题正文,这将使ot更容易
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"];
}
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token);