internal MsalRefreshTokenCacheItem(
     string environment,
     string clientId,
     MsalTokenResponse response,
     string userId = null)
     : this(environment, clientId, response.RefreshToken, response.ClientInfo, response.FamilyId, userId)
 {
 }
예제 #2
0
        private MsalTokenResponse ResultFromBrokerResponse(Dictionary <string, string> responseDictionary)
        {
            MsalTokenResponse brokerTokenResponse;

            string expectedHash       = responseDictionary[iOSBrokerConstants.ExpectedHash];
            string encryptedResponse  = responseDictionary[iOSBrokerConstants.EncryptedResponsed];
            string decryptedResponse  = BrokerKeyHelper.DecryptBrokerResponse(encryptedResponse, _logger);
            string responseActualHash = _cryptoManager.CreateSha256Hash(decryptedResponse);

            byte[] rawHash = Convert.FromBase64String(responseActualHash);
            string hash    = BitConverter.ToString(rawHash);

            if (expectedHash.Equals(hash.Replace("-", ""), StringComparison.OrdinalIgnoreCase))
            {
                responseDictionary = CoreHelpers.ParseKeyValueList(decryptedResponse, '&', false, null);

                if (!ValidateBrokerResponseNonceWithRequestNonce(responseDictionary))
                {
                    return(new MsalTokenResponse
                    {
                        Error = MsalError.BrokerNonceMismatch,
                        ErrorDescription = MsalErrorMessage.BrokerNonceMismatch
                    });
                }

                if (responseDictionary.ContainsKey(iOSBrokerConstants.ApplicationToken))
                {
                    TryWriteBrokerApplicationTokenToKeychain(
                        responseDictionary[BrokerResponseConst.ClientId],
                        responseDictionary[iOSBrokerConstants.ApplicationToken]);
                }

                brokerTokenResponse = MsalTokenResponse.CreateFromiOSBrokerResponse(responseDictionary);

                if (responseDictionary.TryGetValue(BrokerResponseConst.BrokerErrorCode, out string errCode))
                {
                    if (errCode == BrokerResponseConst.iOSBrokerUserCancellationErrorCode)
                    {
                        responseDictionary[BrokerResponseConst.BrokerErrorCode] = MsalError.AuthenticationCanceledError;
                    }
                    else if (errCode == BrokerResponseConst.iOSBrokerProtectionPoliciesRequiredErrorCode)
                    {
                        responseDictionary[BrokerResponseConst.BrokerErrorCode] = MsalError.ProtectionPolicyRequired;
                    }
                }
            }
            else
            {
                brokerTokenResponse = new MsalTokenResponse
                {
                    Error            = MsalError.BrokerResponseHashMismatch,
                    ErrorDescription = MsalErrorMessage.BrokerResponseHashMismatch
                };
            }

            return(brokerTokenResponse);
        }
예제 #3
0
        internal static void SetBrokerResult(Intent data, int resultCode)
        {
            try
            {
                if (data == null)
                {
                    return;
                }

                switch (resultCode)
                {
                case (int)BrokerResponseCode.ResponseReceived:
                    s_androidBrokerTokenResponse =
                        MsalTokenResponse.CreateFromAndroidBrokerResponse(
                            data.GetStringExtra(BrokerConstants.BrokerResultV2),
                            s_correlationId);
                    break;

                case (int)BrokerResponseCode.UserCancelled:
                    s_androidBrokerTokenResponse = new MsalTokenResponse
                    {
                        Error            = MsalError.AuthenticationCanceledError,
                        ErrorDescription = MsalErrorMessage.AuthenticationCanceled,
                    };
                    break;

                case (int)BrokerResponseCode.BrowserCodeError:
                    dynamic errorResult      = JObject.Parse(data.GetStringExtra(BrokerConstants.BrokerResultV2));
                    string  error            = string.Empty;
                    string  errorDescription = string.Empty;

                    if (errorResult != null)
                    {
                        error            = errorResult[BrokerResponseConst.BrokerErrorCode]?.ToString();
                        errorDescription = errorResult[BrokerResponseConst.BrokerErrorMessage]?.ToString();
                    }
                    s_androidBrokerTokenResponse = new MsalTokenResponse
                    {
                        Error            = error,
                        ErrorDescription = errorDescription,
                    };
                    break;

                default:
                    s_androidBrokerTokenResponse = new MsalTokenResponse
                    {
                        Error            = BrokerConstants.BrokerUnknownErrorCode,
                        ErrorDescription = "Broker result not returned from android broker.",
                    };
                    break;
                }
            }
            finally
            {
                s_readyForResponse.Release();
            }
        }
