private static void AddHttpMocks(TokenResponseType aadResponse, MockHttpManager httpManager, bool pca)
        {
            httpManager.AddInstanceDiscoveryMockHandler();
            httpManager.AddMockHandlerForTenantEndpointDiscovery(
                pca ? TestConstants.AuthorityUtidTenant : TestConstants.AadAuthorityWithTestTenantId);

            AddTokenResponse(aadResponse, httpManager);
        }
示例#2
0
        private static void AddHttpMocks(TokenResponseType aadResponse, MockHttpManager httpManager)
        {
            httpManager.AddInstanceDiscoveryMockHandler();
            httpManager.AddMockHandlerForTenantEndpointDiscovery(
                TestConstants.AuthorityUtidTenant);

            AddTokenResponse(aadResponse, httpManager);
        }
示例#3
0
        public static MockHttpMessageHandler AddTokenResponse(
            this MockHttpManager httpManager,
            TokenResponseType responseType,
            IDictionary <string, string> expectedRequestHeaders = null)
        {
            HttpResponseMessage responseMessage;

            switch (responseType)
            {
            case TokenResponseType.Valid_UserFlows:
                responseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                    TestConstants.Uid,
                    TestConstants.DisplayableId,
                    TestConstants.s_scope.ToArray());

                break;

            case TokenResponseType.Valid_ClientCredentials:
                responseMessage = MockHelpers.CreateSuccessfulClientCredentialTokenResponseMessage();

                break;

            case TokenResponseType.Invalid_AADUnavailable503:
                responseMessage = MockHelpers.CreateFailureMessage(
                    System.Net.HttpStatusCode.ServiceUnavailable, "service down");

                break;

            case TokenResponseType.InvalidGrant:
                responseMessage = MockHelpers.CreateInvalidGrantTokenResponseMessage();
                break;

            case TokenResponseType.InvalidClient:

                responseMessage = MockHelpers.CreateInvalidClientResponseMessage();
                break;

            default:
                throw new NotImplementedException();
            }

            var responseHandler = new MockHttpMessageHandler()
            {
                ExpectedMethod         = HttpMethod.Post,
                ExpectedRequestHeaders = expectedRequestHeaders,
                ResponseMessage        = responseMessage,
            };

            httpManager.AddMockHandler(responseHandler);

            return(responseHandler);
        }
        private static void AddTokenResponse(TokenResponseType aadResponse, MockHttpManager httpManager)
        {
            switch (aadResponse)
            {
            case TokenResponseType.Valid:
                var refreshHandler = new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage(
                        TestConstants.UniqueId,
                        TestConstants.DisplayableId,
                        TestConstants.s_scope.ToArray())
                };
                httpManager.AddMockHandler(refreshHandler);
                break;

            case TokenResponseType.Invalid_AADUnavailable:
                var refreshHandler1 = new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateFailureMessage(
                        System.Net.HttpStatusCode.GatewayTimeout, "gateway timeout")
                };
                var refreshHandler2 = new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateFailureMessage(
                        System.Net.HttpStatusCode.GatewayTimeout, "gateway timeout")
                };

                // MSAL retries once for errors in the 500 - 600 range
                httpManager.AddMockHandler(refreshHandler1);
                httpManager.AddMockHandler(refreshHandler2);
                break;

            case TokenResponseType.Invalid_AADAvailable:
                var handler = new MockHttpMessageHandler()
                {
                    ExpectedMethod  = HttpMethod.Post,
                    ResponseMessage = MockHelpers.CreateInvalidGrantTokenResponseMessage()
                };

                httpManager.AddMockHandler(handler);
                break;

            default:
                throw new NotImplementedException();
            }
        }
        private async Task <PublicClientApplication> SetupAndAcquireOnceAsync(
            MockHttpAndServiceBundle httpManagerAndBundle,
            int httpStatusCode,
            int?retryAfterInSeconds,
            TokenResponseType tokenResponseType)
        {
            Trace.WriteLine("1. Setup test");
            var httpManager = httpManagerAndBundle.HttpManager;

            PublicClientApplication app = PublicClientApplicationBuilder.Create(TestConstants.ClientId)
                                          .WithHttpManager(httpManager)
                                          .BuildConcrete();

            new TokenCacheHelper().PopulateCache(app.UserTokenCacheInternal.Accessor, expiredAccessTokens: true);

            var tokenResponse = httpManager.AddAllMocks(tokenResponseType);

            UpdateStatusCodeAndHeaders(tokenResponse.ResponseMessage, httpStatusCode, retryAfterInSeconds);

            if (httpStatusCode >= 500 && httpStatusCode < 600 && !retryAfterInSeconds.HasValue)
            {
                var response2 = httpManager.AddTokenResponse(
                    tokenResponseType, s_throttlingHeader);
                UpdateStatusCodeAndHeaders(response2.ResponseMessage, httpStatusCode, retryAfterInSeconds);
            }

            var account = (await app.GetAccountsAsync().ConfigureAwait(false)).Single();

            Trace.WriteLine("2. First failing call ");
            var ex = await AssertException.TaskThrowsAsync <MsalServiceException>(
                () => app.AcquireTokenSilent(TestConstants.s_scope, account).ExecuteAsync(),
                allowDerived : true)
                     .ConfigureAwait(false);

            Assert.AreEqual(0, httpManager.QueueSize, "No more requests expected");
            Assert.AreEqual(httpStatusCode, ex.StatusCode);
            Assert.AreEqual(tokenResponseType == TokenResponseType.InvalidGrant, ex is MsalUiRequiredException);

            return(app);
        }
