Identitty4 Access Token from Android and token lenght - xamarin

I have a console application where I use to test some code. In my console app everything works as expected. Same code implemented in the xamarin forms and I get an un tI sent a request to identity4 to get a token and it works receiving a token 685 characters of length. The same code that I use in the console is implemented in android on a button click action and I receive the token as well. I try to use the access token to my protected api and I get Unauthorized. I try to use the token in postman and I get Unauthorized. If I use the token received in my console in the postman it works! What I realize is that in the console app the access token have a length of 865 characters and in android the access token have a length of 864. I checked the length from the content which I receive before apply NewtonSoft Json converter
My console code:
private static async Task Main()
{
Console.WriteLine("Request For a token");
//var handler = new HttpClientHandler();
//handler.ClientCertificateOptions = ClientCertificateOption.Manual;
//handler.SslProtocols = SslProtocols.Tls12;
//handler.ClientCertificates.Add(new X509Certificate2("rsaCert.pfx","1234"));
//var client = new HttpClient(handler);
// discover endpoints from metadata
var client = new HttpClient();
//client.BaseAddress = new Uri("http://localhost:5000");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", "test"),
new KeyValuePair<string, string>("password", "test"),
new KeyValuePair<string, string>("scope", "catalogapi1"),
new KeyValuePair<string, string>("client_id", "ro.client"),
new KeyValuePair<string, string>("client_secret", "secret")
});
var result = await client.PostAsync("http://localhost:5000/connect/token", content);
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
ServerReponse responseToken = JsonConvert.DeserializeObject<ServerReponse>(resultContent);
Console.WriteLine("Token Lenght: "+ responseToken.access_token.Length);
Console.WriteLine("\n\n");
// call api
var apiClient = new HttpClient();
apiClient.SetBearerToken(responseToken.access_token);
var response = await apiClient.GetAsync("http://localhost:5100/api/v1/products");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content2 = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content2));
}
Console.WriteLine("Press a key to close the application");
Console.ReadLine();
}
And in my Android event click action:
async void OnButtonClicked(object sender, EventArgs args)
{
var client = new HttpClient();
//client.BaseAddress = new Uri("http://localhost:5000");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", "test"),
new KeyValuePair<string, string>("password", "test"),
new KeyValuePair<string, string>("scope", "test"),
new KeyValuePair<string, string>("client_id", "ro.client"),
new KeyValuePair<string, string>("client_secret", "secret")
});
var result = await client.PostAsync("http://10.0.2.2:5000/connect/token", content);
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
ServerReponse responseToken = JsonConvert.DeserializeObject<ServerReponse>(resultContent);
// call api
var apiClient = new HttpClient();
apiClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", responseToken.access_token.Trim());
// apiClient.SetBearerToken(responseToken.access_token);
var response = await apiClient.GetAsync("http://10.0.2.2:5100/api/v1/products");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content2 = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content2));
}
Console.WriteLine("Press a key to close the application");
Console.ReadLine();
}
public class ServerReponse
{
public string access_token { get; set; }
public string expires_in { get; set; }
public string token_type { get; set; }
public string scope { get; set; }
}

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;
.
}

OwinOAuthProviders RefreshToken flow