예제 #4
0
        private async Task <MsalTokenResponse> GetTokenResponseAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (_requestParams.AppConfig.IsBrokerEnabled)
            {
                _logger.Info("Broker is configured. Starting broker flow without knowing the broker installation app link. ");

                MsalTokenResponse tokenResponse = await FetchTokensFromBrokerAsync(
                    null, // we don't have an installation URI yet
                    cancellationToken)
                                                  .ConfigureAwait(false);

                // if we don't get back a result, then continue with the WebUi
                if (tokenResponse != null)
                {
                    _logger.Info("Broker attempt completed successfully. ");
                    return(tokenResponse);
                }

                _logger.Info("Broker attempt did not complete, most likely because the broker is not installed. Attempting to use a browser / web UI. ");
                cancellationToken.ThrowIfCancellationRequested();
            }

            IAuthCodeRequestComponent authorizationFetcher =
                _authCodeRequestComponentOverride ??
                new AuthCodeRequestComponent(
                    _requestParams,
                    _interactiveParameters);

            var result = await authorizationFetcher.FetchAuthCodeAndPkceVerifierAsync(cancellationToken)
                         .ConfigureAwait(false);

            _logger.Info("An authorization code was retrieved from the /authorize endpoint. ");
            AuthorizationResult authResult = result.Item1;
            string authCode         = authResult.Code;
            string pkceCodeVerifier = result.Item2;

            if (BrokerInteractiveRequestComponent.IsBrokerRequiredAuthCode(authCode, out string brokerInstallUri))
            {
                return(await RunBrokerWithInstallUriAsync(brokerInstallUri, cancellationToken).ConfigureAwait(false));
            }

            _logger.Info("Exchanging the auth code for tokens. ");
            var authCodeExchangeComponent =
                _authCodeExchangeComponentOverride ??
                new AuthCodeExchangeComponent(
                    _requestParams,
                    _interactiveParameters,
                    authCode,
                    pkceCodeVerifier,
                    authResult.ClientInfo);

            return(await authCodeExchangeComponent.FetchTokensAsync(cancellationToken)
                   .ConfigureAwait(false));
        }
        public void CreateFrtFromTokenResponse()
        {
            MsalTokenResponse response = TestConstants.CreateMsalTokenResponse();

            response.FamilyId = "1";

            var frt = new MsalRefreshTokenCacheItem("env", TestConstants.ClientId, response);

            Assert.AreEqual("1", frt.FamilyId);
        }
        private async Task <MsalTokenResponse> SendAndVerifyResponseAsync()
        {
            CreateRequestParametersForBroker();

            MsalTokenResponse msalTokenResponse =
                await Broker.AcquireTokenUsingBrokerAsync(BrokerPayload).ConfigureAwait(false);

            ValidateResponseFromBroker(msalTokenResponse);
            return(msalTokenResponse);
        }
