Service to Service Calls Using Client Credentials - powershell

I tried to create an alias for group in office 365 using below code but it shows some error.how to solve this. I tried to use service to service calls method. I got the token generated. How to check its valid or not? Is it possible to create alias using api for group without powershell option? if no kindly advice me to for other options..
string clientId = "************";
string clientsecret = "******";
string tenantId = "********";
//string resourceUri = "http://office.microsoft.com/outlook/";
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
var authUri = "https://login.windows.net/" + tenantId + "/oauth2/authorize/";
var RESOURCE_URL = "https://graph.windows.net";
HttpClient client = new HttpClient();
var authContext = new AuthenticationContext(authUri);
var credential = new ClientCredential(clientId: clientId, clientSecret: clientsecret);
var result = authContext.AcquireTokenAsync(RESOURCE_URL, credential).Result;
client.DefaultRequestHeaders.Add("Authorization", "bearer " + result.AccessToken);
string content = #"{
'displayName': 'mailgrouptest',
'groupTypes': ['Unified'],
'mailEnabled': true,
'mailNickname': 'mailalias1',
'securityEnabled': false
}";
var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json");
var response = client.PostAsync("https://graph.microsoft.com/v1.0/groups", httpContent).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
When i run this code in console it shows an error like this....is the problem with token ? or tenant id?
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {``
"request-id": "*****-***-",
"date": "2016-05-25T04:53:08"
}
}
}
kindly advice me to create alias for group in api

The mailNickName of group is not able to update using the Microsoft Graph at present.
As a workaround, we can create a new group with the specific the mailNickName you wanted and use the new group. Here is the code to create a group with mailNicekName for your reference:
string clientId = "";
string clientsecret = "";
string tenant = "yourdomain.onmicrosoft.com";
var authUri = "https://login.microsoftonline.com/"+tenant+"/oauth2/token";
var RESOURCE_URL = "https://graph.microsoft.com";
HttpClient client = new HttpClient();
var authContext = new AuthenticationContext(authUri);
var credential = new ClientCredential(clientId: clientId, clientSecret: clientsecret);
var result = authContext.AcquireTokenAsync(RESOURCE_URL, credential).Result;
client.DefaultRequestHeaders.Add("Authorization", "bearer " + result.AccessToken);
string content = #"{
'description': 'description-value',
'displayName': 'displayName-value',
'groupTypes': [
'Unified'
],
'mailEnabled': true,
'mailNickname': 'mailNickname-value',
'securityEnabled': false
}";
var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json");
//var response = client.GetAsync("https://graph.microsoft.com/v1.0/groups").Result;
var response = client.PostAsync("https://graph.microsoft.com/v1.0/groups",httpContent).Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
More detail about Goupr REST API, please refer to here.
For the error “InvalidAuthenticationToken” you were request the access token with incorrect resource. To use the Microsoft Graph API, we need to specify the resource with “https://graph.microsoft.com” instead of “https://graph.windows.net”.
In addition, if you want the mailNickName of group is updateable, you can try to submit the feedback from here.

Related

Flutter qraphQl issue with setting requesting data from body of api

I am trying to connect to an graphQl api that uses the token as the password in the Basic auth section of the header. I have tried using flutter_graphql but as I only get the token back after the user logs in. I have managed to get logged in using:
String username = "";
String password = token;
String basicAuth = 'Basic' + base64Encode(utf8.encode("$username:$password"));
String projects = "query Projects{Projects{id name}}";
Uri newUri = Uri.parse("$link");
var newResponse = await http.post(newUri, headers: {
"Authorization": basicAuth,
"Content-Type": "application/graphql"
}, body: //I need to get projects here.
);
var newNonJsonData = newResponse.body;
group("Testing the graph ql data after logging in: ", () {
test("Logged in", () {
expect(newResponse.statusCode, 200);
});
test("getting the data from the api", () {
print("non json return:" + newNonJsonData);
});
});
I have tried to set the body as
jsonEncode({
'query' : prjects
})
but the moment I request the data it asks to log in.
Please could someone help!!!

Getting 403 forbidden error while accessing linkedIn 2.0 API from SharePoint 2013 web part

