如何验证Prestashop API REST客户端

问题描述 投票:0回答:2

我为正在开发的Bot应用创建了一个界面,用于使用Refit调用Prestashop API。为了调用该API,您需要使用我拥有的Prestashop API密钥进行身份验证。要使用浏览器查询,我只需要使用以下格式调用网址:

$"https://{ApiKey}@{mypage}.com/api"

并且它使用@符号前面指定的Api密钥进行身份验证。要定义改装HttpClient,请在Startup.cs中使用以下代码:

// This is the ApiUrl from the appsettings.json file
var apiUrl = Configuration.GetSection("PrestashopSettings").GetSection("ApiUrl").Value;

// We add the Api and specify the de/serialization will be XML
services.AddRefitClient<IPrestashopApi>(
    new RefitSettings
    {
        ContentSerializer = new XmlContentSerializer()
    })
    .ConfigureHttpClient(c => c.BaseAddress = new System.Uri(apiUrl));

然后,将API注入我的一个类,并调用其功能之一。该URL似乎正确,如果我将完整的URL(基本+ [Get] URL)粘贴到浏览器中,它将正确返回XML。但是,当我从应用程序执行此操作时,它将返回异常:

Microsoft.Bot.Builder.Integration.AspNet.Core.BotFrameworkHttpAdapter:Error: Exception caught : Refit.ApiException: Response status code does not indicate success: 401 (Unauthorized).
   at Refit.RequestBuilderImplementation.<>c__DisplayClass14_0`2.<<BuildCancellableTaskFuncForMethod>b__0>d.MoveNext() in D:\a\1\s\Refit\RequestBuilderImplementation.cs:line 274
--- End of stack trace from previous location where exception was thrown ---

使用Refit的HttpClient进行身份验证的正确方法是什么?我做错了吗?

UPDATE:

所以我尝试了这个:

public class HttpAuthentication : HttpClientHandler
{
    private readonly string Token;
    public HttpAuthentication(string token)
    {
        Token = token ?? throw new ArgumentException(nameof(token));
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var token = Token;
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
        return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
    }
}

此代码在我的Startup.cs中:

var apiKey = Configuration.GetSection("PrestashopSettings").GetSection("ApiKey").Value;
var storeUrl = Configuration.GetSection("PrestashopSettings").GetSection("StoreUrl").Value;

// We add the Api and specify the de/serialization will be XML, and we specify the Authentication Client.
services.AddRefitClient<IPrestashopApi>(
    new RefitSettings
    {
        ContentSerializer = new XmlContentSerializer()
    })
    .ConfigureHttpClient((c) => c.BaseAddress = new System.Uri(storeUrl))
    .ConfigureHttpMessageHandlerBuilder((c) => new HttpAuthentication(apiKey));

而且我仍然收到相同的错误消息。

c# authentication asp.net-core prestashop refit
2个回答
0
投票
public class AuthenticatedHttp : HttpClientHandler { private readonly string Token; public AuthenticatedHttp(string token) { if (token == null) { throw new ArgumentNullException(nameof(token)); } this.Token = token; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // See if the request has an authorize header var token = this.Token; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } }

并将令牌发送给此类:

var token = await GetAccessToken();
            var RestReq = RestService.For<IPerson>(new HttpClient(new AuthenticatedHttp(token)) { BaseAddress = new Uri(Url) });

0
投票

第一个解决方案

您实际上可以使用API​​密钥作为Request参数进行身份验证,其密钥为ws_key,因此您可以像这样发送呼叫:

"https://api.yourapiaddress.com/yourentity?ws_key={API KEY HERE}"

第二解决方案>>

这是我选择的,只添加一个Header参数。发现Prestashop API 1.7使用了具有API密钥作为用户名和空密码的基本授权,因此我在Startup.cs中建立了这样的标题:

// Encode your Api Key String encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(apiKey)); // Add the API to DI in Dialog classes services.AddRefitClient<IPrestashopApi>( new RefitSettings { ContentSerializer = new XmlContentSerializer() }) .ConfigureHttpClient((c) => c.BaseAddress = new Uri(storeUrl)) .ConfigureHttpClient((c) => c.DefaultRequestHeaders.Add("Authorization", "Basic " + encoded));

我使用了Retrofit的ConfigureHttpClient函数,但实际上可以通过创建自己的HttpClient对象并像这样配置DefaultRequestHeaders来实现相同的目的。

© www.soinside.com 2019 - 2024. All rights reserved.