Microsoft C++ Rest SDK for Graph APIs - c++

I am trying out Microsoft's C++ Rest SDK (https://microsoft.github.io/cpprestsdk/index.html) to invoke Graph APIs but it has been a struggle so far.
In C# I can complete my tasks in a few lines of code. For example, refer following code from a Microsoft tutorial:
AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");
bool isUsingClientSecret = AppUsesClientSecret(config);
IConfidentialClientApplication app;
if (isUsingClientSecret)
{
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientSecret(config.ClientSecret)
.WithAuthority(new Uri(config.Authority))
.Build();
}
string[] scopes = new string[] { $"{config.ApiUrl}.default" };
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
}
catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
{
}
// config.ApiUrl is set to "graph.microft.com"
if (result != null)
{
var httpClient = new HttpClient();
var apiCaller = new ProtectedApiCallHelper(httpClient);
await apiCaller.CallWebApiAndProcessResultASync($"{config.ApiUrl}v1.0/users", result.AccessToken, Display);
}
Now for cross-platform support, I need to develop similar functionality in C++ and for this purpose, we are exploring C++ Rest SDK from Microsoft. But I am unable to find any good examples to achieve a simple thing like providing client ID, client secret to get access token and to authorize.
Please let me know if anyone has come across any example / link to achieve the same.

Here you have some code for oauth 2.0 in Dropbox, Linkedin and MS Live scope:
https://github.com/microsoft/cpprestsdk/blob/master/Release/samples/Oauth2Client/Oauth2Client.cpp
Other samples within C++ Rest SDK:
https://github.com/microsoft/cpprestsdk/tree/master/Release/samples
First of all, you have to distinguish:
1. MS Graph authentication - which is, in fact, Azure Access Directory/Microsoft identity platform authentication, based on oauth 2.0 (short name: MSAL)
2. Accessing the MS Graph API using access token from the authentication process (in the standard process you should use MS Graph SDK)
For the C++ there is no MSAL or SDK library.
So - for authentication, you should use oauth 2.0 example which I pasted above.
Because you need to write everything on your own, please read deeply docs about authentication for MS Graph
https://learn.microsoft.com/en-us/graph/auth/
Here you can watch all the needed endpoints, secrets etc. for sample Postman calls:
https://learn.microsoft.com/en-us/graph/use-postman#set-up-on-behalf-of-api-calls
https://developer.microsoft.com/en-us/graph/blogs/30daysmsgraph-day-13-postman-to-make-microsoft-graph-calls/
In the URLs there are the following variables used:
Callback URL: https://app.getpostman.com/oauth2/callback
Auth URL: https://login.microsoftonline.com/**TENANTID**/oauth2/v2.0/authorize
Access Token URL: https://login.microsoftonline.com/**TENANTID**/oauth2/v2.0/token
Client ID: CLIENTID
Client Secret: CLIENTSECRET
Scope: https://graph.microsoft.com/.default
State: RANDOMSTRING
For the API calls, read about Microsoft Graph REST API v1.0 reference
https://learn.microsoft.com/en-us/graph/api/overview?toc=./ref/toc.json&view=graph-rest-1.0

Related

how to get Google groups contents by using directory API or Cloud Identity API

Can anyone please suggest to me how to get the content of google groups by using 2 different API
Cloud identity API
google directory API
We need to get the google group content.
Well, both APIs can interact with Google groups, however, there are subtle differences between them than you can check here.
I would strongly recommend using the Directory API as it has better documentation and as the Cloud Identity API requires either a Cloud Identity Free or a Cloud Identity Premium account. But of course, either of them can be used.
Directory API
For Directory API I would recommend taking a look at the Quickstart, as everything regarding the API's setup in your favorite programming language is explained there.
The documentation on how to deal with groups is here.
Of course, Apps Script is the most straightforward tool to fetch that information, as it can be achieved in a few lines (and adding the AdminDirectory service):
function myFunction() {
var groupList = AdminDirectory.Groups.list({customer:"my_customer"})["groups"];
for (var i = 0; i < groupList.length; i++){
console.log(groupList[i].name+": " + groupList[i].description);
}
}
Cloud Identity API
Regarding Cloud Identity API, you will need to follow this setup.
Then, the documentation regarding groups can be found here.
As an example, here is how it could be done in Apps Script:
function myFunction() {
var customerId = AdminDirectory.Users.get(Session.getEffectiveUser().getEmail()).customerId;
var url = "https://cloudidentity.googleapis.com/v1beta1/groups?parent=customers/"+customerId;
var params = {
method: "get",
headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
};
var groups = JSON.parse(UrlFetchApp.fetch(url,params).getContentText()).groups;
for(var i = 0; i< groups.length;i++){
console.log(groups[i].displayName);
}
}
For that you would also need to append the following line in the appscript.json manifest file. You can open it by going to Project Settings -> Show "appsscript.json" manifest file in editor:
"oauthScopes": ["https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/cloud-identity.groups"]

Using generated on the server AccessToken to connect to GCP Text to Speech