예제 #7
0
        public async Task SerializeDeserializeCacheTestAsync()
        {
            var serviceBundle         = TestCommon.CreateDefaultServiceBundle();
            ITokenCacheInternal cache = new TokenCache(serviceBundle);

            MsalTokenResponse response = TestConstants.CreateMsalTokenResponse();

            var requestContext = new RequestContext(serviceBundle, Guid.NewGuid());
            var requestParams  = CreateAuthenticationRequestParameters(serviceBundle, requestContext: requestContext);

            requestParams.TenantUpdatedCanonicalAuthority = Authority.CreateAuthorityWithTenant(
                requestParams.AuthorityInfo,
                TestConstants.Utid);
            AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefNetworkEnvironment);

            await cache.SaveTokenResponseAsync(requestParams, response).ConfigureAwait(false);

            byte[] serializedCache = ((ITokenCacheSerializer)cache).SerializeMsalV3();

            cache.Accessor.ClearAccessTokens();
            cache.Accessor.ClearRefreshTokens();

            Assert.AreEqual(0, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(0, cache.Accessor.GetAllAccessTokens().Count());

            ((ITokenCacheSerializer)cache).DeserializeMsalV3(serializedCache);

            Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count());

            serializedCache = ((ITokenCacheSerializer)cache).SerializeMsalV3();
            ((ITokenCacheSerializer)cache).DeserializeMsalV3(serializedCache);
            // item count should not change because old cache entries should have
            // been overriden

            Assert.AreEqual(1, cache.Accessor.GetAllRefreshTokens().Count());
            Assert.AreEqual(1, cache.Accessor.GetAllAccessTokens().Count());

            var atItem = (await cache.GetAllAccessTokensAsync(true).ConfigureAwait(false)).First();

            Assert.AreEqual(response.AccessToken, atItem.Secret);
            Assert.AreEqual(TestConstants.AuthorityTestTenant, atItem.Authority);
            Assert.AreEqual(TestConstants.ClientId, atItem.ClientId);
            Assert.AreEqual(response.Scope, atItem.ScopeSet.AsSingleString());

            // todo add test for idToken serialization
            // Assert.AreEqual(response.IdToken, atItem.RawIdToken);

            var rtItem = (await cache.GetAllRefreshTokensAsync(true).ConfigureAwait(false)).First();

            Assert.AreEqual(response.RefreshToken, rtItem.Secret);
            Assert.AreEqual(TestConstants.ClientId, rtItem.ClientId);
            Assert.AreEqual(TestConstants.s_userIdentifier, rtItem.HomeAccountId);
            Assert.AreEqual(TestConstants.ProductionPrefNetworkEnvironment, rtItem.Environment);
        }
        public async Task <MsalTokenResponse> AcquireTokenInteractiveAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            AcquireTokenInteractiveParameters acquireTokenInteractiveParameters)
        {
            MsalTokenResponse msalTokenResponse = null;

            //need to provide a handle
            if (_parentHandle == IntPtr.Zero)
            {
                throw new MsalClientException(
                          "window_handle_required",
                          "Public Client applications wanting to use WAM need to provide their window handle. Console applications can use GetConsoleWindow Windows API for this.");
            }

            //if OperatingSystemAccount is passed then we use the user signed-in on the machine
            if (PublicClientApplication.IsOperatingSystemAccount(authenticationRequestParameters.Account))
            {
                return(await AcquireTokenInteractiveDefaultUserAsync(authenticationRequestParameters, acquireTokenInteractiveParameters).ConfigureAwait(false));
            }

            var cancellationToken = authenticationRequestParameters.RequestContext.UserCancellationToken;

            _logger.Verbose("[WamBroker] Using Windows account picker.");

            using (var core = new NativeInterop.Core())
                using (var authParams = WamAdapters.GetCommonAuthParameters(authenticationRequestParameters, _wamOptions.MsaPassthrough))
                {
                    //Login Hint
                    string loginHint = authenticationRequestParameters.LoginHint ?? authenticationRequestParameters?.Account?.Username;

                    _logger.Verbose("[WamBroker] AcquireTokenInteractive - login hint provided? " + string.IsNullOrEmpty(loginHint));

                    using (var result = await core.SignInInteractivelyAsync(
                               _parentHandle,
                               authParams,
                               authenticationRequestParameters.CorrelationId.ToString("D"),
                               loginHint,
                               cancellationToken).ConfigureAwait(false))
                    {
                        if (result.IsSuccess)
                        {
                            msalTokenResponse = WamAdapters.ParseRuntimeResponse(result, authenticationRequestParameters, _logger);
                            _logger.Verbose("[WamBroker] Successfully retrieved token.");
                        }
                        else
                        {
                            _logger.Error($"[WamBroker] Could not login interactively. {result.Error}");
                            WamAdapters.ThrowExceptionFromWamError(result, authenticationRequestParameters, _logger);
                        }
                    }
                }

            return(msalTokenResponse);
        }
예제 #9
0
        public JsonTests()
        {
            _oAuth2ResponseBase     = InitOAuth2ResponseBase(new OAuth2ResponseBase());
            _oAuth2ResponseBaseJson = JsonHelper.SerializeToJson <OAuth2ResponseBase>(_oAuth2ResponseBase);

            _msalTokenResponse     = InitMsalTokenResponse(new MsalTokenResponse());
            _msalTokenResponseJson = JsonHelper.SerializeToJson <MsalTokenResponse>(_msalTokenResponse);

            _instanceDiscoveryResponse     = InitInstanceDiscoveryResponse(new InstanceDiscoveryResponse());
            _instanceDiscoveryResponseJson = JsonHelper.SerializeToJson <InstanceDiscoveryResponse>(_instanceDiscoveryResponse);
        }
