Пример #1
0
        public async Task POST_Should_Login_And_Return_Valid_Access_And_Refresh_Tokens()
        {
            /*
             * HttpPost("users/login")
             * Login and use the newly recieved tokens to make api call and refresh.
             * Similar to refresh accept in the method we get our tokens. In refresh we generate
             * our first tokens through code and strictly test the refresh endpoint, then validate the tokens recieved from refresh.
             * Here, we get our tokens from the login endpoint and make sure they work as expected.
             *
             */

            // variable for managing our responses
            HttpResponseMessage response;

            // make a login request and validate response code
            using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, _client.BaseAddress + "users/login"))
            {
                Login login = new Login {
                    Email = _retTestUser.Email, Password = "******"
                };                                                                                                                 // the original user
                requestMessage.Content = new StringContent(JsonConvert.SerializeObject(login), Encoding.UTF8, "application/json"); // set content
                response = await _client.SendAsync(requestMessage);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }

            // valid cookies presence, retrieve, and create a cookie header string
            Dictionary <string, string> new_cookies = TestingHelpingMethods.CheckForCookies(response);
            string cookie = "AccessTokenSameSite=" + new_cookies.Single(a => a.Key == "AccessTokenSameSite").Value
                            + "; RefreshTokenSameSite=" + new_cookies.Single(a => a.Key == "RefreshTokenSameSite").Value;

            // check that we recieved a valid login response
            JObject responseBody = await TestingHelpingMethods.CheckForLoginResponse(response);

            // make a call to the api to make sure we recieved a valid access token
            using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, _client.BaseAddress + "users/" + responseBody["id"].ToString()))
            {
                requestMessage.Headers.Add("Cookie", cookie); // set new access and refresh tokens in cookies
                response = await _client.SendAsync(requestMessage);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }

            // make a call to refresh and check for 200 status code.. we dont need to validate refesh in anyway here
            using (var requestMessage = new HttpRequestMessage(HttpMethod.Get, _client.BaseAddress + "users/" + responseBody["id"].ToString()))
            {
                requestMessage.Headers.Add("Cookie", cookie); // set new access and refresh tokens in cookies
                response = await _client.SendAsync(requestMessage);

                Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            }
        }
        public async Task POST_Should_Return_New_Valid_Cookies()
        {
            /*
             * HttpPost("refresh")
             * For this test we need a valid refresh token, and an access token that is expired or not.
             * Then make a call to refresh and use the received tokens to see if we can make a valid call to the api.
             * And finally we make a call to validateRefreshToken to make sure the newly generated refresh was stored in the DB
             */

            // get reference to app settings and local db
            var config = new ConfigurationBuilder().AddJsonFile("appsettings.Development.json").Build();
            DbContextOptions <APIContext> options = new DbContextOptions <APIContext>();
            APIContext context = new APIContext(options, config);

            // generate an access token and valid refresh token
            string[] keyAndIV               = { config.GetValue <string>("UserEncryptionKey"), config.GetValue <string>("UserEncryptionIV") }; // for user encryption there is a single key
            User     user                   = context.Users.Single(a => a.Email.SequenceEqual(HelperMethods.EncryptStringToBytes_Aes("*****@*****.**", keyAndIV)));
            string   accessToken            = HelperMethods.GenerateJWTAccessToken(user.ID, config["UserJwtTokenKey"]);
            ReturnableRefreshToken refToken = new ReturnableRefreshToken(HelperMethods.GenerateRefreshToken(user, context));

            // set cookies in header
            string cookie = "AccessToken=" + accessToken + "; RefreshToken=" + refToken.Token;

            _client.DefaultRequestHeaders.Add("Cookie", cookie);

            // send request to refresh and assert request is ok and new cookies are present
            var response = await _client.PostAsync("refresh", null);

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            // valid cookies presence and retrieve
            Dictionary <string, string> new_cookies = TestingHelpingMethods.CheckForCookies(response);

            // check that we recieved a valid login response
            JObject responseBody = await TestingHelpingMethods.CheckForLoginResponse(response);

            // set new access token in cookies
            _client.DefaultRequestHeaders.Remove("Cookie");
            cookie = "AccessTokenSameSite=" + new_cookies.Single(a => a.Key == "AccessTokenSameSite").Value;
            _client.DefaultRequestHeaders.Add("Cookie", cookie);

            // make a call to the api to make sure we recieved a valid access token
            response = await _client.GetAsync("users/" + responseBody["id"].ToString());

            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            // and the last thing we need is to validate that the refresh token was stored in the DB
            context.Dispose();                                                                                                                                 // close old connection
            user = new APIContext(options, config).Users.Single(a => a.Email.SequenceEqual(HelperMethods.EncryptStringToBytes_Aes("*****@*****.**", keyAndIV))); // get fresh handle of user from the DB
            Assert.True(HelperMethods.ValidateRefreshToken(user, new_cookies.Single(a => a.Key == "RefreshTokenSameSite").Value));
        }