API: https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)
App Permission: r_basicprofile, r_emailaddress, w_share
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string requesturl = "https://api.linkedin.com/v2/me?projection=(id,firstName,lastName)";
HttpWebRequest webRequest = System.Net.WebRequest.Create(requesturl) as HttpWebRequest;
webRequest.Method = "GET";
webRequest.Host = "api.linkedin.com";
//webRequest.ContentType = "application/x-www-form-urlencoded";
//webRequest.Connection = "Keep-Alive";
webRequest.Headers.Add("Authorization", "Bearer " + accessToken);
//Stream dataStream = webRequest.GetRequestStream();
//String postData = String.Empty;
//byte[] postArray = Encoding.ASCII.GetBytes(postData);
//dataStream.Write(postArray, 0, postArray.Length);
//dataStream.Close();
WebResponse response = webRequest.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader responseReader = new StreamReader(dataStream);
String returnVal = responseReader.ReadToEnd().ToString();
If you are using V2 API and you did not taken permission to use r_basicprofile then either apply for permission to use r_basicprofile to linkedin
OR use r_liteprofile + r_emailaddress for V2
(also check r_liteprofile permission is there in your app or not )
r_liteprofile for firstName,lastName,profilePicture,id
r_emailaddress for getting emailAddress
Check this : https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/migration-faq?context=linkedin/consumer/context

How to use the Gmail API, OAuth2 for Apps Script, and Domain-Wide Delegation to set email signatures for users' alias in a G Suite domain

This is a continuation of this question: How to use the Gmail API, OAuth2 for Apps Script, and Domain-Wide Delegation to set email signatures for users in a G Suite domain
It showed a way to set a signature for another account, using Oauth2, Apps Script, and domain wide delegation.
However, it was not working for me when I have this scenario: I have a domain alias in our G-Suite account where myuser#aliasdomain.com is an alias for myuser#maindomain.com. I want to set a signature for myuser#aliasdomain.com. The example from the prior question only did myuser#maindomain.com.
Is it possible?
I tried this (modified from prior question's example code):
var credentials = {
"type": "service_account",
"project_id": "project-id-4606494xxxxxxxxx3",
"private_key_id": "8481966716a20fe34615daxxxxxxxxa",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXbOAiODt\n-----END PRIVATE KEY-----\n",
"client_email": "xxxxxxxxxxxx#project-id-46064949xxxxxxxxxxxx.iam.gserviceaccount.com",
"client_id": "112076306220190xxxxxxxxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxxxxxxx%40project-id-4606494951xxxxxxxxxxxxxx.iam.gserviceaccount.com"
}
function setSignatureTest() {
var loginEmail = 'myuser#maindomain.com';
var sendAsEmail = 'myuser#aliasdomain.com';
var signature = 'test for awesome signature';
var test = setSignature(loginEmail, sendAsEmail, signature);
Logger.log('test result: ' + test);
}
function setSignature(loginEmail, sendAsEmail, signature) {
Logger.log('starting setSignature');
var signatureSetSuccessfully = false;
var service = getDomainWideDelegationService('Gmail: ', 'https://www.googleapis.com/auth/gmail.settings.basic', loginEmail);
if (!service.hasAccess()) {
Logger.log('failed to authenticate as user ' + loginEmail);
Logger.log(service.getLastError());
signatureSetSuccessfully = service.getLastError();
return signatureSetSuccessfully;
} else Logger.log('successfully authenticated as user ' + loginEmail);
var resource = { signature: signature };
var requestBody = {};
requestBody.headers = {'Authorization': 'Bearer ' + service.getAccessToken()};
requestBody.contentType = "application/json";
requestBody.method = "PUT";
requestBody.payload = JSON.stringify(resource);
requestBody.muteHttpExceptions = false;
var loginEmailForUrl = encodeURIComponent(loginEmail);
var sendAsEmailForUrl = encodeURIComponent(sendAsEmail);
var url = 'https://www.googleapis.com/gmail/v1/users/' + loginEmailForUrl + '/settings/sendAs/' + sendAsEmailForUrl;
var maxSetSignatureAttempts = 10;
var currentSetSignatureAttempts = 0;
do {
try {
currentSetSignatureAttempts++;
Logger.log('currentSetSignatureAttempts: ' + currentSetSignatureAttempts);
var setSignatureResponse = UrlFetchApp.fetch(url, requestBody);
Logger.log('setSignatureResponse on successful attempt:' + setSignatureResponse);
signatureSetSuccessfully = true;
break;
} catch(e) {
Logger.log('set signature failed attempt, waiting 3 seconds and re-trying');
Utilities.sleep(3000);
}
if (currentSetSignatureAttempts >= maxSetSignatureAttempts) {
Logger.log('exceeded ' + maxSetSignatureAttempts + ' set signature attempts, deleting user and ending script');
throw new Error('Something went wrong when setting their email signature.');
}
} while (!signatureSetSuccessfully);
return signatureSetSuccessfully;
}
function getDomainWideDelegationService(serviceName, scope, email) {
Logger.log('starting getDomainWideDelegationService for email: ' + email);
return OAuth2.createService(serviceName + email)
// Set the endpoint URL.
.setTokenUrl(credentials.token_uri)
// Set the private key and issuer.
.setPrivateKey(credentials.private_key)
.setIssuer(credentials.client_email)
// Set the name of the user to impersonate. This will only work for
// Google Apps for Work/EDU accounts whose admin has setup domain-wide
// delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
.setSubject(email)
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getScriptProperties())
// Set the scope. This must match one of the scopes configured during the
// setup of domain-wide delegation.
.setScope(scope);
}
It works as I have loginEmail and sendAsEmail set to the loginEmail, but not when set to the one for the domain alias.
I'd appreciate any ideas/help.
Thanks.