예제 #10
0
        protected override async Task <AuthenticationResult> ExecuteAsync(
            CancellationToken cancellationToken)
        {
            await ResolveAuthorityAsync().ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();
            MsalTokenResponse tokenResponse = await GetTokenResponseAsync(cancellationToken)
                                              .ConfigureAwait(false);

            return(await CacheTokenResponseAndCreateAuthenticationResultAsync(tokenResponse)
                   .ConfigureAwait(false));
        }
예제 #11
0
        public MsalTokenResponse HandleSilentAuthenticationResult(string silentResult, string correlationId)
        {
            if (!string.IsNullOrEmpty(silentResult))
            {
                return(MsalTokenResponse.CreateFromAndroidBrokerResponse(silentResult, correlationId));
            }

            return(new MsalTokenResponse
            {
                Error = MsalError.BrokerResponseReturnedError,
                ErrorDescription = "[Android broker] Unknown broker error. Failed to acquire token silently from the broker. " + MsalErrorMessage.AndroidBrokerCannotBeInvoked,
            });
        }
예제 #12
0
        private void ValidateBrokerResponse(MsalTokenResponse msalTokenResponse, Action <Exception> validationHandler)
        {
            try
            {
                _brokerInteractiveRequest.ValidateResponseFromBroker(msalTokenResponse);

                Assert.Fail("MsalServiceException should have been thrown here");
            }
            catch (MsalServiceException exc)
            {
                validationHandler(exc);
            }
        }
예제 #13
0
 internal MsalIdTokenCacheItem(
     string environment,
     string clientId,
     MsalTokenResponse response,
     string tenantId)
     : this(
         environment,
         clientId,
         response.IdToken,
         response.ClientInfo,
         tenantId)
 {
 }
 internal MsalRefreshTokenCacheItem(
     string preferredCacheEnv,
     string clientId,
     MsalTokenResponse response,
     string homeAccountId)
     : this(
         preferredCacheEnv,
         clientId,
         response.RefreshToken,
         response.ClientInfo,
         response.FamilyId,
         homeAccountId)
 {
 }
예제 #15
0
        public void JsonDeserializationTest()
        {
            using (var httpManager = new MockHttpManager())
            {
                httpManager.AddSuccessTokenResponseMockHandlerForPost();

                OAuth2Client             client = new OAuth2Client(httpManager, new TelemetryManager());
                Task <MsalTokenResponse> task   = client.GetTokenAsync(
                    new Uri(CoreTestConstants.AuthorityCommonTenant),
                    new RequestContext(null, new MsalLogger(Guid.NewGuid(), null)));
                MsalTokenResponse response = task.Result;
                Assert.IsNotNull(response);
            }
        }
예제 #16
0
        public void GlobalSetup()
        {
            var serviceBundle = TestCommon.CreateServiceBundleWithCustomHttpManager(null, isLegacyCacheEnabled: EnableLegacyCache);

            _cache    = new TokenCache(serviceBundle, false);
            _response = TestConstants.CreateMsalTokenResponse(TestConstants.Utid);

            _requestParams         = TestCommon.CreateAuthenticationRequestParameters(serviceBundle);
            _requestParams.Account = new Account(TestConstants.s_userIdentifier, $"1{TestConstants.DisplayableId}", TestConstants.ProductionPrefNetworkEnvironment);

            AddHostToInstanceCache(serviceBundle, TestConstants.ProductionPrefCacheEnvironment);

            LegacyTokenCacheHelper.PopulateLegacyCache(serviceBundle.ApplicationLogger, _cache.LegacyPersistence, TokenCacheSize);
            TokenCacheHelper.AddRefreshTokensToCache(_cache.Accessor, TokenCacheSize);
        }
