diff --git a/src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs b/src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs index 893885fcc278..840c9bbd9a22 100644 --- a/src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs +++ b/src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs @@ -57,6 +57,7 @@ public class ConnectAzureRmAccountCommand : AzureContextModificationCmdlet, IMod public const string MSISecretVariable = "MSI_SECRET"; public const int DefaultMaxContextPopulation = 25; public const string DefaultMaxContextPopulationString = "25"; + private const int DefaultManagedServicePort = 50342; private IAzureEnvironment _environment; @@ -127,19 +128,6 @@ public class ConnectAzureRmAccountCommand : AzureContextModificationCmdlet, IMod [Alias("MSI", "ManagedService")] public SwitchParameter Identity { get; set; } - [Parameter(ParameterSetName = ManagedServiceParameterSet, Mandatory = false, HelpMessage = "Obsolete. To use customized MSI endpoint, please set environment variable MSI_ENDPOINT, e.g. \"http://localhost:50342/oauth2/token\". Port number for managed service login.")] - [PSDefaultValue(Help = "50342", Value = 50342)] - public int ManagedServicePort { get; set; } = 50342; - - [Parameter(ParameterSetName = ManagedServiceParameterSet, Mandatory = false, HelpMessage = "Obsolete. To use customized MSI endpoint, please set environment variable MSI_ENDPOINT, e.g. \"http://localhost:50342/oauth2/token\". Host name for managed service login.")] - [PSDefaultValue(Help = "localhost", Value = "localhost")] - public string ManagedServiceHostName { get; set; } = "localhost"; - - [Parameter(ParameterSetName = ManagedServiceParameterSet, Mandatory = false, HelpMessage = "Obsolete. To use customized MSI secret, please set environment variable MSI_SECRET. Secret, used for some kinds of managed service login.")] - [ValidateNotNullOrEmpty] - public SecureString ManagedServiceSecret { get; set; } - - [Alias("SubscriptionName", "SubscriptionId")] [Parameter(ParameterSetName = UserParameterSet, Mandatory = false, HelpMessage = "Subscription Name or ID", ValueFromPipeline = true)] @@ -318,55 +306,7 @@ public override void ExecuteCmdlet() break; case ManagedServiceParameterSet: azureAccount.Type = AzureAccount.AccountType.ManagedService; - var builder = new UriBuilder - { - Scheme = "http", - Host = ManagedServiceHostName, - Port = ManagedServicePort, - Path = "/oauth2/token" - }; - - //ManagedServiceHostName/ManagedServicePort/ManagedServiceSecret are obsolete, should be removed in next major release - if (this.IsBound(nameof(ManagedServiceHostName)) || this.IsBound(nameof(ManagedServicePort)) || this.IsBound(nameof(ManagedServiceSecret))) - { - WriteWarning(Resources.ObsoleteManagedServiceParameters); - } - - var envSecret = System.Environment.GetEnvironmentVariable(MSISecretVariable); - - var msiSecret = this.IsBound(nameof(ManagedServiceSecret)) - ? ManagedServiceSecret.ConvertToString() - : envSecret; - - var envUri = System.Environment.GetEnvironmentVariable(MSIEndpointVariable); - - var suppliedUri = this.IsBound(nameof(ManagedServiceHostName)) - ? builder.Uri.ToString() - : envUri; - - if (!this.IsBound(nameof(ManagedServiceHostName)) && !string.IsNullOrWhiteSpace(envUri) - && !this.IsBound(nameof(ManagedServiceSecret)) && !string.IsNullOrWhiteSpace(envSecret)) - { - // set flag indicating this is AppService Managed Identity ad hoc mode - azureAccount.SetProperty(AuthenticationFactory.AppServiceManagedIdentityFlag, "the value not used"); - } - - if (!string.IsNullOrWhiteSpace(msiSecret)) - { - azureAccount.SetProperty(AzureAccount.Property.MSILoginSecret, msiSecret); - } - - if (!string.IsNullOrWhiteSpace(suppliedUri)) - { - azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, suppliedUri); - } - else - { - azureAccount.SetProperty(AzureAccount.Property.MSILoginUriBackup, builder.Uri.ToString()); - azureAccount.SetProperty(AzureAccount.Property.MSILoginUri, AuthenticationFactory.DefaultMSILoginUri); - } - - azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : string.Format(Constants.DefaultMsiAccountIdPrefix + "{0}", ManagedServicePort); + azureAccount.Id = this.IsBound(nameof(AccountId)) ? AccountId : $"{Constants.DefaultMsiAccountIdPrefix}{DefaultManagedServicePort}"; break; default: //Support username + password for both Windows PowerShell and PowerShell 6+ diff --git a/src/Accounts/Accounts/ChangeLog.md b/src/Accounts/Accounts/ChangeLog.md index fa3e8864ca90..647152b9ebb1 100644 --- a/src/Accounts/Accounts/ChangeLog.md +++ b/src/Accounts/Accounts/ChangeLog.md @@ -19,7 +19,8 @@ --> ## Upcoming Release -* Customized display format of PSAzureRmAccount to hide secret of service principal [#14208] +* Removed obsolete parameters `ManagedServiceHostName`, `ManagedServicePort` and `ManagedServiceSecret` of cmdlet `Connect-AzAccount`, environment variables `MSI_ENDPOINT` and `MSI_SECRET` could be used instead +* Customize display format of PSAzureRmAccount to hide secret of service principal [#14208] * Added optional parameter `AuthScope` to `Connect-AzAccount` to support enhanced authentication of data plane features ## Version 2.2.8 diff --git a/src/Accounts/Accounts/help/Connect-AzAccount.md b/src/Accounts/Accounts/help/Connect-AzAccount.md index 66c25cabcfdc..67f1ffb3160e 100644 --- a/src/Accounts/Accounts/help/Connect-AzAccount.md +++ b/src/Accounts/Accounts/help/Connect-AzAccount.md @@ -445,54 +445,6 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ManagedServiceHostName - -Obsolete. To use customized MSI endpoint, please set environment variable MSI_ENDPOINT, e.g. "http://localhost:50342/oauth2/token". Host name for the managed service. - -```yaml -Type: System.String -Parameter Sets: ManagedServiceLogin -Aliases: - -Required: False -Position: Named -Default value: localhost -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ManagedServicePort - -Obsolete. To use customized MSI endpoint, please set environment variable MSI_ENDPOINT, e.g. "http://localhost:50342/oauth2/token".Port number for the managed service. - -```yaml -Type: System.Int32 -Parameter Sets: ManagedServiceLogin -Aliases: - -Required: False -Position: Named -Default value: 50342 -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -ManagedServiceSecret - -Obsolete. To use customized MSI secret, please set environment variable MSI_SECRET. Token for the managed service login. - -```yaml -Type: System.Security.SecureString -Parameter Sets: ManagedServiceLogin -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - ### -MaxContextPopulation Max subscription number to populate contexts after login. Default is 25. To populate all subscriptions to contexts, set to -1. diff --git a/src/Accounts/Authentication.Test/AuthenticationFactoryTests.cs b/src/Accounts/Authentication.Test/AuthenticationFactoryTests.cs index 571b9429239f..f8b989d8a307 100644 --- a/src/Accounts/Authentication.Test/AuthenticationFactoryTests.cs +++ b/src/Accounts/Authentication.Test/AuthenticationFactoryTests.cs @@ -412,170 +412,6 @@ void VerifyToken(IAccessToken checkToken, string expectedAccessToken, string exp }); } - [Fact] - [Trait(Category.AcceptanceType, Category.CheckIn)] - public void AppServiceManagedIdentity() - { - AzureSessionInitializer.InitializeAzureSession(); - var tenant = Guid.NewGuid().ToString(); - var userId = "MSI@2"; - var environment = AzureEnvironment.PublicEnvironments["AzureCloud"]; - var account = new AzureAccount - { - Id = userId, - Type = AzureAccount.AccountType.ManagedService - }; - const string resource = @"https://management.azure.com/"; - const string endpoint = @"http://127.0.0.1:41217/MSI/token/"; - var expectedUri = $"{endpoint}?resource={resource}&api-version=2017-09-01"; - account.SetProperty(AzureAccount.Property.MSILoginUri , endpoint); - account.SetProperty(AzureAccount.Property.MSILoginSecret , @"bar"); - const string expectedAccessToken = "foo"; - var expectedExpiresOn = DateTimeOffset.Parse("1/23/2019 7:15:42 AM +00:00"); - var responses = new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { - expectedUri, - new ManagedServiceAppServiceTokenInfo() - { - AccessToken = expectedAccessToken, - ExpiresOn = expectedExpiresOn, - Resource = resource, - TokenType = "Bearer", - } - } - }; - AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true); - var msat = new ManagedServiceAppServiceAccessToken(account, environment, tenant); - Assert.Equal(expectedUri, msat.RequestUris.Peek()); - var accessToken = msat.AccessToken; - Assert.Equal(expectedAccessToken, accessToken); - Assert.Equal(expectedExpiresOn, msat.ExpiresOn); - } - - [Fact] - [Trait(Category.AcceptanceType, Category.CheckIn)] - public void AppServiceUserManagedIdentityWithDataPlane() - { - AzureSessionInitializer.InitializeAzureSession(); - var tenant = Guid.NewGuid().ToString(); - var userId = Guid.NewGuid().ToString(); - var environment = AzureEnvironment.PublicEnvironments["AzureCloud"]; - var account = new AzureAccount - { - Id = userId, - Type = AzureAccount.AccountType.ManagedService - }; - const string resource = @"https://vault.azure.com/"; - const string endpoint = @"http://127.0.0.1:41217/MSI/token/"; - var expectedUri = $"{endpoint}?resource={resource}&api-version=2017-09-01&clientid={userId}"; - account.SetProperty(AzureAccount.Property.MSILoginUri, endpoint); - account.SetProperty(AzureAccount.Property.MSILoginSecret, @"bar"); - const string expectedAccessToken = "foo"; - var expectedExpiresOn = DateTimeOffset.Parse("1/23/2019 7:15:42 AM +00:00"); - var responses = new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { - expectedUri, - new ManagedServiceAppServiceTokenInfo() - { - AccessToken = expectedAccessToken, - ExpiresOn = expectedExpiresOn, - Resource = resource, - TokenType = "Bearer", - } - } - }; - AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true); - var msat = new ManagedServiceAppServiceAccessToken(account, environment, environment.GetEndpoint(resource) ?? resource, tenant); - Assert.Equal(expectedUri, msat.RequestUris.Peek()); - var accessToken = msat.AccessToken; - Assert.Equal(expectedAccessToken, accessToken); - Assert.Equal(expectedExpiresOn, msat.ExpiresOn); - } - - [Fact] - [Trait(Category.AcceptanceType, Category.CheckIn)] - public void AppServiceManagedIdentityWithDataPlane() - { - AzureSessionInitializer.InitializeAzureSession(); - var tenant = Guid.NewGuid().ToString(); - var userId = "MSI@2"; - var environment = AzureEnvironment.PublicEnvironments["AzureCloud"]; - var account = new AzureAccount - { - Id = userId, - Type = AzureAccount.AccountType.ManagedService - }; - const string resource = @"https://vault.azure.com/"; - const string endpoint = @"http://127.0.0.1:41217/MSI/token/"; - var expectedUri = $"{endpoint}?resource={resource}&api-version=2017-09-01"; - account.SetProperty(AzureAccount.Property.MSILoginUri, endpoint); - account.SetProperty(AzureAccount.Property.MSILoginSecret, @"bar"); - const string expectedAccessToken = "foo"; - var expectedExpiresOn = DateTimeOffset.Parse("1/23/2019 7:15:42 AM +00:00"); - var responses = new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { - expectedUri, - new ManagedServiceAppServiceTokenInfo() - { - AccessToken = expectedAccessToken, - ExpiresOn = expectedExpiresOn, - Resource = resource, - TokenType = "Bearer", - } - } - }; - AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true); - var msat = new ManagedServiceAppServiceAccessToken(account, environment, environment.GetEndpoint(resource) ?? resource, tenant); - Assert.Equal(expectedUri, msat.RequestUris.Peek()); - var accessToken = msat.AccessToken; - Assert.Equal(expectedAccessToken, accessToken); - Assert.Equal(expectedExpiresOn, msat.ExpiresOn); - } - - [Fact] - [Trait(Category.AcceptanceType, Category.CheckIn)] - public void AppServiceManagedIdentityWithServiceManagement() - { - AzureSessionInitializer.InitializeAzureSession(); - var tenant = Guid.NewGuid().ToString(); - var userId = "MSI@2"; - var environment = AzureEnvironment.PublicEnvironments["AzureCloud"]; - var account = new AzureAccount - { - Id = userId, - Type = AzureAccount.AccountType.ManagedService - }; - const string resource = @"https://management.azure.com/"; - const string serviceManagementResource = @"https://management.core.windows.net/"; - const string endpoint = @"http://127.0.0.1:41217/MSI/token/"; - var expectedUri = $"{endpoint}?resource={resource}&api-version=2017-09-01"; - account.SetProperty(AzureAccount.Property.MSILoginUri, endpoint); - account.SetProperty(AzureAccount.Property.MSILoginSecret, @"bar"); - const string expectedAccessToken = "foo"; - var expectedExpiresOn = DateTimeOffset.Parse("1/23/2019 7:15:42 AM +00:00"); - var responses = new Dictionary(StringComparer.OrdinalIgnoreCase) - { - { - expectedUri, - new ManagedServiceAppServiceTokenInfo() - { - AccessToken = expectedAccessToken, - ExpiresOn = expectedExpiresOn, - Resource = resource, - TokenType = "Bearer", - } - } - }; - AzureSession.Instance.RegisterComponent(HttpClientOperationsFactory.Name, () => TestHttpOperationsFactory.Create(responses, _output), true); - var msat = new ManagedServiceAppServiceAccessToken(account, environment, GetFunctionsResourceId(serviceManagementResource, environment), tenant); - Assert.Equal(expectedUri, msat.RequestUris.Peek()); - var accessToken = msat.AccessToken; - Assert.Equal(expectedAccessToken, accessToken); - Assert.Equal(expectedExpiresOn, msat.ExpiresOn); - } private string GetFunctionsResourceId(string resourceIdOrEndpointName, IAzureEnvironment environment) { var resourceId = environment.GetEndpoint(resourceIdOrEndpointName) ?? resourceIdOrEndpointName; diff --git a/src/Accounts/Authentication/Authentication/ManagedServiceAccessToken.cs b/src/Accounts/Authentication/Authentication/ManagedServiceAccessToken.cs deleted file mode 100644 index a8b8af88658c..000000000000 --- a/src/Accounts/Authentication/Authentication/ManagedServiceAccessToken.cs +++ /dev/null @@ -1,36 +0,0 @@ -// ---------------------------------------------------------------------------------- -// -// 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 Microsoft.Azure.Commands.Common.Authentication.Abstractions; -using System; - -namespace Microsoft.Azure.Commands.Common.Authentication -{ - public class ManagedServiceAccessToken : ManagedServiceAccessTokenBase - { - public ManagedServiceAccessToken(IAzureAccount account, IAzureEnvironment environment, string resourceId, string tenant = "organizations") - : base(account, environment, resourceId, tenant) - { - } - - protected override void SetToken(ManagedServiceTokenInfo info) - { - if (info != null) - { - Expiration = DateTimeOffset.Now + TimeSpan.FromSeconds(info.ExpiresIn); - accessToken = info.AccessToken; - } - } - } -} diff --git a/src/Accounts/Authentication/Authentication/ManagedServiceAccessTokenBase.cs b/src/Accounts/Authentication/Authentication/ManagedServiceAccessTokenBase.cs deleted file mode 100644 index cb1b235cb05e..000000000000 --- a/src/Accounts/Authentication/Authentication/ManagedServiceAccessTokenBase.cs +++ /dev/null @@ -1,205 +0,0 @@ -// ---------------------------------------------------------------------------------- -// -// 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; -using System.Collections.Generic; -using System.Net.Http; -using System.Text; -using System.Threading; - -using Microsoft.Azure.Commands.Common.Authentication.Abstractions; -using Microsoft.Azure.Commands.Common.Authentication.Properties; -using Microsoft.Rest.Azure; - -namespace Microsoft.Azure.Commands.Common.Authentication -{ - public abstract class ManagedServiceAccessTokenBase : IRenewableToken where TManagedServiceTokenInfo : class, ICacheable - { - protected readonly IAzureAccount Account; - protected readonly string Tenant; - protected readonly string ResourceId; - protected readonly IHttpOperations TokenGetter; - protected DateTimeOffset Expiration = DateTimeOffset.Now; - protected string accessToken; - - protected ManagedServiceAccessTokenBase(IAzureAccount account, IAzureEnvironment environment, string resourceId, string tenant = "organizations") - { - if (string.IsNullOrWhiteSpace(account?.Id) || !account.IsPropertySet(AzureAccount.Property.MSILoginUri)) - { - throw new ArgumentNullException(nameof(account)); - } - - if (string.IsNullOrWhiteSpace(tenant)) - { - throw new ArgumentNullException(nameof(tenant)); - } - - if (environment == null) - { - throw new ArgumentNullException(nameof(environment)); - } - - Account = account; - ResourceId = GetResource(resourceId, environment); - var idType = GetIdentityType(account); - foreach (var uri in BuildTokenUri(Account.GetProperty(AzureAccount.Property.MSILoginUri), account, idType, ResourceId)) - { - RequestUris.Enqueue(uri); - } - - if (account.IsPropertySet(AzureAccount.Property.MSILoginUriBackup)) - { - foreach (var uri in BuildTokenUri(Account.GetProperty(AzureAccount.Property.MSILoginUriBackup), account, idType, ResourceId)) - { - RequestUris.Enqueue(uri); - } - } - - Tenant = tenant; - if (!AzureSession.Instance.TryGetComponent(HttpClientOperationsFactory.Name, out IHttpOperationsFactory factory)) - { - factory = HttpClientOperationsFactory.Create(); - } - - TokenGetter = factory.GetHttpOperations(true).WithHeader("Metadata", new[] { "true" }); - if (account.IsPropertySet(AzureAccount.Property.MSILoginSecret)) - { - TokenGetter = TokenGetter.WithHeader("Secret", new[] { account.GetProperty(AzureAccount.Property.MSILoginSecret) }); - } - } - - public string AccessToken - { - get - { - try - { - GetOrRenewAuthentication(); - } - catch (CloudException httpException) - { - throw new InvalidOperationException(string.Format(Resources.MSITokenRequestFailed, ResourceId, httpException?.Request?.RequestUri?.ToString()), httpException); - } - - return accessToken; - } - } - - public Queue RequestUris { get; } = new Queue(); - - public string LoginType => "ManagedService"; - - public string TenantId => Tenant; - - public string UserId => Account.Id; - - public DateTimeOffset ExpiresOn => Expiration; - - public string HomeAccountId { get; } = null; - - public IDictionary ExtendedProperties { get; } - - public void AuthorizeRequest(Action authTokenSetter) - { - authTokenSetter("Bearer", AccessToken); - } - - private void GetOrRenewAuthentication() - { - if (Expiration - DateTimeOffset.Now < ManagedServiceTokenInfo.TimeoutThreshold) - { - TManagedServiceTokenInfo info = null; - while (info == null && RequestUris.Count > 0) - { - var currentRequestUri = RequestUris.Dequeue(); - try - { - info = TokenGetter.GetAsync(currentRequestUri, CancellationToken.None).ConfigureAwait(false).GetAwaiter().GetResult(); - // if a request was succesful, we should not check any other Uris - RequestUris.Clear(); - RequestUris.Enqueue(currentRequestUri); - } - catch (Exception e) when ( (e is CloudException || e is HttpRequestException) && RequestUris.Count > 0) - { - // skip to the next uri - } - } - - SetToken(info); - } - } - - protected abstract void SetToken(TManagedServiceTokenInfo info); - - static IdentityType GetIdentityType(IAzureAccount account) - { - if (string.IsNullOrWhiteSpace(account?.Id) || account.Id.Contains("@")) - { - return IdentityType.SystemAssigned; - } - - if (account.Id.Contains("/")) - { - return IdentityType.Resource; - } - - return IdentityType.ClientId; - } - - static string GetResource(string endpointOrResource, IAzureEnvironment environment) - { - return environment.GetEndpoint(endpointOrResource) ?? endpointOrResource; - } - - protected virtual IEnumerable BuildTokenUri(string baseUri, IAzureAccount account, IdentityType identityType, string resourceId) - { - var builder = new UriBuilder(baseUri) {Query = BuildTokenQuery(account, identityType, resourceId)}; - yield return builder.Uri.ToString(); - - if (identityType == IdentityType.ClientId) - { - builder = new UriBuilder(baseUri) {Query = BuildTokenQuery(account, IdentityType.ObjectId, resourceId)}; - yield return builder.Uri.ToString(); - } - } - - static string BuildTokenQuery(IAzureAccount account, IdentityType idType, string resource) - { - StringBuilder query = new StringBuilder($"resource={Uri.EscapeDataString(resource)}"); - switch (idType) - { - case IdentityType.Resource: - query.Append($"&msi_res_id={Uri.EscapeDataString(account.Id)}"); - break; - case IdentityType.ClientId: - query.Append($"&client_id={Uri.EscapeDataString(account.Id)}"); - break; - case IdentityType.ObjectId: - query.Append($"&object_id={Uri.EscapeDataString(account.Id)}"); - break; - } - - query.Append("&api-version=2018-02-01"); - return query.ToString(); - } - - protected enum IdentityType - { - Resource, - ClientId, - ObjectId, - SystemAssigned - } - } -} diff --git a/src/Accounts/Authentication/Authentication/ManagedServiceAppServiceAccessToken.cs b/src/Accounts/Authentication/Authentication/ManagedServiceAppServiceAccessToken.cs deleted file mode 100644 index a06babebb105..000000000000 --- a/src/Accounts/Authentication/Authentication/ManagedServiceAppServiceAccessToken.cs +++ /dev/null @@ -1,56 +0,0 @@ -// ---------------------------------------------------------------------------------- -// -// 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 Microsoft.Azure.Commands.Common.Authentication.Abstractions; -using System; -using System.Collections.Generic; -using System.Text; - -namespace Microsoft.Azure.Commands.Common.Authentication -{ - public class ManagedServiceAppServiceAccessToken : ManagedServiceAccessTokenBase - { - public ManagedServiceAppServiceAccessToken(IAzureAccount account, IAzureEnvironment environment, string tenant = "organizations") - : base(account, environment, @"https://management.azure.com/", tenant) - { - } - - public ManagedServiceAppServiceAccessToken(IAzureAccount account, IAzureEnvironment environment, string resourceId, string tenant = "organizations") - : base(account, environment, resourceId, tenant) - { - } - - protected override IEnumerable BuildTokenUri(string baseUri, IAzureAccount account, IdentityType identityType, - string resourceId) - { - StringBuilder query = new StringBuilder($"{baseUri}?resource={resourceId}&api-version=2017-09-01"); - - if(identityType == IdentityType.ClientId || identityType == IdentityType.ObjectId) - { - query.Append($"&clientid={Uri.EscapeDataString(account.Id)}"); - } - - yield return query.ToString(); - } - - protected override void SetToken(ManagedServiceAppServiceTokenInfo infoWebApps) - { - if (infoWebApps != null) - { - Expiration = infoWebApps.ExpiresOn; - accessToken = infoWebApps.AccessToken; - } - } - } -} diff --git a/src/Accounts/Authentication/Authentication/ManagedServiceAppServiceTokenInfo.cs b/src/Accounts/Authentication/Authentication/ManagedServiceAppServiceTokenInfo.cs deleted file mode 100644 index 4fc6e26289e5..000000000000 --- a/src/Accounts/Authentication/Authentication/ManagedServiceAppServiceTokenInfo.cs +++ /dev/null @@ -1,53 +0,0 @@ -// ---------------------------------------------------------------------------------- -// -// 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; -using Newtonsoft.Json; - -namespace Microsoft.Azure.Commands.Common.Authentication -{ - /// - /// Wire representation of MSI token WebApps ad hoc - /// - public class ManagedServiceAppServiceTokenInfo : ICacheable - { - public static readonly TimeSpan TimeoutThreshold = TimeSpan.FromMinutes(4); - [JsonProperty(PropertyName ="access_token")] - public string AccessToken { get; set; } - - [JsonProperty(PropertyName = "expires_on")] - public DateTimeOffset ExpiresOn { get; set; } - - [JsonProperty(PropertyName = "resource")] - public string Resource { get; set; } - - [JsonProperty(PropertyName = "token_type")] - public string TokenType { get; set; } - - public override string ToString() - { - return $"(AccessToken: {AccessToken}, ExpiresOn: {ExpiresOn}, Resource:{Resource})"; - } - - public bool ShouldCache() - { - return !IsExpired(); - } - - public bool IsExpired() - { - return DateTimeOffset.Now > ExpiresOn - TimeoutThreshold; - } - } -} diff --git a/src/Accounts/Authentication/Factories/AuthenticationFactory.cs b/src/Accounts/Authentication/Factories/AuthenticationFactory.cs index b7a959be731e..3335cdb4959d 100644 --- a/src/Accounts/Authentication/Factories/AuthenticationFactory.cs +++ b/src/Accounts/Authentication/Factories/AuthenticationFactory.cs @@ -325,12 +325,6 @@ public ServiceClientCredentials GetServiceClientCredentials(IAzureContext contex switch (context.Account.Type) { case AzureAccount.AccountType.ManagedService: - token = GetManagedServiceToken( - context.Account, - context.Environment, - tenant, - context.Environment.GetTokenAudience(targetEndpoint)); - break; case AzureAccount.AccountType.User: case AzureAccount.AccountType.ServicePrincipal: token = Authenticate(context.Account, context.Environment, tenant, null, ShowDialog.Never, null, context.Environment.GetTokenAudience(targetEndpoint)); @@ -393,36 +387,6 @@ public void RemoveUser(IAzureAccount account, IAzureTokenCache tokenCache) } } - private IAccessToken GetManagedServiceToken(IAzureAccount account, IAzureEnvironment environment, string tenant, string resourceId) - { - if (environment == null) - { - throw new InvalidOperationException("Environment is required for MSI Login"); - } - - if (!account.IsPropertySet(AzureAccount.Property.MSILoginUri)) - { - account.SetProperty(AzureAccount.Property.MSILoginUri, DefaultMSILoginUri); - } - - if (!account.IsPropertySet(AzureAccount.Property.MSILoginUriBackup)) - { - account.SetProperty(AzureAccount.Property.MSILoginUriBackup, DefaultBackupMSILoginUri); - } - - if (string.IsNullOrWhiteSpace(tenant)) - { - tenant = environment.AdTenant ?? CommonAdTenant; - } - - if (account.IsPropertySet(AuthenticationFactory.AppServiceManagedIdentityFlag)) - { - return new ManagedServiceAppServiceAccessToken(account, environment, GetFunctionsResourceId(resourceId, environment), tenant); - } - - return new ManagedServiceAccessToken(account, environment, GetResourceId(resourceId, environment), tenant); - } - private string GetResourceId(string resourceIdorEndpointName, IAzureEnvironment environment) { return environment.GetEndpoint(resourceIdorEndpointName) ?? resourceIdorEndpointName; diff --git a/tools/StaticAnalysis/Exceptions/Az.Accounts/BreakingChangeIssues.csv b/tools/StaticAnalysis/Exceptions/Az.Accounts/BreakingChangeIssues.csv index 23000ccfc23a..4aebf0232c86 100644 --- a/tools/StaticAnalysis/Exceptions/Az.Accounts/BreakingChangeIssues.csv +++ b/tools/StaticAnalysis/Exceptions/Az.Accounts/BreakingChangeIssues.csv @@ -13,3 +13,7 @@ "Az.Accounts","Microsoft.Azure.Commands.Profile.Context.RenameAzureRmContext","Rename-AzContext","0","2000","The cmdlet 'Rename-AzContext' no longer supports the parameter 'TargetName' and no alias was found for the original parameter name.","Add the parameter 'TargetName' back to the cmdlet 'Rename-AzContext', or add an alias to the original parameter name." "Az.Accounts","Microsoft.Azure.Commands.Profile.Context.SelectAzureRmContext","Select-AzContext","0","2000","The cmdlet 'Select-AzContext' no longer supports the parameter 'Name' and no alias was found for the original parameter name.","Add the parameter 'Name' back to the cmdlet 'Select-AzContext', or add an alias to the original parameter name." "Az.Accounts","Microsoft.Azure.Commands.Profile.Context.SelectAzureRmContext","Select-AzContext","0","1050","The parameter set 'SelectByName' for cmdlet 'Select-AzContext' has been removed.","Add parameter set 'SelectByName' back to cmdlet 'Select-AzContext'." +"Az.Accounts","Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand","Connect-AzAccount","0","2000","The cmdlet 'Connect-AzAccount' no longer supports the parameter 'ManagedServicePort' and no alias was found for the original parameter name.","Add the parameter 'ManagedServicePort' back to the cmdlet 'Connect-AzAccount', or add an alias to the original parameter name." +"Az.Accounts","Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand","Connect-AzAccount","0","2000","The cmdlet 'Connect-AzAccount' no longer supports the parameter 'ManagedServiceHostName' and no alias was found for the original parameter name.","Add the parameter 'ManagedServiceHostName' back to the cmdlet 'Connect-AzAccount', or add an alias to the original parameter name." +"Az.Accounts","Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand","Connect-AzAccount","0","2000","The cmdlet 'Connect-AzAccount' no longer supports the parameter 'ManagedServiceSecret' and no alias was found for the original parameter name.","Add the parameter 'ManagedServiceSecret' back to the cmdlet 'Connect-AzAccount', or add an alias to the original parameter name." +"Az.Accounts","Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand","Connect-AzAccount","0","1050","The parameter set 'ManagedServiceLogin' for cmdlet 'Connect-AzAccount' has been removed.","Add parameter set 'ManagedServiceLogin' back to cmdlet 'Connect-AzAccount'."