示例#6
0
        /// <summary>
        /// ValidateUserToken: request toke is valide or not
        /// if toke is valide to update with null value
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public TokenResponseType ValidateUserToken(User user)
        {
            TokenResponseType tokenResponseType = new TokenResponseType();

            if (ValidateToken(user))
            {
                User userToUpdate = userDBContext
                                    .Users.SingleOrDefault(x => x.AccessToken == user.AccessToken);

                userToUpdate.AccessToken = null;;
                userDBContext.SaveChanges();
                tokenResponseType.ErrorMsg     = "success";
                tokenResponseType.UserName     = userToUpdate.UserName;
                tokenResponseType.PasswordHash = userToUpdate.PasswordHash;
            }
            else
            {
                tokenResponseType.ErrorMsg     = "AccessToken does not exists!!";
                tokenResponseType.UserName     = "";
                tokenResponseType.PasswordHash = "";
            }
            return(tokenResponseType);
        }
示例#7
0
 public HttpResponseMessage AuthToken([FromBody] User user)
 {
     try
     {
         UserRepository    obj      = new UserRepository();
         TokenResponseType Response = obj.ValidateUserToken(user);
         if (Response.ErrorMsg == "success")
         {
             return(Request.CreateResponse(HttpStatusCode.OK, Response));
         }
         else
         {
             return(Request.CreateResponse(HttpStatusCode.InternalServerError, Response));
         }
     }
     catch (Exception ex)
     {
         return(Request.CreateResponse(HttpStatusCode.InternalServerError,
                                       new TokenResponseType()
         {
             ErrorMsg = "Access Token Required", PasswordHash = "", UserName = ""
         }));
     }
 }
示例#8
0
 public static MockHttpMessageHandler AddAllMocks(this MockHttpManager httpManager, TokenResponseType aadResponse)
 {
     httpManager.AddInstanceDiscoveryMockHandler();
     return(AddTokenResponse(httpManager, aadResponse));
 }
示例#9
0
        public static MockHttpMessageHandler AddAllMocks(this MockHttpManager httpManager, TokenResponseType aadResponse)
        {
            httpManager.AddInstanceDiscoveryMockHandler();
            httpManager.AddMockHandlerForTenantEndpointDiscovery(
                TestConstants.AuthorityUtidTenant);

            return(AddTokenResponse(httpManager, aadResponse));
        }