You first need to create and register an Azure AD app in the Azure portal. That app needs the delegated Group.ReadWrite.All
permission from Microsoft Graph API.
Then you need to get the client ID and client secret of that app. We will need to use that in our application.
Once you have that, you can try and modify the below code:
static async Task MainAsync()
{
string userName = "[email protected]";
string password = "password";
List<KeyValuePair<string, string>> vals = new List<KeyValuePair<string, string>>();
string tenantName = "tenantname.onmicrosoft.com";
string authString = "https://login.microsoftonline.com/" + tenantName;
string resource = "https://graph.microsoft.com";
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
// Config for OAuth client credentials
string clientId = "client-id";
string key = "client-secret";
vals.Add(new KeyValuePair<string, string>("client_id", clientId));
vals.Add(new KeyValuePair<string, string>("resource", resource));
vals.Add(new KeyValuePair<string, string>("username", userName));
vals.Add(new KeyValuePair<string, string>("password", password));
vals.Add(new KeyValuePair<string, string>("grant_type", "password"));
vals.Add(new KeyValuePair<string, string>("client_secret", key));
string url = string.Format("https://login.windows.net/{0}/oauth2/token", tenantName);
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
HttpContent content = new FormUrlEncodedContent(vals);
HttpResponseMessage hrm = httpClient.PostAsync(url, content).Result;
AuthenticationResponse authenticationResponse = null;
if (hrm.IsSuccessStatusCode)
{
Stream data = await hrm.Content.ReadAsStreamAsync();
DataContractJsonSerializer serializer = new
DataContractJsonSerializer(typeof(AuthenticationResponse));
authenticationResponse = (AuthenticationResponse)serializer.ReadObject(data);
var accessToken = authenticationResponse.access_token;
Stream groupLogoStream = new FileStream("C:\\groupassets\\logo-original.png",
FileMode.Open, FileAccess.Read);
var group = UnifiedGroupsUtility.CreateUnifiedGroup("displayName", "description",
"mymodernteamsite", accessToken, groupLogo: groupLogoStream);
// We received a group entity containing information about the group
string groupUrl = group.SiteUrl;
string groupId = group.GroupId;
}
}
}
Have written elongated blog post here - Create modern team sites with CSOM C# and access token
@admins/moderators - have added link to my blog as it will be too big an answer here. However, have added the necessary and relevant code portion that will be enough for the OP to go ahead. Do let me know if I should add more here.