예제 #17
0
        public void JsonDeserializationTest()
        {
            using (var harness = CreateTestHarness())
            {
                harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityCommonTenant);

                OAuth2Client client = new OAuth2Client(harness.ServiceBundle.ApplicationLogger, harness.HttpManager);

                Task <MsalTokenResponse> task = client.GetTokenAsync(
                    new Uri(TestConstants.AuthorityCommonTenant + "oauth2/v2.0/token"),
                    new RequestContext(harness.ServiceBundle, Guid.NewGuid()), addCommonHeaders: true, onBeforePostRequestHandler: null);
                MsalTokenResponse response = task.Result;
                Assert.IsNotNull(response);
            }
        }
 internal MsalIdTokenCacheItem(
     string preferredCacheEnv,
     string clientId,
     MsalTokenResponse response,
     string tenantId,
     string homeAccountId)
     : this(
         preferredCacheEnv,
         clientId,
         response.IdToken,
         response.ClientInfo,
         homeAccountId,
         tenantId)
 {
 }
        private async Task AcquireTokenInternalAsync(IDictionary <string, string> brokerPayload)
        {
            _brokerHelper.InitiateBrokerHandshake(_activity);

            Context mContext = Application.Context;

            brokerPayload[BrokerParameter.BrokerAccountName] = AndroidBrokerHelper.GetValueFromBrokerPayload(brokerPayload, BrokerParameter.LoginHint);

            // Don't send silent background request if account information is not provided
            if (!string.IsNullOrEmpty(AndroidBrokerHelper.GetValueFromBrokerPayload(brokerPayload, BrokerParameter.BrokerAccountName)) ||
                !string.IsNullOrEmpty(AndroidBrokerHelper.GetValueFromBrokerPayload(brokerPayload, BrokerParameter.Username)))
            {
                _logger.Verbose("User is specified for silent token request. Starting silent broker request");
                string silentResult = _brokerHelper.GetBrokerAuthTokenSilently(brokerPayload, _activity);
                _androidBrokerTokenResponse = CreateMsalTokenResponseFromResult(silentResult);
                _readyForResponse?.Release();
                return;
            }
            else
            {
                _logger.Verbose("User is not specified for silent token request");
            }

            _logger.Verbose("Starting Android Broker interactive authentication");

            // onActivityResult will receive the response for this activity.
            // Lauching this activity will switch to the broker app.
            Intent brokerIntent = _brokerHelper.GetIntentForInteractiveBrokerRequest(brokerPayload, _activity);

            if (brokerIntent != null)
            {
                try
                {
                    _logger.Info(
                        "Calling activity pid:" + AndroidNative.OS.Process.MyPid()
                        + " tid:" + AndroidNative.OS.Process.MyTid() + "uid:"
                        + AndroidNative.OS.Process.MyUid());

                    _activity.StartActivityForResult(brokerIntent, 1001);
                }
                catch (ActivityNotFoundException e)
                {
                    _logger.ErrorPiiWithPrefix(e, "Unable to get android activity during interactive broker request");
                }
            }

            await _readyForResponse.WaitAsync().ConfigureAwait(false);
        }
        public async Task <MsalTokenResponse> AcquireTokenSilentAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            AcquireTokenSilentParameters acquireTokenSilentParameters)
        {
            var cancellationToken = authenticationRequestParameters.RequestContext.UserCancellationToken;
            MsalTokenResponse msalTokenResponse = null;

            _logger.Verbose("[WamBroker] Acquiring token silently.");

            using (var core = new NativeInterop.Core())
                using (var authParams = WamAdapters.GetCommonAuthParameters(authenticationRequestParameters, _wamOptions.MsaPassthrough))
                {
                    using (var account = await core.ReadAccountByIdAsync(
                               acquireTokenSilentParameters.Account.HomeAccountId.ObjectId,
                               authenticationRequestParameters.CorrelationId.ToString("D"),
                               cancellationToken).ConfigureAwait(false))
                    {
                        if (account == null)
                        {
                            _logger.WarningPii(
                                $"Could not find a WAM account for the selected user {acquireTokenSilentParameters.Account.Username}",
                                "Could not find a WAM account for the selected user");

                            throw new MsalUiRequiredException(
                                      "wam_no_account_for_id",
                                      $"Could not find a WAM account for the selected user {acquireTokenSilentParameters.Account.Username}");
                        }

                        using (NativeInterop.AuthResult result = await core.AcquireTokenSilentlyAsync(
                                   authParams,
                                   authenticationRequestParameters.CorrelationId.ToString("D"),
                                   account,
                                   cancellationToken).ConfigureAwait(false))
                        {
                            if (result.IsSuccess)
                            {
                                msalTokenResponse = WamAdapters.ParseRuntimeResponse(result, authenticationRequestParameters, _logger);
                            }
                            else
                            {
                                WamAdapters.ThrowExceptionFromWamError(result, authenticationRequestParameters, _logger);
                            }
                        }
                    }
                }

            return(msalTokenResponse);
        }
 internal MsalAccessTokenCacheItem(
     string environment,
     string clientId,
     MsalTokenResponse response,
     string tenantId)
     : this(
         environment,
         clientId,
         response.Scope,
         tenantId,
         response.AccessToken,
         response.AccessTokenExpiresOn,
         response.AccessTokenExtendedExpiresOn,
         response.ClientInfo)
 {
 }
