Skip to content
This repository was archived by the owner on Jul 19, 2024. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions ServiceSamples/AuthenticationUtility/OAuthHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,70 @@ public class OAuthHelper
/// </summary>
public const string OAuthHeader = "Authorization";

/// <summary>
/// Retrieves an authentication header from the service.
/// </summary>
/// <returns>The authentication header for the Web API call.</returns>
public static string GetAuthenticationHeader(Func<DateTimeOffset, DateTimeOffset> callBackSetExpirationToken, bool useWebAppAuthentication = false)
{
string aadTenant = ClientConfiguration.Default.ActiveDirectoryTenant;
string aadClientAppId = ClientConfiguration.Default.ActiveDirectoryClientAppId;
string aadClientAppSecret = ClientConfiguration.Default.ActiveDirectoryClientAppSecret;
string aadResource = ClientConfiguration.Default.ActiveDirectoryResource;

AuthenticationContext authenticationContext = new AuthenticationContext(aadTenant, false);
AuthenticationResult authenticationResult;

if (useWebAppAuthentication)
{
if (string.IsNullOrEmpty(aadClientAppSecret))
{
Console.WriteLine("Please fill AAD application secret in ClientConfiguration if you choose authentication by the application.");
throw new Exception("Failed OAuth by empty application secret.");
}

try
{
// OAuth through application by application id and application secret.
var creadential = new ClientCredential(aadClientAppId, aadClientAppSecret);
authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, creadential).Result;
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Failed to authenticate with AAD by application with exception {0} and the stack trace {1}", ex.ToString(), ex.StackTrace));
throw new Exception("Failed to authenticate with AAD by application.");
}
}
else
{
// OAuth through username and password.
string username = ClientConfiguration.Default.UserName;
string password = ClientConfiguration.Default.Password;

if (string.IsNullOrEmpty(password))
{
Console.WriteLine("Please fill user password in ClientConfiguration if you choose authentication by the credential.");
throw new Exception("Failed OAuth by empty password.");
}

try
{
// Get token object
var userCredential = new UserPasswordCredential(username, password); ;
authenticationResult = authenticationContext.AcquireTokenAsync(aadResource, aadClientAppId, userCredential).Result;
}
catch (Exception ex)
{
Console.WriteLine(string.Format("Failed to authenticate with AAD by the credential with exception {0} and the stack trace {1}", ex.ToString(), ex.StackTrace));
throw new Exception("Failed to authenticate with AAD by the credential.");
}
}

callBackSetExpirationToken(authenticationResult.ExpiresOn.UtcDateTime);
// Create and get JWT token
return authenticationResult.CreateAuthorizationHeader();
}

/// <summary>
/// Retrieves an authentication header from the service.
/// </summary>
Expand Down
31 changes: 22 additions & 9 deletions ServiceSamples/ODataConsoleApplication/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using Microsoft.OData.Client;
using ODataUtility.Microsoft.Dynamics.DataEntities;
using System;
using System.Linq;

namespace ODataConsoleApplication
{
Expand All @@ -17,12 +16,15 @@ static void Main(string[] args)

Uri oDataUri = new Uri(ODataEntityPath, UriKind.Absolute);
var context = new Resources(oDataUri);

DateTimeOffset _expirationToken = DateTime.UtcNow;
var authenticationHeader = "";
context.SendingRequest2 += new EventHandler<SendingRequest2EventArgs>(delegate (object sender, SendingRequest2EventArgs e)
{
var authenticationHeader = OAuthHelper.GetAuthenticationHeader(useWebAppAuthentication: true);
e.RequestMessage.SetHeader(OAuthHelper.OAuthHeader, authenticationHeader);
});
{

if (!IsValidToken()) //Auto refresh token
authenticationHeader = OAuthHelper.GetAuthenticationHeader(SetTokenExpirationDateTime, useWebAppAuthentication: true);
e.RequestMessage.SetHeader(OAuthHelper.OAuthHeader, authenticationHeader);
});

// Uncomment below to run specific examples

Expand All @@ -36,7 +38,7 @@ static void Main(string[] args)
// QueryExamples.SortSyntax(context);
// QueryExamples.FilterByCompany(context);
// QueryExamples.ExpandNavigationalProperty(context);


// 2. Simple CRUD examples

Expand All @@ -48,8 +50,19 @@ static void Main(string[] args)
// ODataChangesetsExample.CreateSalesOrderWithoutChangeset(context);

Console.ReadLine();
}


DateTimeOffset SetTokenExpirationDateTime(DateTimeOffset datahoraexpiracao)
{
_expirationToken = datahoraexpiracao;

return datahoraexpiracao;
}

bool IsValidToken()
{
return _expirationToken > DateTime.UtcNow;
}

}
}
}