Azure API Management – How to set basic authentication in SendRequest

Scenario: I have both username and password stored in name value configuration of API management but I need to use it in SendRequest policy.

Source Code:

<set-variable name=“userName” value=“{{username}}” />

<set-variable name=“password” value=“{{password}}” />

<set-variable name=“basicAuthDetails” value=”@{

var username = context.Variables.GetValueOrDefault<string>(“userName”);

var password = context.Variables.GetValueOrDefault<string>(“password”);

return System.Convert.ToBase64String(System.Text.Encoding.GetEncoding(“ISO-8859-1”).GetBytes(username + “:” + password));

}/>

<set-variable name=“jsonPayload” value=”@{

JObject transBody = new JObject();

//Add all json Property

transBody.Add(“test”, JToken.FromObject(new[]

{

 “test data”

}));

}/>

<send-request mode=“new” response-variable-name=“var” ignore-error=“false”>

<set-url>@{

        var url = context.Api.ServiceUrl+ “/{someURL}”;

       return url;

}</set-url>

<set-method>POST</set-method>

<set-header name=“Authorization” exists-action=“override”>

<value>@(context.Variables.GetValueOrDefault<string>(“basicAuthDetails”))</value>

</set-header>

<set-header name=“Content-Type” exists-action=“override”>

<value>application/json</value>

</set-header>

<set-body template=“none”>@(context.Variables.GetValueOrDefault<string>(“jsonPayload”))</set-body>

</send-request>

 

That is how you can set basic authentication in SendRequest in Azure API Management.

Advertisements