How to get Twitter User Email using Xamarin.Auth library

I m trying to implement twitter authentication for my xamarin app. I checked Request email addresses from users option on developer console but i am not able to get email in user information. Am i doing something wrong
var Twitterauth = new OAuth1Authenticator(
consumerKey: "XXXX",
consumerSecret: "XXX",
requestTokenUrl:new Uri("https://api.twitter.com/oauth/request_token"),
authorizeUrl: new Uri("https://api.twitter.com/oauth/authorize"),
accessTokenUrl: new Uri("https://api.twitter.com/oauth/access_token"),
callbackUrl: new Uri("http://www.isportfoy.com.tr/tr/anasayfa")
);
Twitterauth.Completed += (s, ee) =>
{
if (ee.IsAuthenticated)
{
var request = new OAuth1Request(
"GET",
new Uri("https://api.twitter.com/1.1/account/verify_credentials.json"),
null,
ee.Account);
request.GetResponseAsync().ContinueWith(t =>
{
var res = t.Result;
var resString = res.GetResponseText();
Console.WriteLine("Result Text: " + resString);
});
}
else
{
}
};
Twitter API requires us to indicate if we want to the user email in the response.
Based on the Twitter Documentation this can be done sending the include_email as true.
Full documentation: https://dev.twitter.com/rest/reference/get/account/verify_credentials
if (e.IsAuthenticated)
{
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("include_email","true");
var request = new OAuth1Request(
"GET",
new Uri("https://api.twitter.com/1.1/account/verify_credentials.json"),
param,
e.Account);
}

Issue using Insights Edge API

I am trying to get some insights data using Insights Edge API, but running into permissions issue:
Here is the code I am using:
string applicationId = "";
string applicationSecret = "";
string accountId = "";
System.Net.WebClient client = new System.Net.WebClient();
string accessToken = client.DownloadString("https://graph.facebook.com/oauth/access_token?client_id=" + applicationId + "&client_secret=" + applicationSecret + "&grant_type=client_credentials").Replace("access_token=","");
System.Net.WebRequest req = System.Net.WebRequest.Create("https://graph.facebook.com/v2.4/act_"+accountId+"/insights?access_token=" + accessToken);
System.Net.WebResponse response = req.GetResponse();
using(System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
{
string s = sr.ReadToEnd();
Console.WriteLine(s);
}
I am getting the following JSON back:
{
"error": {
"message": "(#10) You do not have sufficient permissions to perform this action",
"type": "OAuthException",
"code": 10
}
}
Application in question was created under the same Facebook account as the ad account. What do I need to check in account/application settings to see if I have all the correct permissions to access Ad Insights API? The code will need to run in the service that doesn't require user intervention, is application access token the right way to access ad insight data in this case?