Client Side recaptcha verify throws 503 "service is not available" - c#

The URL works if I run it in a browser, so key and response are correct. However when I run the code locally, it throws a 503 error. Any ideas?
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
namespace ProjectM2.Shared
{
public class ReCaptcha
{
public bool Success { get; set; }
public List<string> ErrorCodes { get; set; }
public static bool Validate(string encodedResponse)
{
if (string.IsNullOrEmpty(encodedResponse)) return false;
var client = new System.Net.WebClient();
var secret = ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"];
if (string.IsNullOrEmpty(secret)) return false;
var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, encodedResponse));
var reCaptcha = JsonConvert.DeserializeObject<ReCaptcha>(googleReply);
return reCaptcha.Success;
}
}
}

Solved. It turns out it was the web filter was the culprit. I moved my machine to a vlan without the web filter and the code works.
Thanks to everyone who took the time to read and answer my question.

Related

WebClient taking 43 seconds to download this json string https://jsonplaceholder.typicode.com/posts

12 hours ago (around dinner time here in Texas), it was working just fine at a moment when I hope the latency to be very high because of the high traffic.
Any idea why this could be happening and how to troubleshoot this issue?
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Nancy.Json;
namespace Training.Threading
{
class TasksDemo
{
static async Task Main(string[] args)
{
Post[] posts = await GetPostsAsync();
foreach(Post post in posts)
System.Console.WriteLine(post.Title);
}
public static Task<Post[]> GetPostsAsync() => Task.Run(() =>
{
var json = new WebClient().DownloadString("https://jsonplaceholder.typicode.com/posts");
JavaScriptSerializer ser = new JavaScriptSerializer();
var posts = ser.Deserialize<Post[]>(json);
return posts;
});
}
public class Post
{
public int UserId { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}
I don't think the code is the issue here. It is more so your ISP or the bandwith available to the server / traffic you are trying to contact.
Some tools that will help you diagnose the issue specifically in windows to spot your issue include
'tracert' (trace route)
'ping' (ping)
In Windows:
ping jasonplaceholder.typicode.com
To view latency between "hops"
tracert jsonplaceholder.typicode.com
this will provide in milliseconds the latency to the server you are trying to reach assuming they respond to ping request ICMP.
Following the advice fo #maccettura and #ckuri I'm using now HttpClient, I thought I'd be good to post the code here.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Nancy.Json;
namespace Training.Threading
{
class TasksDemo
{
static async Task Main(string[] args)
{
string json = await GetPostsAsync();
// System.Console.WriteLine(json);
JavaScriptSerializer ser = new JavaScriptSerializer();
var posts = ser.Deserialize<Post[]>(json);
foreach(Post post in posts)
System.Console.WriteLine(post.Title);
}
public static async Task<string> GetPostsAsync()
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(#"https://jsonplaceholder.typicode.com");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return await client.GetStringAsync("/posts");
}
}
}
public class Post
{
public int UserId { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
}

ASP.Net MVC C#: Failed to acquire token silently as no token was found in the cache. Call method AcquireToken

I am attempting to retrieve Azure AD user profile data via the Microsoft Graph API. I have set up a small Visual Studio MVC app using code examples from various sources, primarily Microsoft. In my ignorance, I thought this would be a fairly simple process.
I have browsed other similar cases on SO and have attempted to make use of suggestions from others but to no avail. I have been troubleshooting this issue for four days and would greatly appreciate any assistance.
// UserProfileController.cs
-- contains the calling method: var graphToken = await AuthenticationHelper.GetGraphAccessToken();
//
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using SSO_Test.Models;
using SSO_Test.Utils;
using System.Net.Http.Headers;
namespace SSO_Test.Controllers
{
[Authorize]
public class UserProfileController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
private string clientId = ConfigurationManager.AppSettings["ClientId"];
private string appKey = ConfigurationManager.AppSettings["ClientSecret"];
private string aadInstance = ConfigurationManager.AppSettings["AADInstance"];
private string graphResourceID = "https://graph.microsoft.com";
// GET: UserProfile
public async Task<ActionResult> Index()
{
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
try
{
var graphToken = await AuthenticationHelper.GetGraphAccessToken();
var authenticationProvider = new DelegateAuthenticationProvider(
(requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
return Task.FromResult(0);
});
var graphClient = new GraphServiceClient(authenticationProvider);
var user = await graphClient.Me.Request().GetAsync();
return View(user);
}
catch (AdalException ex)
{
// Return to error page.
ViewBag.Message = ex.Message;
return View("Error");
}
// if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
catch (Exception)
{
return View("Relogin");
}
}
public void RefreshSession()
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/Home" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
}
//AuthenticationHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using SSO_Test.Models;
namespace SSO_Test.Utils
{
public static class AuthenticationHelper
{
public static async Task<string> GetGraphAccessToken()
{
var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var userObjectId = ClaimsPrincipal.Current.FindFirst(SettingsHelper.ClaimTypeObjectIdentifier).Value;
var clientCredential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
var userIdentifier = new UserIdentifier(userObjectId, UserIdentifierType.UniqueId);
// create auth context
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureAdAuthority, new ADALTokenCache(signInUserId));
//added check point for verification purposes
System.Diagnostics.Debug.WriteLine("Check point #1");
//GOOD TO THIS POINT
var result = await authContext.AcquireTokenSilentAsync(SettingsHelper.AzureAdGraphResourceURL, clientCredential, userIdentifier);
//ERROR MESSAGE: "Failed to acquire token silently as no token was found in the cache. Call method AcquireToken"
System.Diagnostics.Debug.WriteLine("Check point #2");
//app never reaches the second check point
return result.AccessToken;
}
}
}
//ADALTokenCache.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Security;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
namespace SSO_Test.Models
{
public class ADALTokenCache : TokenCache
{
private ApplicationDbContext db = new ApplicationDbContext();
private string userId;
private UserTokenCache Cache;
public ADALTokenCache(string signedInUserId)
{
// associate the cache to the current user of the web app
userId = signedInUserId;
this.BeforeAccess = BeforeAccessNotification;
this.AfterAccess = AfterAccessNotification;
this.BeforeWrite = BeforeWriteNotification;
// look up the entry in the database
Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
// place the entry in memory
this.DeserializeAdalV3((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits, "ADALCache"));
}
// clean up the database
public override void Clear()
{
base.Clear();
var cacheEntry = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
db.UserTokenCacheList.Remove(cacheEntry);
db.SaveChanges();
}
// Notification raised before ADAL accesses the cache.
// This is your chance to update the in-memory copy from the DB, if the in-memory version is stale
void BeforeAccessNotification(TokenCacheNotificationArgs args)
{
if (Cache == null)
{
// first time access
Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
}
else
{
// retrieve last write from the DB
var status = from e in db.UserTokenCacheList
where (e.webUserUniqueId == userId)
select new
{
LastWrite = e.LastWrite
};
// if the in-memory copy is older than the persistent copy
if (status.First().LastWrite > Cache.LastWrite)
{
// read from from storage, update in-memory copy
Cache = db.UserTokenCacheList.FirstOrDefault(c => c.webUserUniqueId == userId);
}
}
this.DeserializeAdalV3((Cache == null) ? null : MachineKey.Unprotect(Cache.cacheBits, "ADALCache"));
}
// Notification raised after ADAL accessed the cache.
// If the HasStateChanged flag is set, ADAL changed the content of the cache
void AfterAccessNotification(TokenCacheNotificationArgs args)
{
// if state changed
if (this.HasStateChanged)
{
Cache = new UserTokenCache
{
webUserUniqueId = userId,
//cacheBits = MachineKey.Protect(this.Serialize(), "ADALCache"),
cacheBits = MachineKey.Protect(this.SerializeAdalV3(), "ADALCache"),
LastWrite = DateTime.Now
};
// update the DB and the lastwrite
db.Entry(Cache).State = Cache.UserTokenCacheId == 0 ? EntityState.Added : EntityState.Modified;
db.SaveChanges();
this.HasStateChanged = false;
}
}
void BeforeWriteNotification(TokenCacheNotificationArgs args)
{
// if you want to ensure that no concurrent write take place, use this notification to place a lock on the entry
}
public override void DeleteItem(TokenCacheItem item)
{
base.DeleteItem(item);
}
}
}
//ApplicationDbContext.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace SSO_Test.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public DbSet<UserTokenCache> UserTokenCacheList { get; set; }
}
public class UserTokenCache
{
[Key]
public int UserTokenCacheId { get; set; }
public string webUserUniqueId { get; set; }
public byte[] cacheBits { get; set; }
public DateTime LastWrite { get; set; }
}
}
As you can see, I have noted in the GetGraphAccessToken() method the error message:
"Failed to acquire token silently as no token was found in the cache.
Call method AcquireToken".
I was able to isolate the AcquireTokenSilentAsync() method as the culprit by bracketing it with a pair of Debug.Writeline statements, the first which ran successfully and the second which did not. This was verified by reviewing the contents of the VS Output window, as follows:
Check point #1
Exception thrown:
'Microsoft.IdentityModel.Clients.ActiveDirectory.AdalSilentTokenAcquisitionException'
in mscorlib.dll
The program '[13980] iisexpress.exe' has exited with code -1
(0xffffffff).
I really want this thing to work and I would much prefer utilizing the Graph SDK approach as opposed to using a REST API.
Again, I have been banging my head against the wall for four-plus days. My head is okay but the wall is in bad shape.
Thanks in advance.
If AcquireTokenSilent fails, it means that there is no token in the cache so you have to go get one via AcquireToken as in this.
You've tagged the question with "B2C" but is looks like you are using Azure AD?
There are a full set of Authentication Providers for the standard set of OAuth flows that are now available so you don't have to use the DelegatedAuthenticationProvider any more. https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth There are docs about how to chose the right Auth provider based on scenario here https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS

