Getting Ansible Tower API authentication token from C# - ansible

I tried using this C# code below, but getting status code 401 (reason:unautherized):
var baseUri = "https://ansibletower1.test1.com";
var data = #"{'username':'test123', 'password':'a1b2c3Z0!-99', 'description':'Ansible Api token', 'scope':'write'}";
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(baseUri);
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = httpClient.PostAsync("api/v2/tokens", content).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var result = response.Content.ReadAsStringAsync().Result;
if (result != null)
{
return result;
}
}
}
Try-2: Using Basic Authorization header.. getting same error (401- unautherized).
I tried from python script, it works. Used Basic Authorization header in it.
var baseUri = "https://ansibletower1.test1.com";
var jsonObject = new {description = "Tower API token", scope = "write" };
var username="test123";
var password="a1b2c3Z0!-99";
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(baseUri);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes($"{username}:{password}")));
var content = new StringContent(JsonConvert.SerializeObject(jsonObject), Encoding.UTF8, "application/json");
var response = httpClient.PostAsync("api/v2/tokens", content).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
var result = response.Content.ReadAsStringAsync().Result;
if (result != null)
{
return result;
}
}
}

I figured out. The url "api/v2/tokens" is missing "/" at the end.
It should be:
var response = httpClient.PostAsync("api/v2/tokens/", content).Result;

Related

although i have a token, xamarin gives 401 error, wher is problem

although, i have a token xamarin gives 401 error when i post to rest api, or get..have you any solution ?
public async Task<List<Gorev>> GetGorevlerAsync(Gorev Gorev, string accessToken)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var json = JsonConvert.SerializeObject(Gorev);
HttpContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
string uri = Constants.BaseApiAddress + "http/GorevTeamLstStored";
var ReturnJson = await client.PostAsync(uri, content);
var ls = ReturnJson.Content.ReadAsStringAsync().Result;
var Gorevler = JsonConvert.DeserializeObject<List<Gorev>>(ls);
return Gorevler;
.
}

Null response Xamarin android application using web api

Hi I am just learning Xamarin android development and I just want to CRUD operation but I am stuck that I am unable to get any response from webapi. I have tested my api using SOAPUI and response is ok from that.
[HttpPost]
public HttpResponseMessage CreateEmpAttandance(string value)
{
if (value != "1234")
{
string json = #"{ data: 'Emp Code is not valid.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
else
{
string json = #"{ data: 'data save sucessfully.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
}
this is api code and below is my android application code but I am getting null response exception.
public async Task SaveTodoItemAsync(string EmpCode)
{
try
{
string url = "http://192.168.1.9/attandanceapi/api/attandance?value=12132";
var uri = new Uri(string.Format(url));
var json = JsonConvert.SerializeObject(EmpCode);
var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PostAsync(url, content);
var responses = response;
}
catch (Exception ex)
{
var w = ex.ToString();
}
}
I think we have problem here. You are trying to create content from string not from Json.
var content = new StringContent(EmpCode, Encoding.UTF8, "application/json");
try this:
var content = new StringContent(json, Encoding.UTF8, "application/json");
Edit:
I cannot see your default headers so if you don't have them - just add.
client.DefaultRequestHeaders.Add("Accept", "application/json");

PayPal Rest API webhook signature verification always return verification_status as FAILURE

I have paypal integration application which receives webhook notification from paypal and I want to verify the signature as per docs:
Verify signature rest api link
Here is code which I have written:
public async Task<ActionResult> Index()
{
var stream = this.Request.InputStream;
var requestheaders = HttpContext.Request.Headers;
var reader = new StreamReader(stream);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
var webhook = serializer.Deserialize<Models.Event>(jsonReader);
var webhookSignature = new WebhookSignature();
webhookSignature.TransmissionId = requestheaders["PAYPAL-TRANSMISSION-ID"];
webhookSignature.TransmissionTime = requestheaders["PAYPAL-TRANSMISSION-TIME"];
webhookSignature.TransmissionSig = requestheaders["PAYPAL-TRANSMISSION-SIG"];
webhookSignature.WebhookId = "My actual webhookid from paypal account";
webhookSignature.CertUrl = requestheaders["PAYPAL-CERT-URL"];
webhookSignature.AuthAlgo = requestheaders["PAYPAL-AUTH-ALGO"];
webhookSignature.WebhookEvent = webhook;
var jsonStr2 = JsonConvert.SerializeObject(webhookSignature);
var result = await _webhookService.VerifyWebhookSignatureAsync(webhookSignature);
var jsonStr3 = JsonConvert.SerializeObject(result);
return Content(jsonStr3, "application/json");
}
public async Task<Models.SignatureResponse> VerifyWebhookSignatureAsync(Models.WebhookSignature webhook, CancellationToken cancellationToken = default(CancellationToken))
{
var accessTokenDetails = await this.CreateAccessTokenAsync();
_httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessTokenDetails.AccessToken);
try
{
string jsonStr = JsonConvert.SerializeObject(webhook);
var content = new StringContent(jsonStr, Encoding.UTF8, "application/json");
string url = $"{_baseUrl}notifications/verify-webhook-signature";
var response = await _httpClient.PostAsync(url, content);
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
throw new Exception(error);
}
string jsonContent = response.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<Models.SignatureResponse>(jsonContent);
}
catch (Exception ex)
{
throw new InvalidOperationException("Request to Create payment Service failed.", ex);
}
}
Webhook signature verification response :
{"verification_status":"FAILURE"}
I am getting 200K ok response from api but verification status in response is always FAILURE.I tried many different request.
I am not sure if something is wrong from my request. Looking for help.