I'm building a OwinOAuth (Oauth2) provider for my company to contribute here-https://github.com/TerribleDev/OwinOAuthProviders
The challenge I'm facing is that my company generates the refresh token too along with access token and provides the expiry time for both access token and refresh token. Access token expiry is set to 1hr and using Refresh token I can refresh access tokens again and again for 100 days.
Any implementations that I have seen create a RefreshTokenProvider which I don't need as my company already sends me that. The question I have here is this-
In the AuthenticationHandler class, since tokens are in memory and not saved anywhere and Oauth tokens are always generated by default, I'm not sure where the call/logic to get access tokens based on Refresh Tokens should be done.
Do I need to create a persistent store for all returned tokens and expiry and then match expiry to make a call to RefreshTokenHandler(grant_type=refresh_token) instead of AuthenticationHandler(grant_type=authorization_code) based on that?
I'm really confused here and any help with the implementation is appreciated.
EDIT-1
I have replaced my provider's name with Hidden everywhere.
Adding code for the HiddenAuthenticationHandler.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Owin.Security.Providers.Hidden.Provider;
using System.Net.Http.Headers;
using System.Net;
using System.Linq;
using Microsoft.Owin.Security.OAuth;
namespace Owin.Security.Providers.Hidden
{
public class HiddenAuthenticationHandler : AuthenticationHandler<HiddenAuthenticationOptions>
{
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
private const string AuthorizationEndPoint = "https://appcenter.Hidden.com/connect/oauth2";
private const string TokenEndpoint = "https://oauth.platform.Hidden.com/oauth2/v1/tokens/bearer";
private const string UserInfoEndpoint = "https://sandbox-accounts.platform.Hidden.com/v1/openid_connect/userinfo";//"https://accounts.Hidden.com/v1/openid_connect/userinfo";//Nimisha
private const string RevokeEndpoint = "https://developer.api.Hidden.com/v2/oauth2/tokens/revoke";//Nimisha
private const string JWKSEndpoint = "https://oauth.platform.Hidden.com/op/v1/jwks";//Nimisha
private const string IssuerEndpoint = "https://oauth.platform.Hidden.com/op/v1";//Nimisha
private const string DiscoveryEndpoint = "https://developer.Hidden.com/.well-known/openid_configuration";//Nimisha
private static string refreshToken;
private static string refreshTokenExpiresIn;
private static string tokenType;
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
public HiddenAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
_httpClient = httpClient;
_logger = logger;
}
//public async Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
//{
// var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
// var currentClient = context.ClientId;
// if (originalClient != currentClient)
// {
// context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
// return Task.FromResult<object>(null);
// }
// // Change auth ticket for refresh token requests
// var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
// newIdentity.AddClaim(new Claim("newClaim", "newValue"));
// var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
// context.Validated(newTicket);
// return Task.FromResult<object>(null);
//}
public async Task<AuthenticationTicket> RefreshTokenAsync()
{
AuthenticationProperties properties = null;
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(properties, _logger))
{
return new AuthenticationTicket(null, properties);
}
//var requestPrefix = Request.Scheme + "://" + Request.Host;
////var redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;
//var redirectUri = "https://be97d742.ngrok.io/signin-Hidden";
// Build up the body for the token request
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "refresh_token"),
new KeyValuePair<string, string>("refresh_token", refreshToken)
};
// Request the token
var refreshTokenResponse =
await _httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));
refreshTokenResponse.EnsureSuccessStatusCode();
var text = await refreshTokenResponse.Content.ReadAsStringAsync();
// Deserializes the token response
dynamic response = JsonConvert.DeserializeObject<dynamic>(text);
var accessToken = (string)response.access_token;
var expires = (string)response.expires_in;
//string refreshToken = null;
refreshToken = (string)response.refresh_token;
refreshTokenExpiresIn = (string)response.x_refresh_token_expires_in;
tokenType = (string)response.token_type;
return new AuthenticationTicket(null, properties);
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
AuthenticationProperties properties = null;
try
{
string code = null;
string state = null;
var query = Request.Query;
var values = query.GetValues("code");
if (values != null && values.Count == 1)
{
code = values[0];
}
values = query.GetValues("state");
if (values != null && values.Count == 1)
{
state = values[0];
}
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
return null;
}
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(properties, _logger))
{
return new AuthenticationTicket(null, properties);
}
var requestPrefix = Request.Scheme + "://" + Request.Host;
//var redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;
var redirectUri = "https://be97d742.ngrok.io/signin-Hidden";
// Build up the body for the token request
var body = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("redirect_uri", redirectUri),
new KeyValuePair<string, string>("client_id", Options.ClientId),
new KeyValuePair<string, string>("client_secret", Options.ClientSecret)
};
// Request the token
var tokenResponse =
await _httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));
tokenResponse.EnsureSuccessStatusCode();
var text = await tokenResponse.Content.ReadAsStringAsync();
// Deserializes the token response
dynamic response = JsonConvert.DeserializeObject<dynamic>(text);
var accessToken = (string)response.access_token;
var expires = (string)response.expires_in;
//string refreshToken = null; //Nimisha
refreshToken = (string)response.refresh_token;
refreshTokenExpiresIn = (string)response.x_refresh_token_expires_in;
tokenType = (string)response.token_type;
// Get the Hidden user
var userRequest = new HttpRequestMessage(HttpMethod.Get, Options.Endpoints.UserInfoEndpoint );
userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
userRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var userResponse = await _httpClient.SendAsync(userRequest, Request.CallCancelled);
userResponse.EnsureSuccessStatusCode();
text = await userResponse.Content.ReadAsStringAsync();
var user = JObject.Parse(text);
var context = new HiddenAuthenticatedContext(Context, user, accessToken, expires, refreshToken, refreshTokenExpiresIn, tokenType)
{
Identity = new ClaimsIdentity(
Options.AuthenticationType,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType)
};
if (!string.IsNullOrEmpty(context.Sub))
{
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Sub, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.GivenName))
{
string Name = "";
Name = context.GivenName;
if (!string.IsNullOrEmpty(context.FamilyName))
{
Name = Name +" " + context.FamilyName;
}
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, Name, XmlSchemaString, Options.AuthenticationType));
context.Identity.AddClaim(new Claim("urn:Hidden:name", Name, XmlSchemaString, Options.AuthenticationType));
}
if ((!string.IsNullOrEmpty(context.Email)) && (!string.IsNullOrEmpty(context.EmailVerified)))
{
if (String.Equals(context.EmailVerified, "true"))
{
context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
}
}
if ((!string.IsNullOrEmpty(context.PhoneNumber)) && (!string.IsNullOrEmpty(context.PhoneNumberVerified)))
{
if (String.Equals(context.PhoneNumberVerified, "true"))
{
context.Identity.AddClaim(new Claim(ClaimTypes.MobilePhone, context.Email, XmlSchemaString, Options.AuthenticationType));
}
}
if (!string.IsNullOrEmpty(context.StreetAddress))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.StreetAddress, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.Locality))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Locality, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.Region))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Locality, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.PostalCode))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Locality, XmlSchemaString, Options.AuthenticationType));
}
if (!string.IsNullOrEmpty(context.Country))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Locality, XmlSchemaString, Options.AuthenticationType));
}
context.Properties = properties;
await Options.Provider.Authenticated(context);
return new AuthenticationTicket(context.Identity, context.Properties);
}
catch (Exception ex)
{
_logger.WriteError(ex.Message);
}
return new AuthenticationTicket(null, properties);
}
protected override Task ApplyResponseChallengeAsync()//Nimisha-1
{
if (Response.StatusCode != 401)
{
return Task.FromResult<object>(null);
}
//If Response is 401 then check here based on saved Expiration duration for token and refreshtoken and then make either Refresh Token call or Access Token call
//if(SavedTokenExpiryTime is not null and is >=DateTime.Now) then call RefreshToken api call
//or
//Call below
var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge == null) return Task.FromResult<object>(null);
var baseUri =
Request.Scheme +
Uri.SchemeDelimiter +
Request.Host +
Request.PathBase;
var currentUri =
baseUri +
Request.Path +
Request.QueryString;
//var redirectUri =
// baseUri +
// Options.CallbackPath;//Nimisha check callback path
var redirectUri = "https://be97d742.ngrok.io/signin-Hidden";
var properties = challenge.Properties;
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = currentUri;
}
// OAuth2 10.12 CSRF
GenerateCorrelationId(properties);
// comma separated
var scope = string.Join(" ", Options.Scope);
var state = Options.StateDataFormat.Protect(properties);
//Nimisha //"https://appcenter.Hidden.com/connect/oauth2" + //Nimisha check
var authorizationEndpoint =
Options.Endpoints.AuthorizationEndpoint+
"?client_id=" + Uri.EscapeDataString(Options.ClientId) +
"&response_type=code" +
"&scope=" + Uri.EscapeDataString(scope) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&state=" + Uri.EscapeDataString(state);
Response.Redirect(authorizationEndpoint);
return Task.FromResult<object>(null);
}
public override async Task<bool> InvokeAsync()
{
return await InvokeReplyPathAsync();
}
private async Task<bool> InvokeReplyPathAsync()
{
if (!Options.CallbackPath.HasValue || Options.CallbackPath != Request.Path) return false;
// TODO: error responses
var ticket = await AuthenticateAsync();
if (ticket == null)
{
_logger.WriteWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}
var context = new HiddenReturnEndpointContext(Context, ticket)
{
SignInAsAuthenticationType = Options.SignInAsAuthenticationType,
RedirectUri = ticket.Properties.RedirectUri
};
await Options.Provider.ReturnEndpoint(context);
if (context.SignInAsAuthenticationType != null &&
context.Identity != null)
{
var grantIdentity = context.Identity;
if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal))
{
grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType);
}
Context.Authentication.SignIn(context.Properties, grantIdentity);
}
if (context.IsRequestCompleted || context.RedirectUri == null) return context.IsRequestCompleted;
var redirectUri = context.RedirectUri;
if (context.Identity == null)
{
// add a redirect hint that sign-in failed in some way
redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied");
}
Response.Redirect(redirectUri);
context.RequestCompleted();
return context.IsRequestCompleted;
}
}
}

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.

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

Resources