diff options
author | 杨宇千 <crupest@outlook.com> | 2019-05-06 14:22:10 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-05-06 14:22:10 +0800 |
commit | 79dc38059819cf6dbcb8533b031f9a0dba8f6cb1 (patch) | |
tree | 37c2b6f9dcb3d6f57867ebc7538523d1a338183d /Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs | |
parent | 1cb92b8f2a98005b793c00e0191903c0792d540a (diff) | |
parent | a04bcb5971872e7dbc079de9337875e73f7642dc (diff) | |
download | timeline-79dc38059819cf6dbcb8533b031f9a0dba8f6cb1.tar.gz timeline-79dc38059819cf6dbcb8533b031f9a0dba8f6cb1.tar.bz2 timeline-79dc38059819cf6dbcb8533b031f9a0dba8f6cb1.zip |
Merge pull request #22 from crupest/user-admin
Develop user management feature.
Diffstat (limited to 'Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs')
-rw-r--r-- | Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs b/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs new file mode 100644 index 00000000..cda9fe99 --- /dev/null +++ b/Timeline.Tests/Helpers/Authentication/AuthenticationExtensions.cs @@ -0,0 +1,47 @@ +using Microsoft.AspNetCore.Mvc.Testing; +using Newtonsoft.Json; +using System; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +using Timeline.Entities.Http; +using Xunit; + +namespace Timeline.Tests.Helpers.Authentication +{ + public static class AuthenticationExtensions + { + private const string CreateTokenUrl = "/token/create"; + + public static async Task<CreateTokenResponse> CreateUserTokenAsync(this HttpClient client, string username, string password, bool assertSuccess = true) + { + var response = await client.PostAsJsonAsync(CreateTokenUrl, new CreateTokenRequest { Username = username, Password = password }); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + var result = JsonConvert.DeserializeObject<CreateTokenResponse>(await response.Content.ReadAsStringAsync()); + if (assertSuccess) + Assert.True(result.Success); + + return result; + } + + public static async Task<HttpClient> CreateClientWithUser<T>(this WebApplicationFactory<T> factory, string username, string password) where T : class + { + var client = factory.CreateDefaultClient(); + var token = (await client.CreateUserTokenAsync(username, password)).Token; + client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); + return client; + } + + public static async Task<HttpResponseMessage> SendWithAuthenticationAsync(this HttpClient client, string token, string path, Action<HttpRequestMessage> requestBuilder = null) + { + var request = new HttpRequestMessage + { + RequestUri = new Uri(client.BaseAddress, path), + }; + request.Headers.Add("Authorization", "Bearer " + token); + requestBuilder?.Invoke(request); + return await client.SendAsync(request); + } + } +} |