How do i use the Kenitco API from a Console App - kentico

I'm using Kentico V10 and I can run the website locally. However, when i try to use the API from a console app, i'm getting the following error.
{"Object type 'cms.class' not found."}
The stackTrace has a call to check license. I'm following this page, and it says you have to add a license for your domain, but what domain is used when you are running from a console app?
https://docs.kentico.com/k10/integrating-3rd-party-systems/using-the-kentico-api-externally
I'm using this code from taken from this page.
https://docs.kentico.com/k10/managing-users/user-registration-and-authentication/configuring-single-sign-on
CMS.DataEngine.CMSApplication.Init();
string userName = "myuser";
// Gets the user with the specified user name
UserInfo userInfo = UserInfoProvider.GetUserInfo(userName);
// Gets the authentication URL for a specified user and target URL
string url = AuthenticationHelper.GetUserAuthenticationUrl(userInfo, "SecuredSurvey");
If that was available via the REST API, i'd be happy to get the URL that way, but from what i can see, it's not available.
-Randy

Kentico has some good documentation on how to use the API in an external application, specifically a console library here.
Very notable steps are:
Connecting to the database; make sure you use the same connection string as in your web.config
Install the Kentico.Libraries NuGet package
Initialize Kentico in your application in the Global.asax file.
Write custom code all day long.

Related

Automating SharePoint scripts/code with LegacyAuthProtocolsEnabled set to false