I would like to be able to connect to GCP Text to Speech from a react.js front-end using an access token generated on the server. I adapted the code from the linked reply to produce an access token. However, I was not able to find in the docs how to use that token to connect from the front-end to GCP.
For simplicity, I would like to begin with modifying the linked working node.js example from the docs to use the hardcoded access token instead of the Default Credentials File to connect with the service.
Here is my attempt (compared to the example, only the construction of client is modified):
'use strict';
function main() {
// [START tts_quickstart]
// Imports the Google Cloud client library
const textToSpeech = require('#google-cloud/text-to-speech');
// Import other required libraries
const fs = require('fs');
const util = require('util');
// Creates a client
const client = new textToSpeech({tk: 'ya29.c.Kp8BCQj<etc.>'}).TextToSpeechClient();
async function quickStart() {
// The text to synthesize
const text = 'hello, world!';
// Construct the request
const request = {
input: {text: text},
// Select the language and SSML voice gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
// Performs the text-to-speech request
const [response] = await client.synthesizeSpeech(request);
// Write the binary audio content to a local file
const writeFile = util.promisify(fs.writeFile);
await writeFile('output.mp3', response.audioContent, 'binary');
console.log('Audio content written to file: output.mp3');
}
quickStart();
// [END tts_quickstart]
}
main(...process.argv.slice(2));
I get an error that textToSpeech is not a constructor. How can I fix this example to connect to GCP Text to Speech using the access token?
Unfortunately it is not possible to authenticate via access token using the Text-To-Speech Nodejs Client Library. The TextToSpeechClient in Node runtime only accepts credentials objects which can be found from service accounts.
Based from the SO example you included in your question, it generates the access token and uses it in Android. It makes sense since there are no client libraries for Android as of now, so the OP is using the Text-To-Speech REST API to create an HTTP request. Using HTTP request requires the access token to authenticate, thus the solution of the SO example.
My suggestions are the following:
Adapt the solution similar to the SO example which is sending request via HTTP so you can use access token for authentication.
Use a different programming language like Python (seems unlikely since you are using React). It is possible in Python Client Library to use access token for authentication since it accepts credentials object.
Also just to add you are passing parameters incorrectly on your client object. It should be const client = new textToSpeech.TextToSpeechClient(object);

Generate API client from Django REST framework API

I have an website in Django that is using the REST framework to provide an API.
Is there a way to generate an API client that can be used to communicate with this API that provides objects mapping the contents of the API?
If you're talking about a javascript client API, I have a django management task that I use to generate a javascript library from my DRF API
using AngularJS 1.*. I'm still using DRF 2.4, for easy nested object writes, and Django 1.7. Here it is as a github gist
Take that file, stick it in <app>/management/commands/ and call it like:
python manage.py rest_framework_2_js rest_api.gen.js [base_factory_name] [server_base_url]
If your base_factory_name was foo and you had an API object at server_base_url/Bar/ named Bar, you would use it like:
foo.Bar.get(42)
.then(function(bar_inst) {
console.log(bar_inst);
bar_inst.baz = 77;
bar_inst.save()
.then(function() {
console.log('bar_inst has been saved');
});
})
or
foo.BarList.get('filter_a=5&field_filter_b=abc,d')
.then(function(data) {
console.log(data.results);
})
Each instance in the data.result will be a foo.Bar instance.
You can add callbacks before sending to the server and after retrieving from the server using foo.Bar.pre_save(function (inst) {/*callback mutator*/}) and foo.Bar.post_restore( function(inst) { /*callback mutator*/}).
Anyways, this management task is not productized and it has only one user - me, but I have been using it for 2 years and it works great for me :-) We can work to get it working in your configuration if you like. Naturally the biggest caveat is the AngularJS 1.* dependency.

Single Sign On using Microsoft account and Azure Mobile Services in a C++ Windows Store app

I am trying to build Single Sign On functionality into my C++ Store app using Live SDK and Azure Mobile Services (similar to what is described for .NET apps here).
I am using Azure Mobile C++ Library and the live_connect.h wrapper. Below is what my code looks like:
void MapQuizVC12::StartPage::LoginIntoLive()
{
LiveClient->login(L"wl.basic wl.signin").then([this](bool isLoggedIn)
{
LiveClient->get(L"me").then([this](json::value v)
{
auto token = json::value::object();
token[L"authenticationToken"] = json::value::string(LiveClient->authentication_token());
AzureMobileHelper::mapquizMobileService::GetClient()
.login(azure::mobile::authentication_provider::microsoft, token)
.then([](task<azure::mobile::user> user)
{
try
{
user.wait();
}
catch (std::exception e)
{
}
}, concurrency::task_continuation_context::use_current());
}, concurrency::task_continuation_context::use_current());
}, concurrency::task_continuation_context::use_current());
}
The Live authentication seems to work fine but when I use the auth token to login to Zumo, I get the following exception in the catch block above:
After some playing around. I figured that the Live authToken being returned by the C# SDK is different from the one that is being returned by the C++ API. Azure Mobile service actually expects what is returned by the C# SDK. I have posted about this problem here.
What am I doing wrong?
The problem turned out to be with the token that Live REST API was returning in C++. It seems the correct information was not being requested through the WinRT API used to authenticate with the Live Service. Fixing that fixes this issue.
The correct code snippet has been posted on this MSDN Forums post.

Authentication using Single-sign-on

In my web service project i need to include a authentication part using single-sign-on and spring. I am new to this technology. I was searching for an sample application for past few days, but i couldn't find it. Please help me by suggesting any tutorials. It will be a great help for me
For single-sign-on, the web service method for authentication should take username and password as parameters, and this authentication method should return a MAC ('Message Authentication Code', also named alternatively 'Authentication Token').
All the subsequent calls to other web service methods should contain this MAC so that the web service methods know which user is calling them.
//example pseudo code for authentication
string web_service_auth(string User_Name,string Password) {
...
string Mac;
if (access_accepted(User_Name,Password))
Mac = ...;
else
Mac = "access-denied";
return Mac;
}
//example pseudo code for other methods
string web_service_get_my_info(string Mac) {
if (!mac_is_valid(Mac))
return "invalid-mac";
...
string User_Name = mac_to_username(Mac);
string Info = get_user_info(User_Name);
return Info;
}