Hi @Radu Nour
I'm glad to hear you solve the problem ,if you have any issue about SharePoint, you are welcome to raise a ticket in this forum.
By the way, since the Microsoft Q&A community has a policy that "The question author cannot accept their own answer. They can only accept answers by others." and according to the scenario introduced here: Answering your own questions on Microsoft Q&A, I would make a brief summary of this thread:
[Sharepoint Rest API Permissions to create a Site]
Issue Symptom:
Get 401 Unauthorized error when create a Sharepoint site using Rest Api with access token
Solution:
The error caused by missing request headers and wrong json format, fixed by following powershell script
Import-Module MSAL.PS
#Variables
$ClientID = "XXX"
$ClientSecret = "XXX"
$ClientCertificate = Get-Item "Cert:\CurrentUser\My\XXX"
$tenantID = "XXX"
$scope = "https://XXX.sharepoint.com/.default"
$authority = "https://login.microsoftonline.com/$tenantID/oauth2/v2.0/token"
$Body = @{
"grant_type" = "client_credentials";
"client_id" = "$ClientID";
"client_secret" = "$ClientSecret";
"scope" = "$scope";
}
#Get AccessToken
#$result = Invoke-RestMethod -Method POST -uri $authority -Body $body
#$AccessToken = $result.access_token
#Get AccessToken with MSAL
$AccessToken = Get-MsalToken -ClientId $ClientID -TenantId $tenantID -ClientCertificate $ClientCertificate -Scope $scope
# Inspect the Access Token using JWTDetails PowerShell Module
$AccessToken.AccessToken | Get-JWTDetails
#Create Event
$headers = @{
# "Authorization" = "Bearer "+ $AccessToken;
# "Authorization" = $AccessToken.CreateAuthorizationHeader();
# "Authorization" = "Bearer "+ $AccessToken.CreateAuthorizationHeader();
"Authorization" = "Bearer $($AccessToken.AccessToken)";
"Accept" = "application/json;odata.metadata=none";
"Content-Type" = "application/json;odata=verbose";
"odata-version" = "4.0"
}
#Create JSON Object
$json = @"
{
"request": {
"Title": "Communication Site 1",
"Url":"https://XXX.sharepoint.com/sites/commsite1",
"Lcid": 1033,
"ShareByEmailEnabled":false,
"Classification":"Low Business Impact",
"Description":"Description",
"WebTemplate":"SITEPAGEPUBLISHING#0",
"SiteDesignId":"6142d2a0-63a5-4ba0-aede-d9fefca2c767",
"Owner":"******@XXX.com",
"WebTemplateExtensionId":"00000000-0000-0000-0000-000000000000"
}
}
"@
$uri = "https://XXX.sharepoint.com/_api/SPSiteManager/create"
Invoke-RestMethod -Method POST -Uri $uri -Headers $headers -Body $json
You could click the "Accept Answer" button for this summary to close this thread, and this can make it easier for other community member's to see the useful information when reading this thread. Thanks for your understanding!