We use the Microsoft.SharePoint.Client library to automate SharePoint work from our workflow engine but yesterday, one of our client informed us they wanted to disable the Legacy Authentication (LegacyAuthProtocolsEnabled to false).
Once I tried it on our end, I ended up getting an Unauthorised exception.
All in good wanting to disable the Legacy Authentication for obvious security reason, but the problem with the Modern Authentication is that it requires user interaction which is clearly not a solution since we are running tasks in the background.
I've been googling this for quite some time but I haven't found a solution as of yet on how to handle automatic authentication for background work.
Is there a way to "authenticate" to SharePoint without any user interaction while LegacyAuthProtocolsEnabled is set to false?
I found an article that suggested using the App Authentication but after reading more about it, I believe this is considered an old method to authenticate and is likely to be deprecated as well over time, but I thought I'd still give it a go just in case but it did not work. When I got to
https://tenant.sharepoint.com/_layouts/15/appregnew.aspx
Where tenant is our company domain name, and I click on the "Create" button after filling in all the relevant fields, I get the following error, which is completely useless:
Sorry, something went wrong
An unexpected error has occurred.
TECHNICAL DETAILS
According to this article HOW TO HARDEN YOUR SHAREPOINT ONLINE ENVIRONMENT BY DISABLING LEGACY AUTHENTICATION, Legacy Authentication was no longer be an option as of the 13/10/2020, yet here we are, and the option is still available in SharePoint 365 and while the article is interesting explain why Legacy Authentication should be switched off, etc... it does not get into any details as to how automated solutions should be handled.
Also found an old thread "LegacyAuthProtocolsEnabled" and Scripted Logons to SharePoint Online? where #DeanWang suggests leaving it turned on as:
All custom CSOM, PowerShell code will stop working
This may also prevent third-party apps from accessing SharePoint
Online resources.
I'm going to stop here as I could keep going and the question is already too long for my liking and bottom line is, does anyone know if there is a way, and what is the best way, to authenticate to SharePoint while running automated "scripts/code" from a background task without requiring any user interaction while the Legacy Authentication is switch off?
Thanks
Update-1
After reading articles after articles, I've yet to connect to SharePoint 365.
I also spend more time on the PnP Framework as recommended by numerous articles. I created a dummy app with the following sample code which is used again in various articles, including this one:
Secure Authentication of SharePoint with PnP Framework with C#(Code)
My code is identical as you can see:
var clientContext = new AuthenticationManager().GetACSAppOnlyContext(
"https://mycompany.sharepoint.com/sites",
"MyClientid",
"MySecretId");
using (clientContext)
{
//Get Lists
var web = clientContext.Web;
var lists = web.Lists;
clientContext.Load(lists);
clientContext.ExecuteQuery();
foreach (var list in lists)
{
}
}
And even though I've granted full control in Azure for the specific test app that's using the specific ClientId and SecretId
I'm still getting the following error (401 - unauthorized):
System.Exception
HResult=0x80131500
Message=Token request failed.
Source=PnP.Framework
StackTrace:
at SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2S2SClient.Issue(String securityTokenServiceUrl, OAuth2AccessTokenRequest oauth2Request) in /_/src/lib/PnP.Framework/Utilities/OAuth/OAuth2S2SClient.cs:line 18
at PnP.Framework.Utilities.TokenHelper.GetAppOnlyAccessToken(String targetPrincipalName, String targetHost, String targetRealm) in /_/src/lib/PnP.Framework/Utilities/TokenHelper.cs:line 116
at PnP.Framework.Utilities.ACSTokenGenerator.GetToken(Uri siteUrl) in /_/src/lib/PnP.Framework/Utilities/ACSTokenGenerator.cs:line 37
at PnP.Framework.AuthenticationManager.<GetContextAsync>b__59_0(String site) in /_/src/lib/PnP.Framework/AuthenticationManager.cs:line 971
at PnP.Framework.AuthenticationManager.<>c__DisplayClass75_0.<GetAccessTokenContext>b__0(Object sender, WebRequestEventArgs args) in /_/src/lib/PnP.Framework/AuthenticationManager.cs:line 1336
at Microsoft.SharePoint.Client.ClientRuntimeContext.OnExecutingWebRequest(WebRequestEventArgs args)
at Microsoft.SharePoint.Client.ClientContext.FireExecutingWebRequestEventInternal(WebRequestEventArgs args)
at Microsoft.SharePoint.Client.ClientContext.GetWebRequestExecutor()
at Microsoft.SharePoint.Client.ClientContext.GetFormDigestInfoPrivate()
at Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()
at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
at ConsoleApp5.Program.Main(String[] args) in C:\Users\myuser\source\repos\ConsoleApp5\ConsoleApp5\Program.cs:line 23
This exception was originally thrown at this call stack:
[External Code]
SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2WebRequest.GetResponse() in OAuth2WebRequest.cs
SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2S2SClient.Issue(string, SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2AccessTokenRequest) in OAuth2S2SClient.cs
Inner Exception 1:
WebException: The remote server returned an error: (401) Unauthorized.
Is there another section I should be looking at (and change) in the App Registration in Azure
Since it's the SharePoint Online that we are talking about, one easy way to connect to different SharePoint Sites is by using the Azure AD App-Only approach and since you are talking about a Deamon Service you can easily use Application Permissions when registering the App Registration.
You can, and you should, read more about it from the linked Microsoft Docs article.
You can also loggin via certificate or app registration secret as it is discribed in the Log in to Microsoft 365 in order to create automated CI CD SPFx pipelines, for example.
Hope the above helps, if not feel free to ask :)
Update: Please read below in order to have a better understanding.
Firstly, in your code segment you are using a wrong method from the PnP.Framework package.
AuthenticationManager().GetACSAppOnlyContext()
The above method refers to a completely different method of obtaining an authentication token, more specifically the Sharepoint App-Only model, which... well.... more or less is not being used nowadays quite so ofte. I think I read somewhere that MS is thinking of retiring this kind of Authentication and going onwards on the path of Azure Active Directory authentication, but, unfotunately, I cannot seem to find the link.
Furthermore, I have collected three projects and uploaded them to github for you to see. You can simply clone the repo and run the projects as-is from HERE.
As you will be able to see for yourself, there are three projects in the solution, which you can run each one individually from VSCode or Vs.
More in detail:
ConsoleApp1
(sorry for the name but forgot to switch it :) )
This is a Deamon Console Project that references the PnP.Framework namespace and tries to utilize all of the goodies that the good folks form the PnP Community have contributed.
The procedure is straight forward and is the same for all three projects ->
Read the AppConfiguration
Request the Access Token with appropriate scopes (Depending the service that i am referencing)
Declare the Token to be used by our Client Context.
In the PnP.Framework-related project the above cycle can be seen as below
AuthenticationConfiguration config = AuthenticationConfiguration.ReadFromJsonFile("appsettings.json");
var authManager = new PnP.Framework.AuthenticationManager(config.ClientId, config.Certificate.CertificateDiskPath, config.Certificate.CertificatePassword, config.Tenant);
using (var cc = authManager.GetAccessTokenContext("https://<REPLACE:name of tenant>.sharepoint.com/sites/testsite2", (string siteURL) => authManager.GetAccessToken(siteURL)))
ConsoleAppMSGraph
As the name suggests this Deamon Console App utilizes GraphServiceClient graphClient in order to get all the information that you request through the graph endpoint.
Subsequntly, you will notice that for this porject the scope name changes to
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
In addition, we request a collection of all the lists that currently reside in our SharePoint Root Site with the below segment:
var lists = await graphClient.Sites["root"].Lists
.Request()
.GetAsync();
ConsoleAppSPClient
This app is the default and most simple way of accessing data on Sharepoint.
The projects utilizes MSAL.Net and Microsoft.Sharepoint.Client namespaces in order to fetch an access token and, subsequently, embed that token in all our next requests.
In order to keep the answer a bit short, please refer to here in order to see how we initiate a Confidential App Client, request for a token and, later on, embedd it in our ClientContext object.
Notes
I have listed in the Readme.md of the repo, which permissions you should give to your app registration. You can view them Here.
I am using the Sites.FullControl.All but you can narrow down the list of sites that the app registration will have access by using the Sites.Selected.
All of the above projects, reference a common class library that serves as a strongly typed configuration object.
IMPORTANT you should always use a certificate to authenticate the client app as it is mentioned here. The previous link also describes the way you can create a certificate and upload it to the store of the app registration.
Amazing! Thank you very much #Jimas13. For the last 2 weeks I was struggling to find solution to my problem!! You saved me!! If you ever been in Greece let me buy you a drink!

