Dynamics WEB API returns on post -StatusCode: 401, ReasonPhrase: 'Unauthorized' - asp.net-web-api

I am trying to create a lead in CRM from via web api , but its throwing unauthorized access error. I am able to login to CRM but from Web Api , It's throwing error
Below is my code
var credentials = new NetworkCredential("username", "password");
var client = new HttpClient(new HttpClientHandler() { Credentials = credentials })
{
BaseAddress = new Uri("https://*******.dynamics.com/XRMServices/2011/Organization.svc/api/data/v8.2/")
};
Entity lead1 = new Entity();
lead1["firstname"] = "TestFirstName";
lead1["lastname"] = "TestLastName";
lead1["emailaddress1"] = "%%%%%%%%%";
lead1["companyname"] = "&&&&&&";
string output = new JavaScriptSerializer().Serialize(lead1).ToString();
HttpRequestMessage request = null;
try
{
request = new HttpRequestMessage(HttpMethod.Post, "leads");
request.Content = new StringContent(output);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
Task<HttpResponseMessage> response = client.SendAsync(request);
response.Wait();
if (response.Result.IsSuccessStatusCode)
{
//retrievedContact1 = JsonConvert.DeserializeObject<JObject>(rep .Content.ReadAsStringAsync());
}

Related

How to Fetch Access token from my custom controller in asp.net web api 2

I have implemented the code for generating access token.I am able to get the token from default Token End Point Path(https://localhost:44312/token) when trying to get it from Postman.
However I want to implement Login Controller which internally should call the default token end point and send the response.
public async Task<IHttpActionResult> Login(UserModel userModel)
{
HttpResponseMessage response;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:44312/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("cache-control", "no-cache");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
userModel.grant_type = "password";
var parameters = new Dictionary<string, string> { { "username", userModel.UserName }, { "password", userModel.Password }, { "grant_type", "password" } };
var encodedContent = new FormUrlEncodedContent(parameters);
response = client.PostAsync("/token", encodedContent).Result;
}
return Ok(response);
}
I get an httpstatus OK response but not the access token. Any guidance in solving the issue would be helpful.

xamarin android webservice get error

I am using the below code to create php mys1l webservice, when run app I get exception error, the server returns error 404 and the debugger points to this line:
var response = client.UploadValues(uri, parameters);
My complete code
WebClient client = new WebClient();
Uri uri = new Uri("http://149.255.62.48/Login/xamarinsignIn.php");
NameValueCollection parameters = new NameValueCollection();
parameters.Add("uemail", userEmail);
parameters.Add("pass", userPassword);
var response = client.UploadValues(uri, parameters);
var responseString = Encoding.Default.GetString(response);
JSONObject ob = new JSONObject(responseString);
if (ob.OptString("success").Equals("1"))
{
mainActivity.RunOnUiThread(() =>
Toast.MakeText(mainActivity, "You Successfully LogIn", ToastLength.Short).Show());
}
else {
mainActivity.RunOnUiThread(() =>
Toast.MakeText(mainActivity, "InValid Email or Password", ToastLength.Short).Show());
}

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.

Resharpe.portable get Twitter request token

Hello i'm doing an xamarin.form application and i'm implementing the twitter login using oauth.
I have problem to get the request_token folowing the link:
https://dev.twitter.com/oauth/reference/post/oauth/request_token
using restsharp.portable for the request POST i arrive at this point:
public async void GetTwitterToken()
{
try
{
TwitterLogin tw = new TwitterLogin();
RestClient client = new RestClient("https://api.twitter.com");
RestRequest request = new RestRequest("/oauth/request_token", Method.POST);
client.Authenticator = OAuth1Authenticator.ForRequestToken(tw.oauth_consumer_key, tw.oauth_consumer_secret);
IRestResponse response = await client.Execute(request);
}
catch (Exception e)
{
}
}
Parameter "response" it's ok but i'don't know how to parse to get token (it's not json).
i have seen this example:
public void GetRequestToken()
{
var client = new RestClient("https://api.twitter.com"); // Note NO /1
client.Authenticator = OAuth1Authenticator.ForRequestToken(
_consumerKey,
_consumerSecret,
"http://markashleybell.com" // Value for the oauth_callback parameter
);
var request = new RestRequest("/oauth/request_token", Method.POST);
var response = client.Execute(request);
var qs = HttpUtility.ParseQueryString(response.Content);
_token = qs["oauth_token"];
_tokenSecret = qs["oauth_token_secret"];
}
But i don't have HttpUtility.ParseQueryString(response.Content) whith xamarin.form framework

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();
}

Resources