Authenticating with Clockify API?

I'm working on a new application where I need to use Clockify's API. When I make my test application for a proof of concept, I notice that I'm getting a 401 error as a response to using one of their base functions, get clients by work space. Am I missing something with the authentication? Is there a setting I need to allow on my profile? The error I'm getting is: System.Net.WebException: 'The remote server returned an error: (401) Unauthorized.' Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Api
{
public class ApiHelper
{
public static HttpClient ApiClient { get; set; } = new HttpClient();
public static void InitializeClient(string username, string password)
{
ApiClient = new HttpClient();
ApiClient.BaseAddress = new Uri("https://api.clockify.me/api/");
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static void GetClientsFromWorkspace(string workspace)
{
ApiClient.DefaultRequestHeaders.Add("X-Api-Key", "*********");
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://api.clockify.me/api/workspaces/" + workspace + "/clients");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "GET";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
}
}
You’re setting the api key header on the ApiClient but then making your request with a newly createdHttpWebRequest which doesn’t then have the required api key header.
You should either make your request using the ApiClient or add the X-Api-Key header to theHttpWebRequest as follows:
httpWebRequest.Headers.Add(“X-Api-Key”, “********”)

How to get magento admin token with restsharp

I'm pretty new to rest API and restsharp so I need some help. I need to get a magento version 2.2.3 admin token but I keep getting a bad request. I've followed this tutorial: https://www.youtube.com/watch?v=2sdGuC7IUAI&t=343s. But I'm ending up with a bad request. When I check the statuscode using a the breakpoints from the tutorial I get: NotFound.
My main goal is to get the categories I have in Magento. But to get that I need an admin token. I already have a bearer acces code etc.
I would really appreciate your help.
my code so far:
magento.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using Newtonsoft.Json;
namespace MagentoTest
{
public class magento
{
private RestClient Client { get; set; }
private string Token { get; set; }
public magento(string magentoUrl)
{
Client = new RestClient(magentoUrl);
}
public magento(string magentoUrl,string token)
{
Client = new RestClient(magentoUrl);
Token = token;
}
public string GetAdminToken(string userName, string passWord)
{
var request = CreateRequest("/rest/V1/integration/admin/token", Method.POST);
var user = new Credentials();
user.username = userName;
user.password = passWord;
string Json = JsonConvert.SerializeObject(user, Formatting.Indented);
request.AddParameter("aplication/json", Json, ParameterType.RequestBody);
var response = Client.Execute(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
return response.Content;
}
else
{
return "";
}
}
private RestRequest CreateRequest(string endPoint, Method method)
{
var request = new RestRequest(endPoint, method);
request.RequestFormat = DataFormat.Json;
return request;
}
}
}
Credentials:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MagentoTest
{
public class Credentials
{
public string username { get; set; }
public string password { get; set; }
}
}
(Client)
Program.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MagentoTest;
namespace Client
{
class Program
{
static void Main(string[] args)
{
GetToken("blabla", "blabla");
}
static void GetToken(string userName, string passWord)
{
var m2 = new magento("http://beta.topprice24.com");
string token = m2.GetAdminToken(userName, passWord);
}
}
}
It looks, relative URL needs to be changed as "/rest/default/V1/integration/admin/token"
(https://devdocs.magento.com/guides/v2.1/get-started/order-tutorial/order-admin-token.html).
I have simplified the above code and you can easily get the token.
Keep your Credentials class as it is and change your main program as below
Modified Code:(Program.cs)
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Client
{
class Program
{
static void Main(string[] args)
{
//Base URL needs to be Specified
String host = "http://beta.topprice24.com";
//Relative URL needs to be Specified
String endpoint = "/rest/default/V1/integration/admin/token";
RestClient _restClient = new RestClient(host);
var request = new RestRequest(endpoint, Method.POST);
//Initialize Credentials Property
var userRequest = new Credentials{username="blabla",password="blabla"};
var inputJson = JsonConvert.SerializeObject(userRequest);
//Request Header
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Accept", "application/json");
//Request Body
request.AddParameter("application/json", inputJson, ParameterType.RequestBody);
var response = _restClient.Execute(request);
var token=response.Content;
}
}
}

How to Connect WebServiceURL in Xamarin.Forms project?

Good Day Everyone. I'm creating Xamarin.Forms Portable Application in my Visual Studio 2015.
I want my Mobile Application to connect to the SQL Database I have in my VS2015 and return a LIST OF CUSTOMERS which should be display to my mobile phone.
In my solution, I have created a Xamarin Portable project and a WebForms project that will handle my Web Services and Database.
In my WebForms project, I was able to retrieve data from the Database using LINQ expression. I even checked this by using WEB API and I was really able to retrieved data. Like the image below :
What I want to do is to access this data to my Xamarin Portable project using RestClient. I used the WebServiceUrl of my WebForms project to get the data it contains. But whenever I used a Breakpoint to test if it retrieved the Data, it does not return any value.
Meaning I won't really be able to display the LIST OF CUSTOMERS.
What do you think is the reason behind this?
Here are some of my codes :
1.) WebForms
CustomerController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WebFormsDemo;
using WebFormsDemo.ViewModel;
namespace WebFormsDemo.Controllers
{
public class CustomerController : ApiController
{
private EBMSEntities db = new EBMSEntities();
// GET: api/Customer
public IQueryable<CustomerViewModel> GetCustomerViewModels()
{
var displaycustomerInfo = from cust in db.CUSTOMERs
select new CustomerViewModel
{
Id = cust.CUSTOMER_ID,
CUSTOMER_CODE = cust.CUSTOMER_CODE,
CUSTOMER_NAME = cust.CUSTOMER_NAME,
CUSTOMER_MOBILE_NUMBER = cust.CUSTOMER_MOBILE_NUMBER,
CUSTOMER_EMAIL_ADDRESS = cust.CUSTOMER_EMAIL_ADDRESS,
CUSTOMER_CONTACT = cust.CUSTOMER_EMAIL_ADDRESS + "," + " " + cust.CUSTOMER_MOBILE_NUMBER
};
return displaycustomerInfo;
}
}
}
2.) XamarinForms
RestClient.cs
public class RestClient_Customer <T>
{
private const string WebServiceUrl = "http://localhost:50857/api/Customer/";
public async Task<List<T>> GetCustomerAsync()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
}
.
CustomerServices.cs
using Plugin.RestClient;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using XamarinFormsDemo.Models;
namespace XamarinFormsDemo.Services
{
public class CustomerServices
{
public async Task<List<Customer>> GetCustomerAsync()
{
RestClient_Customer<Customer> restClient = new RestClient_Customer<Customer>();
var customerList = await restClient.GetCustomerAsync(); //yung getasync ay pantawag as restclient
return customerList;
}
}
}
.
CustomerVM.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
using XamarinFormsDemo.Models;
using XamarinFormsDemo.Services;
using XamarinFormsDemo.Views;
namespace XamarinFormsDemo.ViewModels
{
public class CustomerVM : INotifyPropertyChanged
{
private List<Customer> _customerList; // keep all customers
private List<Customer> _searchedCustomerList; // keep a copy for searching
private Customer _selectedCustomer = new Customer();
private string _keyword = "";
public string Keyword
{
get
{
return _keyword;
}
set
{
this._keyword = value;
// while keyword changed we filter Employees
//Filter();
}
}
private void Filter()
{
if (string.IsNullOrWhiteSpace(_keyword))
{
CustomerList = _searchedCustomerList;
}
else
{
// var lowerKeyword = _keyword.ToLower();
CustomerList = _searchedCustomerList.Where(r => r.CUSTOMER_NAME.ToLower().Contains(_keyword.ToLower())).ToList();
// EmployeesList = _searchedEmployeesList.Where(r => r.EMPLOYEE_NAME.Contains(_keyword)).ToList();
}
}
public List<Customer> CustomerList
{
get
{
return _customerList;
}
set
{
_customerList = value;
OnPropertyChanged();
}
}
public CustomerVM()
{
InitializeDataAsync();
}
private async Task InitializeDataAsync()
{
var customerServices = new CustomerServices();
_searchedCustomerList = await customerServices.GetCustomerAsync();
CustomerList = await customerServices.GetCustomerAsync();
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
NOTE: Please take a closer look to my RestClient whether I'm doing it right thing or not. Thanks a lot.
I dont think it is the problem with emulator or phone. You cant just connect to localhost over your android device. you must use the external ip address provided by the router if it is connected to Wireless. Please see these 2 topics
How can I access my localhost from my Android device?
How to connect to my http://localhost web server from Android Emulator in Eclipse

Categories

Resources