How can I force Firebase Realtime Database URL without "default-rtdb"

My realtime database URL is like https://myprojectid.firebaseio.com
When I start my node.js server I have error message :
#firebase/database: FIREBASE WARNING: Firebase error. Please ensure
that you have the URL of your Firebase Realtime Database instance
configured correctly.
(https://myprojectid-default-rtdb.firebaseio.com/)
My Firebase config is :
# Firebase
apiKey=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx
authDomain=myprojectid.firebaseapp.com
databaseURL=https://myprojectid.firebaseio.com
projectId=myprojectid
storageBucket=myprojectid.appspot.com
messagingSenderId=00000000000000
appId=1:0000000000000:web:000000000000000
When I'm trying to debug npm library, I can see that namespace is indeed "myprojectid-default-rtdb" but can't find where to change it.
I tried to set databaseURL with query string ?ns=myprojectid but not better.
By searching on Google I could read :
For recently created Firebase projects the default database URI
usually has the format https://
-default-rtdb.firebaseio.com. Databases in projects
created before September 2020 had the default database URI
https://.firebaseio.com. For backward compatibility
reasons, if you don’t specify a database URI, the SDK will use the
project ID defined in the Service Account JSON file to automatically
generate it
Could you help me to find a solution please?
There's no way to change the name of the default database instance that is created in your Firebase project. If your project is on the paid plan, you can add additional database instances where you fully control the name, but not for the default one.
You will have to update your project configuration to use the correct database URL. If the database in the US data center, that'd be:
databaseURL=https://myprojectid-default-rtdb.firebaseio.com

BIM360 Issues editor Forge Node JS App -trying to run on localhost 3000

I am trying to work with the BIM 360 Issue Editor created by Petr and available on github https://github.com/petrbroz/bim360-issue-editor/tree/develop
I have added all the dependencies,etc. but seem to be stuck with the configuration.
I am testing on local host and I am getting invalid URI error, what would be the correct configuration variables for launch.json file for
"HOST_URL": "http://localhost:3000","SERVER_SESSION_SECRET","CLI_CONFIG_PASSWORD"
Also there is SENDGRID_API_KEY required, which throws an error on the console, I add the key from SendGrid in config.js, and the error goes away. Is it correct?
Please suggest. Thanks
Here's more details about the env. variables:
HOST_URL is just the host/port the app is listening on (for example, http://localhost:3000)
This value is used to built the callback URL for the 3-legged OAuth workflow; for example, if the host URL is http://localhost:3000, the callback URL will be http://localhost:3000/auth/callback
Note that the same callback URL must be configured for your Forge app on https://forge.autodesk.com/myapps
SERVER_SESSION_SECRET is an arbitrary string that will be used to encrypt/decrypt browser cookies
CLI_CONFIG_PASSWORD is only needed when you want to use the command-line utility that's part of the sample code; in that case the configuration for the CLI utility will be zipped in a password-protected *.zip file using this env. variable as the password
SENDGRID_API_KEY is also optional and only needed if you want the app to send email notifications to users who triggered the Excel export

Azure Web App - Cannot GET (particular path)

I have been trying out the AADv2 sample from BotAuth to no avail.
The error that I keep getting after I select the button on the action card is that either a HTTP 500 internal server error, or Cannot GET /botauth/aadv2. When I check if the root web page or the messaging endpoint is working or not, I get the same error - either Cannot GET / or Cannot GET \api\messages. The root page I have been trying to get to is https://(botname).azurewebsites.net
May I know what steps I can take to resolve this issue? I have tried to Google the error, but to no avail. Please let me know if you need more information!
Since you are test the sample directly on Azure Web Apps, there should be a few of questions we should pay attention on.
1, const MICROSOFT_APP_ID = envx("MICROSOFT_APP_ID");
const MICROSOFT_APP_PASSWORD = envx("MICROSOFT_APP_PASSWORD");
we declare the environment valiable as MicrosoftAppId and MicrosoftAppPassword. Please modify this sentence as
//bot application identity
const MICROSOFT_APP_ID = envx("MicrosoftAppId");
const MICROSOFT_APP_PASSWORD = envx("MicrosoftAppPassword");
2, And you also need to check the environment variables are set correctly in Application settings of Azure Web App, which is shown at https://github.com/MicrosoftDX/botauth/tree/master/Node/examples/aadv2#3-setup-environment-variables
3, You can leverage online code editor to develop, debug, and manage your project on Azure Web Apps.
And in the output column, you can see the detailed errors throwm by the application. You can leverage these info to narrow down your issue.
Tips, after you changing the application settings, it's better to restart your Azure Web App.

Just created Azure Mobile App service calls return http 400 error

Here's what I'm doing.
Install latest Azure SDK (by the date)
Open Visual Studio 2013
Create a new Azure Mobile App project. The simple service is created with TodoItem DataObject and 2 simple controllers - TodoItemController and ValuesController
Do not change anything
Start the project
The service is started and hosted in local IISExpress on url http://localhost:50993/ (the port may vary).
The "This mobile app is up and running" web page is opened in the browser. But http 400 error is returned when I try to invoke some GET-actions: for example http://localhost:50993/api/values or http://localhost:50993/tables/TodoItem.
Any ideas? Is something wrong in my environment or is that me doing something wrong?
Thanks.
I guess you can opt out of version checking by setting a value of true for the app setting MS_SkipVersionCheck. Specify this either in your web.config or in the Application Settings section of the Azure Portal.
This generally happens when you don't add a ZUMO-API-VERSION header to the request. This is required when making requests from a REST client, but the mobile client SDKs add the header automatically.
To fix, add the header ZUMO-API-VERSION with value of 2.0.0.
To learn more, see https://azure.microsoft.com/en-us/documentation/articles/app-service-mobile-client-and-server-versioning/.
Adding
http://localhost:50993/tables/Location?ZUMO-API-VERSION=2.0.0
at the end will do the trick.

Resources