I am trying to add an alternate email with Microsoft Graph API from a.Net Core app.
The user class in Microsoft Graph does not provide a property for adding an additional mail id.
You can using Azure AD Graph to add the mail id to the otherMails. Here is sample to update the this property:
PATCH: https://graph.windows.net/{tenant}/me?api-version=1.6
authorization: bearer {access_token}
{
"otherMails":["test#test.com"]
}
Refer the links below for the user entity and update user REST:
Entity and complex type reference | Graph API reference
Update User
Here is the C# code to retrieve the alternate email
Select(u => new {
u.DisplayName,
u.Mail,
u.UserPrincipalName,
u.OtherMails
})
.GetAsync();
You can get the alternate email from the "otherMails" property on a User in the Graph API Docs.
Note that this is only returned on a Select, so you need to include the query parameter "$select=otherMails" to see it.
GET https://graph.microsoft.com/v1.0/users/USER_ID?$select=otherMails
authorization: bearer {access_token}
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#users(otherMails)",
"#odata.id": "https://graph.microsoft.com/v2/YOUR_AAD_TENANT/directoryObjects/USER_ID/Microsoft.DirectoryServices.User",
"otherMails": [
"altEmail#website.com"
]
}
Related
I was looking to add members to Project using REST API.
I was able to create project using API:
POST https://{instance}/{collection}/_apis/projects?api-version=5.0
Also, I was able to create a team in a project using REST API:
POST https://{instance}/{collection}/_apis/projects/{projectId}/teams?api-version=5.0
However, I was not able to get a REST API to add members to team and project.
Can you please help?
Devops server 2019 - Is there an REST api to add members to project
and team
For this issue,I think there is no out of box rest api to achieve it . The Members - Add rest api is currently not available for Azure DevOps Server 2019.
As a workaround ,we can track this rest api by press F12 in browser then select Network.
Sample request url :
https://collectionName/DefaultCollection/projectId/_api/_identity/AddIdentities?__v=5
Sample request body:
{
"newUsersJson": "[]",
"existingUsersJson": "[\"55b98726-c6f5-48d2-976b-xxxxxx\"]",
"groupsToJoinJson": "[\"7283653f-54b2-4ebf-86c3-xxxxxxx\"]",
"aadGroupsJson": "[]"
}
In this step ,you need to convert the name of the member you want to add and the name of the team to json, then add to the request body. Here is a case states how to convert a string to JSON in C#.
From this record ,we can get the request url and request body.
I test this with postman and can successfully add a member to a project team.
Here are two cases(case1 , case2) with similar problems. You can also refer to them.
The use voice instance in the above case is no longer available. You could submit a new one to our main forum for product suggestions. Our PM and Product Group are reviewing these suggestion regularly and considering take it as plan.
The REST API to add members to projects and team is not documented. As Hugh mentioned we can track the REST API with develop tools (press F12 in browser), however as we can see we can only use the user and team/group GUID in the request json body.
Post https://wsicads2019/DefaultCollection/{project}/_api/_identity/AddIdentities?api-version=5.0
Request Body:
{
"newUsersJson": "[]",
"existingUsersJson": "[\"55b98726-c6f5-48d2-976b-xxxxxx\"]",
"groupsToJoinJson": "[\"7283653f-54b2-4ebf-86c3-xxxxxxx\"]",
"aadGroupsJson": "[]"
}
For the specific team/groups we can use the REST APIs Projects and teams to get their GUID.
For the user, actually it's used the TeamFoundationId, the unique TeamFoundationId is automatically generated when a user is added to Azure DevOps Server. We cannot generate the ID with external tools.
So, to use that REST API, we need to get the TeamFoundationId of the specific user which you want to add it to the projects/teams.
Currently, no REST API to list TeamFoundationId of the users in Azure DevOps Server 2019, however we can get it with Client API:
Below sample for your reference to get the TeamFoundationId of a specific user: (It will also export the user list with their TeamFoundationId to userlist.txt)
using System;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using System.Linq;
using System.IO;
namespace Getuserlist
{
class Program
{
static void Main(string[] args)
{
TfsConfigurationServer tcs = new TfsConfigurationServer(new Uri("https://wsicads2019"));
IIdentityManagementService ims = tcs.GetService<IIdentityManagementService>();
TeamFoundationIdentity tfi = ims.ReadIdentity(IdentitySearchFactor.AccountName, "[DefaultCollection]\\Project Collection Valid Users", MembershipQuery.Expanded, ReadIdentityOptions.None);
TeamFoundationIdentity[] ids = ims.ReadIdentities(tfi.Members, MembershipQuery.None, ReadIdentityOptions.None);
using (StreamWriter file = new StreamWriter("userlist.txt"))
foreach (TeamFoundationIdentity id in ids)
{
if (id.Descriptor.IdentityType == "System.Security.Principal.WindowsIdentity" && id.UniqueName == "Domain\\User")
{ Console.WriteLine("[{0},{1}]", id.UniqueName, id.TeamFoundationId); }
file.WriteLine("[{0},{1}]", id.UniqueName, id.TeamFoundationId);
}
var count = ids.Count(x => ids.Contains(x));
Console.WriteLine(count);
Console.ReadLine();
}
}
}
I am trying to send over a Post request to sendgrid to generate an API key for a subuser.
This is what my code currently looks like
body = JSON.parse('{
"name":"My API Key",
"scopes": [
"mail.send",
"alerts.create",
"alerts.read"
]
}')
header = {'On-Behalf-Of' => 'my#email.com'}
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.api_keys.post(request_body: body, request_header: header)
This code generates the API but on the main account instead of the Subuser account. The header is what drives where the API key is generated and I can seem to find any sources online that how the correct syntax for sending over the header to sendgrid.
If you could please help I would really appreciate it. Thanks!
I recently had to do this. You need to set the On-Behalf-Of headers when you instantiate the client not when you make the request:
```
#send_grid = API.new(api_key: #api_key, request_headers: {
'On-Behalf-Of' => #username
})
```
Then when you make a request with #send_grid it will send on behalf of the subuser -- and the API key will not show up in the list of api keys on the parent account
If I understand correct, you want to send email "From" another user. On Behalf of is non standard way of doing things.
For eg. https://sendgrid.com/docs/Classroom/Troubleshooting/Authentication/my_emails_are_displaying_as_on_behalf_of_or_via_in_some_mail_clients.html
You may want to try setting from instead of on-behalf-of
"from": {
"email": "from_address#example.com"
},
Refer to: https://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/index.html
I make the following REST GET request:
https://graph.microsoft.com/v1.0/me/onenote/notebooks
I get the following response:
{
"error": {
"code": "30108",
"message": "The OneDriveForBusiness for this user account cannot be retrieved.",
"innerError": {
"request-id": "25926552-3157-483a-bbcd-41a7105cd531",
"date": "2017-07-22T18:46:07"
}
}
}
I do not have a One Drive For Business account. Do I really need one to access the OneNote API?
Thanks.
Yes. In order to use the API (to access OneNote data), you must have a OneDrive (whether personal/consumer or business/Office 365) - since the OneNote cloud data is actually stored in OneDrive/SharePoint. If you have an Office 365 account, you can try going to https://portal.office.com and then click in the left-hand "waffle" button, and click OneDrive which should create your own personal OneDrive for Business.
Please take a look at https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/onenote for more details.
Also, if you are just trying out the API you could use Graph Explorer. It has some saved/sample queries that you can try. (Under Sample Queries, click show more samples and toggle the OneNote switch).
Hope this helps,
Here how I solved it in my Azure function by switching to authentication with Microsoft account and using the classic OneNote Rest API.
var request = require('request');
module.exports = function (context, req) {
var microsoftAccountAccessToken = req.headers['x-ms-token-microsoftaccount-access-token'];
context.log( "Microsoft Account Access Token: " + microsoftAccountAccessToken );
request(
{
url: 'https://www.onenote.com/api/v1.0/me/notes/notebooks',
method: "GET",
headers: {
'Authorization': 'Bearer ' + microsoftAccountAccessToken
},
},
function( error, response, body )
{
if (!error && response.statusCode === 200) {
context.log(body);
context.res = {
body: body
};
context.done();
}
else {
context.log("error: " + error)
context.log("response.statusCode: " + response.statusCode)
context.log("response.statusText: " + response.statusText)
context.res = {
body: response.statusText
};
context.done();
}
}
);
};
https://learn.microsoft.com/en-us/graph/onenote-error-codes#30108
The user's personal OneDrive for Business could not be retrieved. The following table lists some possible causes.
The user's personal site has not been provisioned. The user should open OneDrive for Business and follow any instructions to provision the site. If this fails, they should contact their Office 365 tenant administrator.
The user's personal site is currently being provisioned. Try the request later.
The user does not have a valid OneDrive for Business license. The user should contact their Office 365 tenant administrator.
A network issue prevented the request from being successfully sent.
I tried many ways and finally I used the method mentioned here: https://learn.microsoft.com/en-us/previous-versions/office/office-365-api/how-to/onenote-auth
The auth server is login.live.com, the above page provides two methods: code and token. Both could use. After auth and get the token, I can call Graph API with that token.
Code method is simpler to demonstrate. First, open this in browser:
https://login.live.com/oauth20_authorize.srf
?response_type=token
&client_id={client_id}
&redirect_uri={redirect_uri}
&scope={scope}
Then, after login an account, it will callback. Just copy the access_token in the callback URL. Do:
GET https://graph.microsoft.com/v1.0/me/onenote/pages
Accept: application/json
Authorization: Bearer {access_token}
The pages could be retrieved without 30108 error. These are simple test steps. I implemented in Java, and can get OneNote data through Microsoft's Graph library(com.microsoft.graph:microsoft-graph:1.5.+). As below:
IOnenotePageCollectionPage pages = graphClient.me().onenote().pages().buildRequest().get();
graphClient is IGraphServiceClient. But I implemented the authentication provider through login.live.com.
I use this URL to get id_token:
https://login.microsoftonline.com/common/oauth2/authorize?
response_type=id_token%20code&
client_id=MY_CLIENT_GUID_ID_IN_HERE&
redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fopenid%2Freturn&nonce=alfaYYCTxBK8oypM&
state=6DnAi0%2FICAWaH14e
and this return result like this
http://localhost:3000/auth/openid/return?
code=AAA_code_in_here&
id_token=eyJ0eXAi_xxxx_yyyy_in_here&
state=6DnAi0%2FICAWaH14e&
session_state=xxxx_guid_xxxxx
and then i use the id_token to query Graph (use POST man)
i have see this post InvalidAuthenticationToken and CompactToken issues - Microsoft Graph using PHP Curl but make no sense.
OATH 2.0 requires multiple steps. The first request returns an OAUTH Code. The next step is converting that OATUH code into a Bearer Token. This is the step you are missing here.
I would also recommend using the v2 Endpoint which is a lot easier to work with (particularly with Graph). I wrote a v2 Endpoint Primer that walks through the process and may be helpful as well.
You can't use the token directly, there is one more step to exchange the code you get from the response url into token.
Here is my C# code (using Microsoft.IdentityModel.Clients.ActiveDirectory)
public static AuthenticationResult ExchangeCodeForToken(string InTenantName, string InUserObjId, string InRedirectUri, string InApplicationAzureClientID, string InApplicationAzureClientAppKey)
{
Check.Require(!string.IsNullOrEmpty(InTenantName), "InTenantName must be provided");
Check.Require(!string.IsNullOrEmpty(InUserObjId), "InUserObjId must be provided");
if (CanCompleteSignIn) //redirect from sign-in
{
var clientCredential = new ClientCredential(InApplicationAzureClientID, InApplicationAzureClientAppKey);
var authContext = new AuthenticationContext(Globals.GetLoginAuthority(InTenantName), (TokenCache)new ADALTokenCache(InUserObjId)); //Login Authority is https://login.microsoftonline.com/TenantName
return authContext.AcquireTokenByAuthorizationCode(VerificationCode, new Uri(InRedirectUri), clientCredential, Globals.AZURE_GRAPH_API_RESOURCE_ID); //RESOURCE_ID is "https://graph.microsoft.com/"
}
return null;
}
I had this issue today when I was playing with graph API, the problem in my case was how I was generating the token.
I used postman for generating the token wherein the Auth URL section I was adding the resource = client_id whereas it should be the graph URL. After making that change I was able to make the call via postman.
In order for the above to work, please make sure your application in Azure has delegated permissions to access the Graph API.
To receive the access token and use it for profile requests, you don't need anything from server-side, you can implement the oAuth2 just from the client side.
Use the following URL for login:
https://login.microsoftonline.com/common/oauth2/authorize?client_id=YOUR_CLIENT_ID&resource=https://graph.microsoft.com&response_type=token&redirect_uri=YOUR_REDIRECT_URI&scope=User.ReadBasic.All
After successful login, user will redirected to the page with access_token parameter. Then use the following AJAX call to fetch user info:
var token = login_window.location.href.split('access_token=').pop().split('&')[0];
$.ajax({
url: "https://graph.microsoft.com/v1.0/me",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer '+token);},
success: function(data) {
alert('Hi '+data.displayName);
console.log(data);
}
});
Note that you may need to enable oauth2AllowImplicitFlow:true setting from your Azure Active Directory application manifest file.
Set "oauth2AllowImplicitFlow": false to "oauth2AllowImplicitFlow": true.
Lastly, ensure that your app has required permissions for Microsoft Graph which are sign in users and View users' basic profile
An updated answer to get access with new applications:
Register your app in the app registration portal.
Authorization request example:
https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?client_id=6731de76-14a6-49ae-97bc-6eba6914391e&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&response_mode=query&scope=offline_access%20user.read%20mail.read&state=12345
Authorization response will look like this:
https://localhost/myapp/?code=M0ab92efe-b6fd-df08-87dc-2c6500a7f84d&state=12345
Get a token
POST /{tenant}/oauth2/v2.0/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&scope=user.read%20mail.read
&code=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq3n8b2JRLk4OxVXr...
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&grant_type=authorization_code
&client_secret=JqQX2PNo9bpM0uEihUPzyrh // NOTE: Only required for web apps
Use the access token to call Microsoft Graph
GET https://graph.microsoft.com/v1.0/me
Authorization: Bearer eyJ0eXAiO ... 0X2tnSQLEANnSPHY0gKcgw
Host: graph.microsoft.com
Source:
https://learn.microsoft.com/en-us/graph/auth-v2-user?context=graph/api/1.0
You can also get an access token without a user, see here:
https://learn.microsoft.com/en-us/graph/auth-v2-service
I am developing an iOS application for a store on BigCommerce.com . I have successfully retrieved the products list from the BigCommerce API and I have also created a new user using the same.
Create User: https://developer.bigcommerce.com/api/stores/v2/customers#create-a-customer
Product List:
https://developer.bigcommerce.com/api/stores/v2/products
But i am unable to understand that how should i login into the BigCommerce Store as a customer to purchase products listed.
Please can anyone help.
You can login by sending a POST to:
/remote.php?w=expressCheckoutLogin
Send fields 'login_email' and 'login_pass' in your POST's body.
Its very hard to finding login api in bigCommerce. this solution is 100% working and tested.
Keep Enjoy
APi URL : https://api.bigcommerce.com/stores/[STORE_HASH]/v2/customers/[CUSTOMER_ID]/validate
Method : POST
Header
X-Auth-Client : Client_id
X-Auth-Token : Access Token
Accept : application/json
Content-Type : application/json
Body
{
"password": "123456"
}
Response
{
"success": true
}