예제 #22
0
 internal MsalIdTokenCacheItem(
     string preferredCacheEnv,
     string clientId,
     MsalTokenResponse response,
     string tenantId,
     string userId = null
     )
     : this(
         preferredCacheEnv,
         clientId,
         response.IdToken,
         response.ClientInfo,
         tenantId,
         userId)
 {
 }
예제 #23
0
        private MsalTokenResponse InitMsalTokenResponse(MsalTokenResponse msalTokenResponse)
        {
            msalTokenResponse.TokenType         = "token type";
            msalTokenResponse.AccessToken       = "access token";
            msalTokenResponse.RefreshToken      = "refresh token";
            msalTokenResponse.Scope             = "scope scope";
            msalTokenResponse.ClientInfo        = "client info";
            msalTokenResponse.IdToken           = "id token";
            msalTokenResponse.ExpiresIn         = 123;
            msalTokenResponse.ExtendedExpiresIn = 12345;
            msalTokenResponse.RefreshIn         = 12333;
            msalTokenResponse.FamilyId          = "family id";

            InitOAuth2ResponseBase(msalTokenResponse);

            return(msalTokenResponse);
        }
예제 #24
0
        public async Task <MsalTokenResponse> SendTokenRequestToBrokerAsync()
        {
            if (Broker != null && !Broker.IsBrokerInstalledAndInvokable())
            {
                throw new MsalClientException(MsalError.BrokerApplicationRequired, MsalErrorMessage.AndroidBrokerCannotBeInvoked);
            }

            _authenticationRequestParameters.RequestContext.Logger.Info(LogMessages.CanInvokeBrokerAcquireTokenWithBroker);

            MsalTokenResponse msalTokenResponse =
                await Broker.AcquireTokenSilentAsync(
                    _authenticationRequestParameters,
                    _silentParameters).ConfigureAwait(false);

            ValidateResponseFromBroker(msalTokenResponse);
            return(msalTokenResponse);
        }
        internal static MsalServiceException FromBrokerResponse(
            MsalTokenResponse msalTokenResponse,
            string errorMessage)
        {
            string errorCode     = msalTokenResponse.Error;
            string correlationId = msalTokenResponse.CorrelationId;
            string subErrorCode  = string.IsNullOrEmpty(msalTokenResponse.SubError)?
                                   MsalError.UnknownBrokerError : msalTokenResponse.SubError;
            HttpResponse         brokerHttpResponse = msalTokenResponse.HttpResponse;
            MsalServiceException ex = null;

            if (IsAppProtectionPolicyRequired(errorCode, subErrorCode))
            {
                ex = new IntuneAppProtectionPolicyRequiredException(errorCode, subErrorCode)
                {
                    Upn           = msalTokenResponse.Upn,
                    AuthorityUrl  = msalTokenResponse.AuthorityUrl,
                    TenantId      = msalTokenResponse.TenantId,
                    AccountUserId = msalTokenResponse.AccountUserId,
                };
            }

            if (IsInvalidGrant(errorCode, subErrorCode) || IsInteractionRequired(errorCode))
            {
                ex = new MsalUiRequiredException(errorCode, errorMessage);
            }

            if (string.Equals(errorCode, MsalError.InvalidClient, StringComparison.OrdinalIgnoreCase))
            {
                ex = new MsalServiceException(
                    MsalError.InvalidClient,
                    MsalErrorMessage.InvalidClient + " Original exception: " + errorMessage);
            }

            if (ex == null)
            {
                ex = new MsalServiceException(errorCode, errorMessage);
            }

            SetHttpExceptionData(ex, brokerHttpResponse);

            ex.CorrelationId = correlationId;
            ex.SubError      = subErrorCode;

            return(ex);
        }
        internal static void SetBrokerResult(Intent data, int resultCode)
        {
            try
            {
                if (data == null)
                {
                    return;
                }

                switch (resultCode)
                {
                case (int)BrokerResponseCode.ResponseReceived:
                    s_androidBrokerTokenResponse = CreateMsalTokenResponseFromResult(data.GetStringExtra(BrokerConstants.BrokerResultV2));
                    break;

                case (int)BrokerResponseCode.UserCancelled:
                    s_androidBrokerTokenResponse = new MsalTokenResponse
                    {
                        Error            = MsalError.AuthenticationCanceledError,
                        ErrorDescription = MsalErrorMessage.AuthenticationCanceled,
                    };
                    break;

                case (int)BrokerResponseCode.BrowserCodeError:
                    s_androidBrokerTokenResponse = new MsalTokenResponse
                    {
                        Error            = data.GetStringExtra(BrokerConstants.BrokerResultErrorCode),
                        ErrorDescription = data.GetStringExtra(BrokerConstants.BrokerResultV2),
                    };
                    break;

                default:
                    s_androidBrokerTokenResponse = new MsalTokenResponse
                    {
                        Error            = BrokerConstants.BrokerUnknownErrorCode,
                        ErrorDescription = "Broker result not returned from android broker.",
                    };
                    break;
                }
            }
            finally
            {
                s_readyForResponse.Release();
            }
        }
