Forum Discussion
rodfrey
May 29, 2019Copper Contributor
Permissions for Project Online to access via REST api
Hi. I'm having a lot of trouble trying to access Project Online data through the REST interface. I understand Oauth2 and I'm successfully getting an authorization token using a client id and sec...
Hepster
Copper Contributor
dlafer Yes, we solved it after weeks of trying. We did this...
ProjectContext myProjectContext = _projectOnlineUtils.GetProjectContext
(_configuration["ProjectOnline:SiteUrl"],
_configuration["AzureAd:ClientId"],
_configuration["ProjectOnline:PJOAccount"],
_configuration["ProjectOnline:PJOPassword"],
_configuration["AzureAd:TenantId"],
_configuration["ProjectOnline:Scope"]);
ProjectCollection projects = myProjectContext.Projects;
myProjectContext.Load(projects);
await myProjectContext.ExecuteQueryAsync();
and this
public ProjectContext GetProjectContext(string siteUrl, string clientId, string userName, string password, string tenantId, string scope)
{
try
{
PublicClientApplicationBuilder pcaConfig = PublicClientApplicationBuilder.Create(clientId)
.WithTenantId(tenantId);
string redirectUri = "http://localhost";
pcaConfig.WithRedirectUri(redirectUri);
SecureString sc = new();
foreach (char c in password) sc.AppendChar(c);
AuthenticationResult tokenResult = pcaConfig.Build()
.AcquireTokenByUsernamePassword
(new[] {scope},
userName,
sc)
.ExecuteAsync()
.Result;
ProjectContext projectContext = new(siteUrl);
projectContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + tokenResult.AccessToken; };
return projectContext;
}
catch (Exception e)
{
_logger.LogError($"{DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)}: Error - {e.Message}");
return null;
}
}
It need a bit of a clean, but it works.