Skip to content

Add KeyVault Token Capability for AccessToken auth #5158

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 29, 2017
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Xunit;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using System.Linq;

namespace Common.Authentication.Test
{
Expand Down Expand Up @@ -98,5 +99,55 @@ public void VerifyValidateAuthorityFalseForOnPremise()

Assert.False(((MockAccessTokenProvider)authFactory.TokenProvider).AdalConfiguration.ValidateAuthority);
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void CanAuthenticateWithAccessToken()
{
AzureSessionInitializer.InitializeAzureSession();
string tenant = Guid.NewGuid().ToString();
string userId = "[email protected]";
var armToken = Guid.NewGuid().ToString();
var graphToken = Guid.NewGuid().ToString();
var kvToken = Guid.NewGuid().ToString();
var account = new AzureAccount
{
Id = userId,
Type = AzureAccount.AccountType.AccessToken
};
account.SetTenants(tenant);
account.SetAccessToken(armToken);
account.SetProperty(AzureAccount.Property.GraphAccessToken, graphToken);
account.SetProperty(AzureAccount.Property.KeyVaultAccessToken, kvToken);
var authFactory = new AuthenticationFactory();
var environment = AzureEnvironment.PublicEnvironments.Values.First();
var checkArmToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null);
VerifyToken(checkArmToken, armToken, userId, tenant);
checkArmToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.ActiveDirectoryServiceEndpointResourceId);
VerifyToken(checkArmToken, armToken, userId, tenant);
var checkGraphToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, AzureEnvironment.Endpoint.GraphEndpointResourceId);
VerifyToken(checkGraphToken, graphToken, userId, tenant);
checkGraphToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.GraphEndpointResourceId);
VerifyToken(checkGraphToken, graphToken, userId, tenant);
var checkKVToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, environment.AzureKeyVaultServiceEndpointResourceId);
VerifyToken(checkKVToken, kvToken, userId, tenant);
checkKVToken = authFactory.Authenticate(account, environment, tenant, new System.Security.SecureString(), "Never", null, AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId);
VerifyToken(checkKVToken, kvToken, userId, tenant);
}

void VerifyToken(IAccessToken checkToken, string expectedAccessToken, string expectedUserId, string expectedTenant)
{

Assert.True(checkToken is RawAccessToken);
Assert.Equal(expectedAccessToken, checkToken.AccessToken);
Assert.Equal(expectedUserId, checkToken.UserId);
Assert.Equal(expectedTenant, checkToken.TenantId);
checkToken.AuthorizeRequest((type, token) =>
{
Assert.Equal(expectedAccessToken, token);
Assert.Equal("Bearer", type);
});
}

}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\..\..\packages\xunit.runner.visualstudio.2.1.0\build\net20\xunit.runner.visualstudio.props" Condition="Exists('..\..\..\packages\xunit.runner.visualstudio.2.1.0\build\net20\xunit.runner.visualstudio.props')" />
<Import Project="..\..\..\packages\xunit.core.2.1.0\build\portable-net45+win8+wp8+wpa81\xunit.core.props" Condition="Exists('..\..\..\packages\xunit.core.2.1.0\build\portable-net45+win8+wp8+wpa81\xunit.core.props')" />
<Import Project="..\..\packages\xunit.runner.visualstudio.2.1.0\build\net20\xunit.runner.visualstudio.props" Condition="Exists('..\..\packages\xunit.runner.visualstudio.2.1.0\build\net20\xunit.runner.visualstudio.props')" />
<Import Project="..\..\packages\xunit.core.2.1.0\build\portable-net45+win8+wp8+wpa81\xunit.core.props" Condition="Exists('..\..\packages\xunit.core.2.1.0\build\portable-net45+win8+wp8+wpa81\xunit.core.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,5 @@
<package id="xunit.core" version="2.1.0" targetFramework="net45" />
<package id="xunit.extensibility.core" version="2.1.0" targetFramework="net45" />
<package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net45" />
<package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net45" />
</packages>
<package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net45" developmentDependency="true" />
</packages>
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;

