I need to query get a single user details through Microsoft graph by email id, can anyone help me I couldn't find it in MS docs.
var users = graphServiceClient.Users.Request().GetAsync().GetAwaiter().GetResult();
this brings only 100 users
I need to get user by email so I can get specific user
Pls try this code.
using Azure.Identity;
using Microsoft.Graph;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "hanxia.onmicrosoft.com";
var clientId = "azure_ad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var temp = await graphClient.Users.Request().Filter("mail eq 'tiny#outlook.com'").GetAsync();
When we want to do a filter in Ms graph api, we may firstly check if the target property support filter, for ms user api, mail is supported.
Related
I am trying to retrieve a list of users from an azure security group, however i am having trouble with this, as i do not know the best possible and easy way to do this in c#. Any help/direction and sample code would be grateful.
To retrieve list of users from an azure security group, make sure to grant the below API permission:
Please try using the below script by Jason Pan in this SO Thread like below:
public async Task<JsonResult> sample()
{
var clientId = Your_Client_ID;
var clientSecret = Your_Client_Secret;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = Your_Tenant_ID;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
try
{
var members = await graphClient.Groups["Your_Group_ID"].Members.Request().GetAsync();
return Json(members);
}
catch (Exception e)
{
return Json("");
throw;
}
}
You can use Microsoft Graph restful web APIs to access microsoft cloud resources .
It has api endpoints for groups , users etc.
In your case you can use list groups endpoint to fetch the groups.
https://learn.microsoft.com/en-us/graph/api/resources/group?view=graph-rest-1.0
I'm trying to set automatic replies for Microsoft users using the example here.
The difference from the docs is that I'm trying to do this not for me, but for another user using permissions. Getting error: The OData request is not supported
The issue is mentioned here and here. But both are closed.
The one solution mentioned is here but for this I'm getting the error Access is denied. Check credentials and try again.
Does anyone know of a way to set automatic replies / update mailbox settings in microsoft graph using the c# sdk using the users option - not me?
Using application api permission is right here and we may also refer to the workaround mentioned by OP which worked for him.
===========================================
According to the api document, it support Application permission,
So could you pls try this code:
using Azure.Identity;
using Microsoft.Graph;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var mailboxSettings = new MailboxSettings
{
AutomaticRepliesSetting = new AutomaticRepliesSetting
{
Status = AutomaticRepliesStatus.Scheduled,
ScheduledStartDateTime = new DateTimeTimeZone
{
DateTime = "2022-07-03T18:00:00",
TimeZone = "UTC"
},
ScheduledEndDateTime = new DateTimeTimeZone
{
DateTime = "2022-07-07T18:00:00",
TimeZone = "UTC"
},
ExternalReplyMessage = "I'm on vacation.",
InternalReplyMessage = "I'm on vacation."
}
};
var user = new User();
user.MailboxSettings = mailboxSettings;
await graphClient.Users["user_id"].Request().UpdateAsync(user);
And pls don't forget to add Application api permission MailboxSettings.ReadWrite in Azure AD.
I am trying to upload file on onedrive by using microsoft graph onedrive api.
I am using the method for authentication
Client credentials provider
https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#client-credentials-provider
Like:
// /.default scope, and preconfigure your permissions on the
// app registration in Azure. An administrator must grant consent
// to those permissions beforehand.
var scopes = new[] { "https://graph.microsoft.com/.default" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "my-tenantid";
// Values from app registration
var clientId = "YOUR_CLIENT_ID";
var clientSecret = "YOUR_CLIENT_SECRET";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// https://learn.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
HttpPostedFileBase file = Request.Files;[0];
int fileSize = file.ContentLength;
string fileName = file.FileName;
string mimeType = file.ContentType;
Stream fileContent = file.InputStream;
var res = await graphClient.Me.Drive.Root.ItemWithPath(fileName).Content
.Request()
.PutAsync<DriveItem>(fileContent);
After executing this code then it gives an error in response.
Message: /me request is only valid with delegated authentication flow.
Inner error:
AdditionalData:
date: 2021-12-29T05:30:08
request-id: b51e50ea-4a62-4dc7-b8d2-b26d75268cdc
client-request-id: b51e50ea-4a62-4dc7-b8d2-b26d75268cdc
ClientRequestId: b51e50ea-4a62-4dc7-b8d2-b26d75268cdc
Client credential flow will generate the token on behalf the app itself, so in this scenario, users don't need to sign in first to generate the token stand for the user and then call the api. And because of the design,when you used Me in the graph SDK, your code/app don't know who is Me so it can't work. You should know the user_id first and use /users/{id | userPrincipalName} instead of /Me, in the SDK, that is graphClient.Users["your_user_id"] instead of graphClient.Me
In your scenario, there're 2 solutions, one way is using delegated authentication flow like what you said in your title, another way is get the user id before calling the graph api so that you can use Users["id"] but not Me
===================== Update=========================
I haven't finished the code yet but I found the correct solution now.
Firstly, we can upload file to one drive by this api, you may check the screenshot if this is one drive or sharepoint:
https://graph.microsoft.com/v1.0/users/user_id/drive/items/root:/testupload2.txt:/content
If it is, then the next is easy, using the code below to get an access token and send http request to calling the api:
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "your_azuread_clientid";
var clientSecret = "corresponding_client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var tokenRequestContext = new TokenRequestContext(scopes);
var token = clientSecretCredential.GetTokenAsync(tokenRequestContext).Result.Token;
I know it's complex because the api is not the same as this one which has SDK sample, but I think it also deserves to try if they are similar.
I am not an expert on all things Azure, but I'd like to read my own calendar programmatically. I found some code to access Microsoft Graph and read my calendar, but it seems I have to create an App Registration first, is it possible to SKIP the app registration if I only need to read my OWN calendar? here's my starting point:
var scopes = new[] { "User.Read" };
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var userName = "myaccount#company.com";
var password = "pwdhere";
var userNamePasswordCredential = new UsernamePasswordCredential(
userName, password, tenantId, clientId, options);
var graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);
var events = await graphClient.Me.Calendar.Events
.Request()
.Filter("startsWith(subject,'All')")
.GetAsync();
You need an app registration, otherwise you couldn't even log in. If it's an Azure AD you don't control, such as your employer, you'll need to get an admin to create that for you.
I'm trying to create Windows Service that will allow me to send emails on behalf of specific users.
Lates version of Graph Client allows specifying retries using WithMaxRetry.
Unfortunately, there aren't any good examples showing "best practices" when creating ConfidentialClientApplication.
Currently, I use the below code to send email without asking for login and password:
const string clientId = "foo...99a0";
const string clientSecret = "#6A...cx#$a";
const string tenant = "1c...7";
const string azureAdInstance = "https://login.microsoftonline.com/{0}";
var authority = string.Format(CultureInfo.InvariantCulture, azureAdInstance, tenant);
string[] scopes = { "https://graph.microsoft.com/.default" };
var clientCredentials = new ClientCredential(clientSecret);
var confidentialClientApplication =
new ConfidentialClientApplication(
clientId,
authority,
"https://daemon",
clientCredentials,
null,
new TokenCache());
var graphClient =
new GraphServiceClient("https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async(requestMessage) =>
{
var result = await confidentialClientApplication
.AcquireTokenForClientAsync(scopes);
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("bearer", result.AccessToken);
}));
var recipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "test#example.com"
}
}
};
var email = new Message
{
Body = new ItemBody
{
Content = "Works fine!",
ContentType = BodyType.Html,
},
Subject = "Test",
ToRecipients = recipients
};
await graphClient
.Users["sender#example.onmicrosoft.com"]
.SendMail(email, true)
.Request()
.PostAsync();
but I can't figure out how to create ConfidentialClientApplication based on recent changes from Request Context With Middleware Options.
Because I wasn't able to find up to date example my question is, how should I create GraphServiceClient to be able to send emails from Windows Service?
This is code from above PR:
HttpProvider httpProvider = new HttpProvider();
var graphClient = new GraphServiceClient(appOnlyProvider, httpProvider);
graphClient.PerRequestAuthProvider = () => CreateDelegatedProvider();
var me = await graphClient.Me.Request()
.WithScopes(string[] { "User.Read" }) // adds auth scopes
.WithMaxRetry(5) // specifies maximum number of retries
.WithPerRequestAuthProvider()
.GetAsync();
How should I adopt it per my requirement?
I'm new to Graph so I want to avoid bad code.
One of the pieces of the puzzle that I believe you are missing is the new Authentication Providers library that is here https://www.nuget.org/packages/Microsoft.Graph.Auth/0.1.0-preview and there are some examples of how to use these Authentication providers here https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth
This library provides a set of authorization providers based on the desired OAuth2 flow. In your case you should use the ClientCredentialsProvider instead of the DelegateProvider.
You don't need to use a PerRequestAuthProvider. That is only needed for scenarios where you want to switch between different flows or different appIds in each call.