Requesting token from ADFS by using usernamemixed

i am trying obtain a token from ADFS server from .net web api an on-premise Windows authentication while requesting i am getting below exception .
An exception of type 'System.ServiceModel.Security.MessageSecurityException' occurred in
mscorlib.dll but was not handled in user code Additional information:
The HTTP request was forbidden with client authentication scheme
'Anonymous'.
The code to obtain token is as follows
var trustChannelFactory = new WSTrustChannelFactory(new UserNameWSTrustBinding(
System.ServiceModel.SecurityMode.TransportWithMessageCredential),
new System.ServiceModel.EndpointAddress(new Uri("https://ADFSSERVER/adfs/services/trust/13/usernamemixed")))
{
TrustVersion = TrustVersion.WSTrust13,
Credentials = { UserName = { UserName = "DCK", Password = "gfgfg" } },
};
var requestSecurityToken = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
KeyType = KeyTypes.Bearer,
AppliesTo = new EndpointReference("urn:feedbackapp")
};
RequestSecurityTokenResponse response;
var securityToken = trustChannelFactory.CreateChannel().Issue(requestSecurityToken, out response);
return securityToken;
could you someone help me to proceed to get the token
var binding = WSTrust13Bindings.UsernameMixed;
var serviceUri = new Uri(_config.StsUri, "/adfs/services/trust/13/usernamemixed");
using (var factory = new WSTrustChannelFactory(binding, serviceUri.AbsoluteUri))
{
factory.TrustVersion = TrustVersion.WSTrust13;
factory.Credentials.UserName.UserName = userName;
factory.Credentials.UserName.Password = password;
RequestSecurityTokenResponse response;
var channel = factory.CreateChannel();
channel.Issue(new RequestSecurityToken()
{
RequestType = RequestTypes.Issue,
AppliesTo = new EndpointReference(_config.ResourceUri.ToString()),
KeyType = KeyTypes.Bearer
}, out response);
var sb = new StringBuilder();
var ser = new WSTrust13ResponseSerializer();
using (var sw = new StringWriter(sb, CultureInfo.InvariantCulture))
{
var xw = XmlTextWriter.Create(sw, new XmlWriterSettings() { OmitXmlDeclaration = true });
ser.WriteXml(response, xw, new WSTrustSerializationContext(factory.SecurityTokenHandlerCollectionManager));
xw.Flush();
}
return sb.ToString();
}

win8 HttpClient auto redirect

When I use HttpClient.GetAsync(url),but the url is not a reachable address,but it always redirect to another address,and it return a statuecode with ok.
var httpClient = new HttpClient(handler);
httpClient.DefaultRequestHeaders.ExpectContinue = false;
//using ()
{
HttpResponseMessage response = new HttpResponseMessage();
response = await httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync();
Debug.WriteLine(response.StatusCode.ToString());
}
else
{
// problems handling here
Debug.WriteLine(
"Error occurred, the status code is: {0}",
response.StatusCode
);
}
}

Resources