예제 #27
0
        private async Task <AuthenticationResult> RefreshRtOrFailAsync(CancellationToken cancellationToken)
        {
            // Try FOCI first
            MsalTokenResponse msalTokenResponse = await TryGetTokenUsingFociAsync(cancellationToken)
                                                  .ConfigureAwait(false);

            // Normal, non-FOCI flow
            if (msalTokenResponse == null)
            {
                // Look for a refresh token
                MsalRefreshTokenCacheItem appRefreshToken = await FindRefreshTokenOrFailAsync()
                                                            .ConfigureAwait(false);

                msalTokenResponse = await RefreshAccessTokenAsync(appRefreshToken, cancellationToken)
                                    .ConfigureAwait(false);
            }
            return(await CacheTokenResponseAndCreateAuthenticationResultAsync(msalTokenResponse).ConfigureAwait(false));
        }
예제 #28
0
        internal TokenResponse(
            MsalTokenResponse mtr,
            ITimeService timeService = null)
        {
            var timeSvc = timeService ?? new TimeService();

            AccessToken  = mtr.AccessToken;
            RefreshToken = mtr.RefreshToken;
            IdToken      = new IdToken(mtr.IdToken);
            Scopes       = ScopeUtils.Split(mtr.Scope);
            var clientInfo = ClientInfo.Create(EncodingUtils.Base64UrlDecodeUnpadded(mtr.ClientInfo));

            ExpiresOn         = timeSvc.GetUtcNow().AddSeconds(mtr.ExpiresIn);
            ExtendedExpiresOn = timeSvc.GetUtcNow().AddSeconds(mtr.ExtendedExpiresIn);

            Uid  = clientInfo.UniqueObjectIdentifier;
            Utid = clientInfo.UniqueTenantIdentifier;
        }
 internal MsalAccessTokenCacheItem(
     string preferredCacheEnv,
     string clientId,
     MsalTokenResponse response,
     string tenantId,
     string userId = null)
     : this(
         preferredCacheEnv,
         clientId,
         response.Scope,
         tenantId,
         response.AccessToken,
         response.AccessTokenExpiresOn,
         response.AccessTokenExtendedExpiresOn,
         response.ClientInfo,
         userId)
 {
 }
        public void JsonDeserializationTest()
        {
            using (var harness = CreateTestHarness())
            {
                harness.HttpManager.AddSuccessTokenResponseMockHandlerForPost(TestConstants.AuthorityCommonTenant);

                OAuth2Client client = new OAuth2Client(harness.ServiceBundle.DefaultLogger, harness.HttpManager, new TelemetryManager(
                                                           harness.ServiceBundle.Config,
                                                           harness.ServiceBundle.PlatformProxy,
                                                           null));

                Task <MsalTokenResponse> task = client.GetTokenAsync(
                    new Uri(TestConstants.AuthorityCommonTenant + "oauth2/v2.0/token"),
                    new RequestContext(harness.ServiceBundle, Guid.NewGuid()));
                MsalTokenResponse response = task.Result;
                Assert.IsNotNull(response);
            }
        }