namespace Microsoft.Azure.Commands.Common.Authentication
{
public class RawAccessToken : IAccessToken
{
public string AccessToken
{
get; set;
}

public string LoginType
{
get; set;
}

public string TenantId
{
get; set;
}

public string UserId
{
get; set;
}

public void AuthorizeRequest(Action<string, string> authTokenSetter)
{
authTokenSetter("Bearer", AccessToken);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@
<Compile Include="Authentication\ITokenProvider.cs" />
<Compile Include="Authentication\KeyStoreApplicationCredentialProvider.cs" />
<Compile Include="Authentication\ProtectedFileTokenCache.cs" />
<Compile Include="Authentication\RawAccessToken.cs" />
<Compile Include="Authentication\ServicePrincipalKeyStore.cs" />
<Compile Include="Authentication\ServicePrincipalTokenProvider.cs" />
<Compile Include="Authentication\UserTokenProvider.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,42 @@ public IAccessToken Authenticate(
configuration.ClientRedirectUri,
configuration.ResourceClientUri,
configuration.ValidateAuthority);
if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
if (account != null && environment != null
&& account.Type == AzureAccount.AccountType.AccessToken)
{
var rawToken = new RawAccessToken
{
TenantId = tenant,
UserId = account.Id,
LoginType = AzureAccount.AccountType.AccessToken
};

if ((string.Equals(resourceId, environment.AzureKeyVaultServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase)
|| string.Equals(AzureEnvironment.Endpoint.AzureKeyVaultServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase))
&& account.IsPropertySet(AzureAccount.Property.KeyVaultAccessToken))
{
rawToken.AccessToken = account.GetProperty(AzureAccount.Property.KeyVaultAccessToken);
}
else if ((string.Equals(resourceId, environment.GraphEndpointResourceId, StringComparison.OrdinalIgnoreCase)
|| string.Equals(AzureEnvironment.Endpoint.GraphEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase))
&& account.IsPropertySet(AzureAccount.Property.GraphAccessToken))
{
rawToken.AccessToken = account.GetProperty(AzureAccount.Property.GraphAccessToken);
}
else if ((string.Equals(resourceId, environment.ActiveDirectoryServiceEndpointResourceId, StringComparison.OrdinalIgnoreCase)
|| string.Equals(AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, resourceId, StringComparison.OrdinalIgnoreCase))
&& account.IsPropertySet(AzureAccount.Property.AccessToken))
{
rawToken.AccessToken = account.GetAccessToken();
}
else
{
throw new InvalidOperationException(string.Format(Resources.AccessTokenResourceNotFound, resourceId));
}

token = rawToken;
}
else if (account.IsPropertySet(AzureAccount.Property.CertificateThumbprint))
{
var thumbprint = account.GetProperty(AzureAccount.Property.CertificateThumbprint);
#if !NETSTANDARD
Expand Down Expand Up @@ -325,7 +360,7 @@ private AdalConfiguration GetAdalConfiguration(IAzureEnvironment environment, st
string.Format("No Active Directory endpoint specified for environment '{0}'", environment.Name));
}

var audience = environment.GetEndpoint(resourceId);
var audience = environment.GetEndpoint(resourceId)?? resourceId;
if (string.IsNullOrWhiteSpace(audience))
{
string message = Resources.InvalidManagementTokenAudience;
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -310,4 +310,8 @@
<value>[Common.Authentication]: Parsed token '{0}' with json value '{1}' and decoded issuer '{2}'.</value>
<comment>0 = raw token; 1 = decoded token; 2 = issuer</comment>
</data>
<data name="AccessTokenResourceNotFound" xml:space="preserve">
<value>Cannot retrieve access token for resource '{0}'. Please ensure that you have provided the appropriate access tokens when using access token login.</value>
<comment>{0} = authentication resource id</comment>
</data>
</root>
4 changes: 2 additions & 2 deletions src/Common/Commands.ScenarioTests.Common/packages.config
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@
<package id="xunit.core" version="2.1.0" targetFramework="net45" />
<package id="xunit.extensibility.core" version="2.1.0" targetFramework="net45" />
<package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net45" />
<package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net45" />
</packages>
<package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net45" developmentDependency="true" />
</packages>
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,5 @@
<package id="xunit.core" version="2.1.0" targetFramework="net45" />
<package id="xunit.extensibility.core" version="2.1.0" targetFramework="net45" />
<package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net45" />
<package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net45" />
</packages>
<package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net45" developmentDependency="true" />
</packages>
Original file line number Diff line number Diff line change
Expand Up @@ -74,21 +74,23 @@ public string GetToken()

private static string GetTenantId(IAzureContext context)
{
var tenantId = string.Empty;
if (context.Account == null)
{
throw new ArgumentException(KeyVaultProperties.Resources.ArmAccountNotFound);
}

if (context.Account.Type != AzureAccount.AccountType.User &&
context.Account.Type != AzureAccount.AccountType.ServicePrincipal)
throw new ArgumentException(string.Format(KeyVaultProperties.Resources.UnsupportedAccountType, context.Account.Type));

if (context.Subscription != null && context.Account != null)
var tenantId = string.Empty;
if (context.Tenant != null && context.Tenant.GetId() != Guid.Empty)
{
tenantId = context.Tenant.Id.ToString();
}
else if (string.IsNullOrWhiteSpace(tenantId) && context.Subscription != null && context.Account != null)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think you need to check if the tenantId is empty - you just set it to empty above

{
tenantId = context.Subscription.GetPropertyAsArray(AzureSubscription.Property.Tenants)
.Intersect(context.Account.GetPropertyAsArray(AzureAccount.Property.Tenants))
.FirstOrDefault();
}

if (string.IsNullOrWhiteSpace(tenantId) && context.Tenant != null && context.Tenant.GetId() != Guid.Empty)
tenantId = context.Tenant.Id.ToString();
return tenantId;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

using Microsoft.Azure.Commands.Common;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.ScenarioTest;
using Microsoft.Azure.ServiceManagemenet.Common.Models;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
Expand All @@ -24,6 +26,7 @@
using System.Management.Automation;
using System.Threading;
using Xunit;
using Xunit.Abstractions;

namespace Microsoft.Azure.Commands.Profile.Test
{
Expand All @@ -33,8 +36,16 @@ public class LongRunningCmdletTests : RMTestBase
static readonly ProgressRecord Progress = new ProgressRecord(0, "activity", "description");
static readonly ErrorRecord Error = new ErrorRecord(new InvalidOperationException("invalid operation"), "12345", ErrorCategory.InvalidOperation, new object());
static readonly object Output = new TestCmdletOutput();
static readonly object lockObject = new object();

ManualResetEvent jobCompleted = new ManualResetEvent(false);
private XunitTracingInterceptor xunitLogger;

public LongRunningCmdletTests(ITestOutputHelper output)
{
TestExecutionHelpers.SetUpSessionAndProfile();
xunitLogger = new XunitTracingInterceptor(output);
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
Expand All @@ -56,7 +67,6 @@ public void CanSupportShouldProcess()
Mock<ICommandRuntime> mockRuntime;
var cmdlet = SetupCmdlet(true, false, out mockRuntime);
var job = cmdlet.ExecuteAsJob("Test Job") as AzureLongRunningJob<AzureStreamTestCmdlet>;
job.StateChanged += this.HandleStateChange;
WaitForCompletion(job, j =>
{
ValidateCompletedCmdlet(job);
Expand Down Expand Up @@ -226,9 +236,10 @@ AzureStreamTestCmdlet SetupCmdlet(bool CallShouldProcess, bool CallShouldContinu

public void HandleStateChange(object sender, JobStateEventArgs args)
{
lock (this)
lock (lockObject)
{
var job = sender as AzureLongRunningJob;
xunitLogger.Information(string.Format("[statechangedhandler]: previous state: '{0}', current state: '{1}'", args.PreviousJobStateInfo?.State, args.JobStateInfo?.State));
if (args.JobStateInfo.State == JobState.Completed || args.JobStateInfo.State == JobState.Failed || args.JobStateInfo.State == JobState.Stopped)
{
this.jobCompleted.Set();
Expand All @@ -254,7 +265,8 @@ void WaitForCompletion(AzureLongRunningJob job, Action<AzureLongRunningJob> vali
job.StateChanged += this.HandleStateChange;
try
{
if (this.jobCompleted.WaitOne(TimeSpan.FromSeconds(10)))
HandleStateChange(job, new JobStateEventArgs(job.JobStateInfo, new JobStateInfo(JobState.NotStarted)));
if (this.jobCompleted.WaitOne(TimeSpan.FromSeconds(30)))
{
validate(job);
}
Expand All @@ -266,6 +278,10 @@ void WaitForCompletion(AzureLongRunningJob job, Action<AzureLongRunningJob> vali
finally
{
job.StateChanged -= this.HandleStateChange;
foreach (var message in job.Debug)
{
xunitLogger.Information(message?.Message);
}
}

}
Expand All @@ -287,6 +303,7 @@ public class TestCmdletOutput
public string Property { get { return "PropertyValue"; } }
}

[Cmdlet(VerbsDiagnostic.Test, "AzureJob",ConfirmImpact =ConfirmImpact.High)]
public class AzureStreamTestCmdlet : AzurePSCmdlet
{
public IList<ErrorRecord> Error { get; set; } = new List<ErrorRecord>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@
<package id="xunit.core" version="2.1.0" targetFramework="net45" />
<package id="xunit.extensibility.core" version="2.1.0" targetFramework="net45" />
<package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net45" />
<package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net45" />
<package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net45" developmentDependency="true" />
</packages>