<commit_before>﻿// ----------------------------------------------------------------------------------
// 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 Hyak.Common;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.Azure.Common.Authentication.Properties;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Security;

namespace Microsoft.Azure.Common.Authentication
{
    internal class ServicePrincipalTokenProvider : ITokenProvider
    {
        private static readonly TimeSpan expirationThreshold = TimeSpan.FromMinutes(5);

        public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
            AzureAccount.AccountType credentialType)
        {
            if (credentialType == AzureAccount.AccountType.User)
            {
                throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType");
            }
            return new ServicePrincipalAccessToken(config, AcquireToken(config, userId, password), this, userId);
        }

        private AuthenticationResult AcquireToken(AdalConfiguration config, string appId, SecureString appKey)
        {
            if (appKey == null)
            {
                return Renew(config, appId);
            }

            StoreAppKey(appId, config.AdDomain, appKey);

            string authority = config.AdEndpoint + config.AdDomain;
            var context = new AuthenticationContext(authority, config.ValidateAuthority, config.TokenCache);
            var credential = new ClientCredential(appId, appKey);
            return context.AcquireToken("https://management.core.windows.net/", credential);
        }

        private AuthenticationResult Renew(AdalConfiguration config, string appId)
        {
            TracingAdapter.Information(Resources.SPNRenewTokenTrace, appId, config.AdDomain, config.AdEndpoint, 
                config.ClientId, config.ClientRedirectUri);
           using (SecureString appKey = LoadAppKey(appId, config.AdDomain))
            {
                if (appKey == null)
                {
                    throw new KeyNotFoundException(string.Format(Resources.ServiceKeyNotFound, appId));
                }
                return AcquireToken(config, appId, appKey);
            }
        }

        private SecureString LoadAppKey(string appId, string tenantId)
        {
            return ServicePrincipalKeyStore.GetKey(appId, tenantId);
        }

        private void StoreAppKey(string appId, string tenantId, SecureString appKey)
        {
            ServicePrincipalKeyStore.SaveKey(appId, tenantId, appKey);
        }<commit_msg>Fix hard-coded SP resource uri issue<commit_after>﻿// ----------------------------------------------------------------------------------
// 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 Hyak.Common;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.Azure.Common.Authentication.Properties;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Security;

namespace Microsoft.Azure.Common.Authentication
{
    internal class ServicePrincipalTokenProvider : ITokenProvider
    {
        private static readonly TimeSpan expirationThreshold = TimeSpan.FromMinutes(5);

        public IAccessToken GetAccessToken(AdalConfiguration config, ShowDialog promptBehavior, string userId, SecureString password,
            AzureAccount.AccountType credentialType)
        {
            if (credentialType == AzureAccount.AccountType.User)
            {
                throw new ArgumentException(string.Format(Resources.InvalidCredentialType, "User"), "credentialType");
            }
            return new ServicePrincipalAccessToken(config, AcquireToken(config, userId, password), this, userId);
        }

        private AuthenticationResult AcquireToken(AdalConfiguration config, string appId, SecureString appKey)
        {
            if (appKey == null)
            {
                return Renew(config, appId);
            }

            StoreAppKey(appId, config.AdDomain, appKey);

            string authority = config.AdEndpoint + config.AdDomain;
            var context = new AuthenticationContext(authority, config.ValidateAuthority, config.TokenCache);
            var credential = new ClientCredential(appId, appKey);
            return context.AcquireToken(config.ResourceClientUri, credential);
        }

        private AuthenticationResult Renew(AdalConfiguration config, string appId)
        {
            TracingAdapter.Information(Resources.SPNRenewTokenTrace, appId, config.AdDomain, config.AdEndpoint, 
                config.ClientId, config.ClientRedirectUri);
           using (SecureString appKey = LoadAppKey(appId, config.AdDomain))
            {
                if (appKey == null)
                {
                    throw new KeyNotFoundException(string.Format(Resources.ServiceKeyNotFound, appId));
                }
                return AcquireToken(config, appId, appKey);
            }
        }

        private SecureString LoadAppKey(string appId, string tenantId)
        {
            return ServicePrincipalKeyStore.GetKey(appId, tenantId);
        }

        private void StoreAppKey(string appId, string tenantId, SecureString appKey)
        {
            ServicePrincipalKeyStore.SaveKey(appId, tenantId, appKey);
        }
{'fraction_non_alphanumeric': 0.1217197924388436, 'fraction_numerical': 0.0014825796886582653, 'mean_word_length': 2.3166175024582105, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 1, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5940405', 'n_tokens_mistral': 1566, 'n_tokens_neox': 1515, 'n_words': 443}