Base solution for your next web application
Open Closed

Token Based Authentication WebApi AND Unittest #2587


User avatar
0
michaelhilgers created

Hi,

I ran into an issue when I try to get the token from the TokenAuthController.

I use in my test project the TestServer from the Microsoft.AspNetCore.TestHost Assembly.

I tested my WebApi without the code below to get the Token and all worked fine. After the test I will get a Token to test other function so I implemented the following code:

I created an BaseWebApiClient class an into this class I 'll get the token.

string path = $"/api/TokenAuth/Authenticate";

            AjaxResponse<AuthenticateResultModel> result = new AjaxResponse<AuthenticateResultModel>();

            try
            {
                Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                var serializedString = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(input), Encoding.UTF8, "application/json");

                // Achtung hier funktioniert nur PostAsync und keine PostAsync as Json oder sonstwas
                HttpResponseMessage response = await Client.PostAsync(path, serializedString);

                var json = await response.Content.ReadAsStringAsync();

                if (response.IsSuccessStatusCode)
                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<AjaxResponse<AuthenticateResultModel>>(json);
                else
                    result = new AjaxResponse<AuthenticateResultModel>(Newtonsoft.Json.JsonConvert.DeserializeObject<AjaxResponse<ErrorInfo>>(json).Error);
            }
            catch (Exception e)
            {
                result = new AjaxResponse<AuthenticateResultModel>(new ErrorInfo(e.HResult, e.Message));
            }

            // Token setzen 
            if (result.Success)
            {
                Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.Result.AccessToken);
            }

When I try now to get the token in my Unittest I got multiple Errors:

The First Error was that "Microsoft.IdentityModel.Tokens" wasn't found in the test project => I added the package => work Next Error was that "System.IdentityModel.Tokens.Jwt": wasn't found in the Host.Core ( I added a Host.Core Project for the TestServer => same classes as in Host project ) => Added the package => work

Now I can debug the code in the BaseWebApi an here I got the following response

{Method: POST, RequestUri: 'http://localhost/api/TokenAuth/Authenticate', Version: 1.1, Content: System.Net.Http.StringContent, Headers: { Accept: application/json Accept: application/json Host: localhost Content-Type: application/json; charset=utf-8 }}

All other test passed but I m not able to get a token...

Can you help me please ?


1 Answer(s)