Worlight.Connect() throwing "Error retrieving device data" - xamarin

In my Android project, I am trying to connect to the Worklight server (CLI) but after the client.Connect() method call, when I look at the task result, it has an error message saying Error retrieving device data and HTTP status 500. However, I can see the activity count increasing in the Analytics portal.
I am following the sample that comes along with the Xamarin Worklight SDK. All I did was changing the Realm to another one and stripped out irrelevant methods and kept the ConnectAsync & Connect methods alone.
If I run the Worklight sample application that comes along with the SDK, I don't see this error in the task. It gets back a HTTP 200 and everything looks good.
Here is the code, for clarity sake.
private async Task<WorklightResponse> Connect()
{
//lets send a message to the server
client.Analytics.Log("Trying to connect to server", metadata);
ChallengeHandler customCH = new CustomChallengeHandler(appRealm);
client.RegisterChallengeHandler(customCH);
WorklightResponse task = await client.Connect();
//lets log to the local client (not server)
client.Logger("Xamarin").Trace("connection");
//write to the server the connection status
client.Analytics.Log("Connect response : " + task.Success);
return task;
}

This probably has to do with you Android app permissions. Edit your Android project options. In the Android Application->Required Permissions list, select the appropriate permissions. For example, one of my apps requires:
AccessNetworkState
AccessWiFiState
GetAccounts
Internet
UseCredentials
WakeLock
WriteExternalStorage
I have received the same error message without the appropriate permissions. Your list may vary depending on requirements.

By default, the SubscribeServlet is tied to a rejectAll login module which rejects all login requests. If you have not changed the login module, then this is probably why you're seeing your login rejected.
Try changing the login module to a different one if you're using the rejectAll login module

Related

Bot Channels Registration - There was an error sending this message to your bot: HTTP status code Unauthorized

I am in the process of building a chat bot that will integrate with Teams or Slack. To get started I am using the echo bot template, but I am adding it to an exiting API that I have in my Service Fabric Cluster.
When running the application locally, I can connect to it fine from the Bot Emulator, but when I deploy it to my Azure channel registration, and test it in the web chat I get:
There was an error sending this message to your bot: HTTP status code Unauthorized.
I am setting the AppID and Password and they are saved and being retrieved from KeyVault, and I throw an exception at startup if either of the values are blank (which is not the case).
I set it as follow:
services.AddBot<EchoBot>(options =>
{
options.CredentialProvider = new SimpleCredentialProvider(Configuration["MicrosoftAppId"], Configuration["MicrosoftAppPassword"]);
options.OnTurnError = async (context, exception) =>
{
ServiceEventSource.Current.Message(exception.Message);
await context.SendActivityAsync("Sorry, it looks like something went wrong.");
};
});
I have added a teams channel, where the error does not occur, but the message never reaches the server.
The service is reachable and the controller allows unauthorized credentials while this is in testing.
Solved my own issue.
It turns out that if you are using a self signed certificate, then this could occur, as per Microsofts documents found here -
If one or more error(s) are indicated in the chat window, click the error(s) for details. Common issues include:
The emulator settings specify an incorrect endpoint for the bot. Make sure you have included the proper port number in the URL and the proper path at the end of the URL (e.g., /api/messages).
The emulator settings specify a bot endpoint that begins with https. On localhost, the endpoint should begin with http.
In the emulator settings, the Microsoft App ID field and/or the Microsoft App Password do not contain valid values. Both fields should be populated and each field should contain the corresponding value that you verified in Step 2.
Security has not been enabled for the bot. Verify that the bot configuration settings specify values for both app ID and password.
Lessons Learnt
Read the doc's
When you get frustrated, calm down and read the doc's

Configuring OAuth 2 Authentication with NativeScript provided Enterprise Auth project template

I am Configuring OAuth 2 Authentication with NativeScript provided Enterprise Auth project template, I followed the complete guide to configure Azure Active Directory. After setting up URLs and keys when I am executing the application through tns preview, it is giving me following error:
https://auth.kinvey.com/v3/oauth/auth?client_id=kid_SJcDEau7N&redirect_uri=nsplayresume%3A%2F%2F&response_type=code&scope=openid
Error:
{"error":"invalid_client","error_description":"Client authentication failed.","debug":"Client Verification Failed: redirect uri not valid"}
When I check the login script it was showing error because there was no argument given in the Kinvey.User.loginWithMIC() function so I provided Kinvey.User.loginWithMIC('http://example.com') as it was showing in the video tutorial.
login() {
if (Kinvey.User.getActiveUser() == null) {
Kinvey.User.loginWithMIC()
.then((user: Kinvey.User) => {
this.navigateHome();
console.log("user: " + JSON.stringify(user));
})
.catch((error: Kinvey.BaseError) => {
alert("An error occurred. Check your Kinvey settings.");
console.log("error: " + error);
});
} else {
this.navigateHome();
}
}
as expected it should show the login screen for the account which I have configured in Azure Active Directory.
Here I have a NativeScript solution, which makes use of Kinvey's Mobile Identity Connect. It's basically built using the same template that you would like to make use of. There are couple of important steps, that you need to take care before running that project, they are as follows:
Open kinvey.common.ts file from inside the src/app/shared folder and
set your Application ID and Application Secret (and Instance ID if
present, if not - remove the attribute). That's needed so that the NativeScript application can connect to your Kinvey Backend.
Open the Login component's TypeScript controller and set your MIC identifier. The MIC identifier is the MIC Service's ID. That will tell the app which service to refer to from the backend.
Open the MIC Service settings from the Kinvey Console and set myscheme:// as a redirect URI. The authorization endpoint normally redirects the user back to the client’s registered redirect URL. Depending on the platform, native apps can either claim a URL pattern, or register a custom URL scheme that will launch the application. For example, an iOS application may register a custom protocol such as myapp:// and then use a redirect_uri of myapp://callback.
For most up-to-date list of those crucial items, you can check out the repository's README file. Try that, and let me know if you can get Kinvey MIC working.

Using Windows Authentication to call a Web API from a Windows Store application

Here is the context of my issue: I am developing a Windows Store application that will be side-loaded on several tablets our client is planning to use. This tablet app will make calls into a Web API which in turn will do CRUD operations with a repository (SQL Server via EntityFramework). Everything has to use Windows Authentication. The tablets are Dell running Windows 10. Each user will log in with its own active domain credentials. The tablet will pass the credentials to the Web API which in turn will pass them to the repository (database). Based on the credentials, the repository will determine the group the user belongs to and based on that, it will give access to resources the user is allowed to access.
My Web API works fine. I tested it with Fiddler. For the HTTP GET request, I want to test, I checked the "Automatically Authenticate" checkbox and I can see the three successive messages, first two returning with 401 and the third returning HTTP Code 200, along with the data I requested.
However, when I try to call it from my Windows Store app, I only send one GET Request, the first one. My Web API is hosted in IIS Express. At the advice of a very distinct member of this group, I configured IIS Express to expose the Web API using the IP address of my development machine rather than "localhost". Before doing this I wouldn't see any GET Requests hitting the server, not even the first one.
I know that Windows Authentication uses the NTLM scheme and it requires a negotiation process, hence the 3 messages Fiddler sends initially to the server?
How do I need to write my Web API Client code to bypass this negotiation? I spent all morning and afternoon reading solutions to my problem, here on SO and many other websites, but somehow, I still did not get it to work. I must be missing something and I don't know what. Here is my code on the Web API Client side:
var authHandler = new HttpClientHandler()
{
Credentials = CredentialCache.DefaultNetworkCredentials,
ClientCertificateOptions = ClientCertificateOption.Automatic
};
var webApiClient = new HttpClient(authHandler)
{
BaseAddress = new Uri(_serviceUri), // _serviceUri is a string that looks like this "http://10.120.5.201:53045"
};
webApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await webApiClient.GetAsync("api/user");
My call never returns from GetAsync, but in Fiddler, I can see only the first GET Requests being posted to the server. How can I get my client to follow up, behind the scenes, just like Fiddler does, and send the other two messages so that, eventually, the third one would return with a response HTTP 200 code and with the data I receive in Fiddler?
If anyone can point me in the right direction, I would be highly appreciative.
The problem was that the "Enterprise Authentication" setting was not set in the Capabilities tab of the Package.appxmanifest file of my app. It took me a while to figure out that that was the problem, but as soon as I checked it, my app started using Windows Authentication.

Windows Store App Push Notifications via Azure Service Bus

I'm trying to send a push notification to my Windows Store App developed in my laptop using VS 2013 Express. It's been few days now but I cannot figure out why I get "The Token obtained from the Token Provider is wrong" error. I use Windows Azure Notification Bus for this purpose. I use VS Server Explorer to send test notifications. I can see my laptop is being registered as a device in the Device Registration tab too. I tried the Azure portal as well, but the same error. However, when I try to connect to Service Bus Explorer 2.4.3.0 providing the connection string it throws below error.
<21:47:14> Exception: The remote server returned an error: (401) Unauthorized. Manage claim is required for this operation..TrackingId:c0c4fea2-08bc-4def-964c-ec6e690b7551_G45,TimeStamp:10/12/2014 4:17:11 PM. Method b__7e: retry 2 of 10.
FYI: I'm following below article step by step.
http://azure.microsoft.com/en-us/documentation/articles/notification-hubs-windows-store-dotnet-get-started/
Please help me. Thank you.
Mahesh
Looks like token is just expired. Make sure you obtain token each time application starts. In terms of the article you refer it means you should call method InitNotificationsAsync() to do it. Here is that method:
private async void InitNotificationsAsync()
{
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
var hub = new NotificationHub("<hub name>", "<connection string with listen access>");
var result = await hub.RegisterNativeAsync(channel.Uri);
// Displays the registration ID so you know it was successful
if (result.RegistrationId != null)
{
var dialog = new MessageDialog("Registration successful: " + result.RegistrationId);
dialog.Commands.Add(new UICommand("OK"));
await dialog.ShowAsync();
}
}

In ASP.NET is there an event fired on a Windows Authentication log in failure? (Logging the details of a Windows Authentication failure)

I am building a .NET 4.0, ASP.NET MVC 3 intranet application that runs on IIS 7.5 in integrated mode. Windows Authentication is used to govern access to the website. The Windows Authentication module is enabled and all other auth modules are disabled.
Currently when a user provides improper credentials, the Windows Authentication module correctly rejects the credentials and re-displays a login prompt. It does so 3 times, after which a standard .NET 401 Unauthorized Access page is shown. This is expected and desirable.
My goal: I would like to be able to log the details of the failed authentication attempt to my own custom event log. Particularly, to capture the user name that was used in the log in attempt. (I'll accept that capturing the password is not likely to be possible for security reasons.)
Is my goal possible?
I have already built a working an IHttpModule module and added it as an event handler to the WindowsAuthenticationModule, like this:
myWindowsAuthenticationModule.Authenticate += WindowsAuthentication_Authenticate;
But my code does not get called in the case of a failed log in attempt, presumably because WindowsAuthenticationModule has already decided that the log in is failed and so there is no point calling my module. My module does get called after a successful log in attempt, and so I am certain that my event handler is properly set up.
To the best of my knowledge, the WindowsAuthenticationModule does not expose an event that is fired when authentication fails, so that option is out.
Any ideas? Or am I barking up a tree that has no solution?
I was looking at the same issue, and looks like there is no events for windows authentication, even that Authenticate event is common for forms and windows.
But I found a solution to this!
http://www.codeproject.com/Articles/11202/Redirecting-to-custom-401-page-when-quot-Access-de
UPDATE
From original article
protected void Application_EndRequest(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context.Response.Status.Substring(0,3).Equals("401"))
{
if(User.Identity.IsAuthenticated)
{
// this means user is authenticated, but 401 still returned
// which means no access to page or whatever you are trying to access?
}
}
}
UPDATE2
I also found out that this solution doesn't work in all cases. I was testing in different environments, so was working for me, but not for others.
By default IIS will not even run this piece of code and just return it's own error page, what you want to do is tell IIS to let app handle errors.
<httpErrors existingResponse="PassThrough">
</httpErrors>
Now, with that said, IIS won't return any more of custom errors and you will need to handle them in application, ie. not only 401, but 403, 405, etc

Resources