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.
Related
I created a Teams tab application by customizing the SSO react app sample from the Teams toolkit. The application redirects the user to our website (inside one of the tabs). I can grab the id-token in react (teamsfx.getCredentials().getToken("")) and pass it to our web application via a query parameter.
This id-token is validated and then passed around to various microservices that comprise our backend.
This part works well, but then, we had the need to refresh the token. So, we decided for the web application (written in Angular) to fetch the token using #microsoft/teamsfx and #microsoft/teams-js npm packages.
While I am not certain if that is the way to go, when I execute the following code inside an angular service, it throws the "SDK initialization timed out" error.
try {
const teamsFx: TeamsFx = new TeamsFx(IdentityType.User, {
"clientId": "ee89fb47-a378-4096-b893-**********",
"objectId": "df568fe9-3d33-4b22-94fc-**********",
"oauth2PermissionScopeId": "4ce5bb24-585a-40d3-9891-************",
"tenantId": "5d65ee67-1073-4979-884c-**************",
"oauthHost": "https://login.microsoftonline.com",
"oauthAuthority": "https://login.microsoftonline.com/5d65ee67-1073-4979-884c-****************",
"applicationIdUris": "api://localhost/ee89fb47-a378-4096-b893-***************",
"frontendEndpoint": "https://localhost",
"initiateLoginEndpoint": "https://localhost:8101"
});
const creds = await teamsFx.getCredential().getToken('https://graph.microsoft.com/User.Read');
const token = creds?.token;
console.log("New Token: ", token);
const expirationTimestamp = creds?.expiresOnTimestamp;
this.scheduleRefresh(expirationTimestamp);
this.tokenRefreshed.next({ token: token, expiresOnTimestamp: expirationTimestamp });
}
catch (error) {
console.error("Error in getNewTeamsToken(): ", error);
}
Am I missing anything here, or is the approach itself wrong? Please advise.
Teams is basically just using MSAL under the covers (with a bit of other stuff thrown in I think) to get the token. If you want to be able to authenticate your user outside of Teams, in a separate web app, you can simply use MSAL yourself (something like this I'd guess: https://learn.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-angular-auth-code).
That would mean, essentially, that you have a tab web app, doing Teams SSO and then a separate standalone Angular app doing direct MSAL auth. Does you tab app actually do anything? If not, and you're only using it to redirect, you can instead combine these into a single app, and detect in the app whether you're in Teams or not - if you are, do SSO using TeamsFX. If not, do MSAL login directly. This link shows how to detect if your inside of Teams or not.
If you want to continue with separate apps that's fine, but I absolutely would not pass the token as a QueryString parameter - that is extremely dangerous. First of all, tokens are not meant to be passed like this at all, as they could be intercepted. Secondly, passing them on Querystring means that they are entirely open - anything inbetween can sniff the address and lift out your token (if it was a POST payload with httpS, for instance, at least the 'S' would be encrypting the token between browser and server).
I have Azure Bot deployed with Virtual Assistant Template, which was working fine (And still working in Portal's Test In Web Chat feature) until I enabled Direct Line App Service Extension.
Primary objective to enable DL App Service extension is to isolate bot access and secure app service.
I have followed MS documentation https://learn.microsoft.com/en-us/azure/bot-service/bot-service-channel-directline-extension-net-bot?view=azure-bot-service-4.0 and ensured every step is configured correctly.
Primary step to make sure DL app service is working correctly is to check if https://xxx.azurewebsites.net/api/messages or https://xxx.azurewebsites.net/.bot/ url return correct json result f.x: {"v":"123","k":true,"ib":true,"ob":true,"initialized":true}
But instead i am getting Error Response 400 Bad Request and error message appeared in browser is : "Upgrade to WebSocket is required."
I couldn't even reach to a step where troubleshooting guide mentioned here : https://learn.microsoft.com/en-us/azure/bot-service/bot-service-channel-directline-extension-net-bot?view=azure-bot-service-4.0#troubleshooting could help to resolve.
As i said earlier Bot is still working and the url : https://xxx.azurewebsites.net loads site correctly , can be seen in below
Any help is appreciated
These are the changes I have done and it worked:
Refer Repo With sample code:
https://github.com/SSanjeevi/VirtualAssistantDirectlineExtn
Wrote detailed here.
Project file:
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
<NoWarn>NU1701</NoWarn>
<Version>1.0.3</Version>
BotController.cs
private readonly IBotFrameworkHttpAdapter adapter;
public BotController(IBotFrameworkHttpAdapter httpAdapter, IBot bot)
Startup.cs
Configure Services method:
// Register the Bot Framework Adapter with error handling enabled.
// Note: some classes use the base BotAdapter so we add an extra registration that pulls the same instance.
services.AddSingleton<IBotFrameworkHttpAdapter, DefaultAdapter>();
services.AddSingleton<BotAdapter>(sp => sp.GetService<BotFrameworkHttpAdapter>());
// Configure channel provider
Configure method:
using Microsoft.Bot.Builder.Integration.AspNet.Core;
app.UseHsts();
app.UseCors(x => x.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
// Allow the bot to use named pipes.
app.UseNamedPipes(System.Environment.GetEnvironmentVariable("APPSETTING_WEBSITE_SITE_NAME") + ".directline");
Webchat:
let directLineConnection = await window.WebChat.createDirectLineAppServiceExtension({
domain: domainUrl,
token
});
The attached repo code also contains serilog implementation to have logging in log stream in app service where you can see the error logs if you face any issues.
Follow this article and implement serilog in bot api and deploy .
https://www.lkgforit.com/2022/10/troubleshooting-by-writing-logs-at_15.html
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
I'm trying to fit the Okta Asp.NET Core Mvc example (https://github.com/oktadeveloper/okta-aspnetcore-mvc-example) into my React Asp.Net Core app. (The reason I'm not using Okta's React example is that it uses Babel and my VS2017 React project uses Typescript.) The Mvc example runs fine against my Okta account, and my React app compiles and runs w the Okta SDK and other code copied from the Mvc example, but I can't get it to authenticate.
Okta returns an http 400: Identity Provider: unknown, Error Code: invalid request, Description: the 'redirect_uri' parameter must be an absolute Uri that is whitelisted in the client app settings.
All I've done is add [authorize] attribs to my controller and a button that requests account/login. Both actions return the same error. I do have the app Url in my Okta app settings.
This, most likely does not have anything to do with React/asp.net but the OIDC flow. If we strip down the SDK, your call to get the jwt token will look something like this: {{url}}/oauth2/v1/authorize?idp=0oae59ifqdtRaTT4G0h7&client_id={{client_id}}&response_type=id_token&response_mode=fragment&scope=openid&redirect_uri=https://www.bing.com
note the redirect_uri above should be the listed in your application setting. To do that: go to Okta's admin dashboard > application >application > choose the application that you used the id of above, and add the above URL to "Login redirect URIs" in the general tab. If that is correct make sure there is no space in the above request.
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