简体   繁体   English

OAuth 2.0 REST Web API 和 xamarin 表单

[英]OAuth 2.0 REST Web API and xamarin forms

I make webservice api based on this tutorial https://www.c-sharpcorner.com/article/asp-net-mvc-oauth-2-0-rest-web-api-authorization-using-database-first-approach/ and I need to consume the service form xamarin forms.我根据本教程制作了 webservice api https://www.c-sharpcorner.com/article/asp-net-mvc-oauth-2-0-rest-web-api-authorization-using-database-first-approach/我需要使用 xamarin 形式的服务形式。 But I don't know how to authorize client.但我不知道如何授权客户。

Before you try authorizing in code, you should try talking to your API via an api client such as Postman .在您尝试在代码中授权之前,您应该尝试通过 api 客户端(例如Postman )与您的 API 对话。

You can see in step 11 of the article you reference that the writer is infact doing this.您可以在您引用的文章的第 11 步中看到作者实际上正在这样做。

He is performing the following steps:他正在执行以下步骤:

  • Calling the token endpoint (no auth)调用令牌端点(无身份验证)
  • Adding the token to his subsequent requests将令牌添加到他的后续请求中

In order to call an API with authorization, you must first know the auth method (basic, OAuth etc).为了通过授权调用 API,您必须首先了解 auth 方法(基本、OAuth 等)。 In this case you're saying it's OAuth:在这种情况下,您说的是 OAuth:

Take a look at the guide, it shares this picture:看看指南,它分享了这张照片: 图片来自 OP 指南

To do this in code you will need to add the following header to your http client.要在代码中执行此操作,您需要将以下标头添加到 http 客户端。 Lets assume you're using vanilla System.Net.Http.HttpClient you would need to implement a class that looks something like this:假设您使用的是 vanilla System.Net.Http.HttpClient您需要实现一个如下所示的类:

public class APIClient
{
    private HttpClient _client;

    public APIClient()
    {
        _client = SetupClient();
    }

    private HttpClient SetupClient()
    {
        //setup your client here
        var client = new HttpClient();

        //string oauthToken = TokenService.GetUserToken();
        string oauthToken = "eyJhbGciO......."; //Example token
        client.DefaultRequestHeaders.Add("Authorization", $"Bearer {oauthToken}");

        //more setup here

        return client;
    }

    public async Task<HttpResponseMessage> Get(string endpoint)
    {
        var request = new HttpRequestMessage(HttpMethod.Get, endpoint);

        return await CallAsync(request);
    }

    private async Task<HttpResponseMessage> CallAsync(HttpRequestMessage request)
    {
        //do things before?

        var result = await _client.SendAsync(request);

        //handle result? null? not success code?

        return result;
    }
}

When you initialise your HttpClient you should add the following header:初始化HttpClient ,应添加以下标头:

  • Authorization : Bearer {yourtoken} Authorization : Bearer {yourtoken}

Now subsequent api requests will have authorization from your api client.现在后续的 api 请求将获得您的 api 客户端的授权。 How you set this bearer value is up to you.您如何设置此承载值取决于您。 Some people store credentials in the xamarin main App class, and then retrieve the property.有些人将凭据存储在 xamarin 主App类中,然后检索该属性。 Other will persist the data into a plist and have the apiclient read this value (maybe credentials expire every 30 days).其他人会将数据保存到 plist 中,并让 apiclient 读取此值(可能凭据每 30 天过期一次)。

Regardless there are a number of pitfalls that come with talking to api's from a xamarin app.不管怎样,从 xamarin 应用程序中与 api 交谈会带来许多陷阱。 You should always start by calling your api from outside of your app, from within an api client.您应该始终从应用程序外部调用 api 开始,从 api 客户端内部调用。 This will teach you how to configure the requests correctly, without the overhead of worrying if your code/configuration is correct.这将教您如何正确配置请求,而无需担心您的代码/配置是否正确。

Please check my class if help you如果对您有帮助,请查看我的课程

   `public class ServicesClient
    {

        private HttpClient httpClient;
        private bool _IsConnection { get { return CheckInternet(); } }
        public bool IsConnection { get { return _IsConnection; } }


        public ServicesClient()
        {
            httpClient = new HttpClient(new HttpClientHandler());
            //You can change the key as you need and add value 
            httpClient.DefaultRequestHeaders.Add("key", "000000");
        }

        //Get Method
        public async Task<T> GetAsync<T>(string URL) where T : class
        {
            if (IsConnection)
            {
                    var result = await httpClient.GetStringAsync(URL);
                    if (!string.IsNullOrEmpty(result))
                        return JsonConvert.DeserializeObject<T>(result);
                    else
                        return null;
            }
            return null;
        }

        //Post Method
        public async Task<T> PostAsync<T>(string URL, object param) where T : class
        {
            if (IsConnection)
            {
                var json = JsonConvert.SerializeObject(param);
                var httpContent = new StringContent(json, Encoding.UTF8, "application/json");

                    var result = await httpClient.PostAsync(URL, httpContent);
                    if (result.IsSuccessStatusCode)

                            return JsonConvert.DeserializeObject<T>(result.Content.ReadAsStringAsync().Result);
            }
            return null;
        }

        bool CheckInternet()
        {
            return Connectivity.NetworkAccess == NetworkAccess.Internet;
        }
    }
}`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM