Adding Endpoints with Authorization in separate PublicApi project (#413)

* Adding tests for GetById endpoint

* Updating tests and messages

* Adding paged endpoint and also AutoMapper

* Authenticate endpoint works as bool with tests

* Got JWT token security working with Create and Delete endpoints and Swashbuckle.

* Working on getting cookie and jwt token auth working in the same app
All tests are passing

* Creating new project and moving APIs
Build succeeds; tests need updated.

* all tests passing after moving services to PublicApi project

* Fix authorize attributes

* Uncomment and update ApiCatalogControllerLists tests

Co-authored-by: Eric Fleming <eric-fleming18@hotmail.com>
This commit is contained in:
Steve Smith
2020-06-30 11:36:28 -04:00
committed by GitHub
parent e5e9868003
commit dd5a435cb4
49 changed files with 1024 additions and 75 deletions

View File

@@ -26,6 +26,7 @@
<ItemGroup>
<ProjectReference Include="..\..\src\ApplicationCore\ApplicationCore.csproj" />
<ProjectReference Include="..\..\src\PublicApi\PublicApi.csproj" />
<ProjectReference Include="..\..\src\Web\Web.csproj" />
</ItemGroup>
@@ -33,8 +34,4 @@
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
<ItemGroup>
<Folder Include="Web\ApiEndpoints\" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,79 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.eShopWeb.Infrastructure.Data;
using Microsoft.eShopWeb.Infrastructure.Identity;
using Microsoft.eShopWeb.PublicApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
namespace Microsoft.eShopWeb.FunctionalTests.PublicApi
{
public class ApiTestFixture : WebApplicationFactory<Startup>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureServices(services =>
{
services.AddEntityFrameworkInMemoryDatabase();
// Create a new service provider.
var provider = services
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
// Add a database context (ApplicationDbContext) using an in-memory
// database for testing.
services.AddDbContext<CatalogContext>(options =>
{
options.UseInMemoryDatabase("InMemoryDbForTesting");
options.UseInternalServiceProvider(provider);
});
services.AddDbContext<AppIdentityDbContext>(options =>
{
options.UseInMemoryDatabase("Identity");
options.UseInternalServiceProvider(provider);
});
// Build the service provider.
var sp = services.BuildServiceProvider();
// Create a scope to obtain a reference to the database
// context (ApplicationDbContext).
using (var scope = sp.CreateScope())
{
var scopedServices = scope.ServiceProvider;
var db = scopedServices.GetRequiredService<CatalogContext>();
var loggerFactory = scopedServices.GetRequiredService<ILoggerFactory>();
var logger = scopedServices
.GetRequiredService<ILogger<ApiTestFixture>>();
// Ensure the database is created.
db.Database.EnsureCreated();
try
{
// Seed the database with test data.
CatalogContextSeed.SeedAsync(db, loggerFactory).Wait();
// seed sample user data
var userManager = scopedServices.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = scopedServices.GetRequiredService<RoleManager<IdentityRole>>();
AppIdentityDbContextSeed.SeedAsync(userManager, roleManager).Wait();
}
catch (Exception ex)
{
logger.LogError(ex, $"An error occurred seeding the " +
"database with test messages. Error: {ex.Message}");
}
}
});
}
}
}

View File

@@ -0,0 +1,51 @@
using Microsoft.eShopWeb.ApplicationCore.Constants;
using Microsoft.eShopWeb.Infrastructure.Identity;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace Microsoft.eShopWeb.FunctionalTests.Web.Api
{
public class ApiTokenHelper
{
public static string GetAdminUserToken()
{
string userName = "admin@microsoft.com";
string[] roles = { "Administrators" };
return CreateToken(userName, roles);
}
public static string GetNormalUserToken()
{
string userName = "demouser@microsoft.com";
string[] roles = { };
return CreateToken(userName, roles);
}
private static string CreateToken(string userName, string[] roles)
{
var claims = new List<Claim> { new Claim(ClaimTypes.Name, userName) };
foreach (var role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
var key = Encoding.ASCII.GetBytes(AuthorizationConstants.JWT_SECRET_KEY);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims.ToArray()),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}

View File

@@ -0,0 +1,43 @@
using Microsoft.eShopWeb.ApplicationCore.Constants;
using Microsoft.eShopWeb.FunctionalTests.PublicApi;
using Microsoft.eShopWeb.PublicApi.AuthEndpoints;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers
{
[Collection("Sequential")]
public class AuthenticateEndpoint : IClassFixture<ApiTestFixture>
{
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
public AuthenticateEndpoint(ApiTestFixture factory)
{
Client = factory.CreateClient();
}
public HttpClient Client { get; }
[Theory]
[InlineData("demouser@microsoft.com", AuthorizationConstants.DEFAULT_PASSWORD, true)]
[InlineData("demouser@microsoft.com", "badpassword", false)]
public async Task ReturnsExpectedResultGivenCredentials(string testUsername, string testPassword, bool expectedResult)
{
var request = new AuthenticateRequest()
{
Username = testUsername,
Password = testPassword
};
var jsonContent = new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
var response = await Client.PostAsync("api/authenticate", jsonContent);
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var model = stringResponse.FromJson<AuthenticateResponse>();
Assert.Equal(expectedResult, model.Result);
}
}
}

View File

@@ -1,18 +1,16 @@
using Microsoft.eShopWeb.Web.ViewModels;
using Microsoft.eShopWeb.FunctionalTests.PublicApi;
using Microsoft.eShopWeb.Web.ViewModels;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers
{
[Collection("Sequential")]
public class ApiCatalogControllerList : IClassFixture<WebTestFixture>
public class ApiCatalogControllerList : IClassFixture<ApiTestFixture>
{
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
public ApiCatalogControllerList(WebTestFixture factory)
public ApiCatalogControllerList(ApiTestFixture factory)
{
Client = factory.CreateClient();
}
@@ -22,7 +20,7 @@ namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers
[Fact]
public async Task ReturnsFirst10CatalogItems()
{
var response = await Client.GetAsync("/api/catalog/list");
var response = await Client.GetAsync("/api/catalog-items?pageSize=10");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var model = stringResponse.FromJson<CatalogIndexViewModel>();
@@ -33,7 +31,7 @@ namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers
[Fact]
public async Task ReturnsLast2CatalogItemsGivenPageIndex1()
{
var response = await Client.GetAsync("/api/catalog/list?page=1");
var response = await Client.GetAsync("/api/catalog-items?pageSize=10&pageIndex=1");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var model = stringResponse.FromJson<CatalogIndexViewModel>();

View File

@@ -0,0 +1,78 @@
using Microsoft.eShopWeb.FunctionalTests.PublicApi;
using Microsoft.eShopWeb.FunctionalTests.Web.Api;
using Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers
{
[Collection("Sequential")]
public class CreateEndpoint : IClassFixture<ApiTestFixture>
{
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
private int _testBrandId = 1;
private int _testTypeId = 2;
private string _testDescription = "test description";
private string _testName = "test name";
private string _testUri = "test uri";
private decimal _testPrice = 1.23m;
public CreateEndpoint(ApiTestFixture factory)
{
Client = factory.CreateClient();
}
public HttpClient Client { get; }
[Fact]
public async Task ReturnsNotAuthorizedGivenNormalUserToken()
{
var jsonContent = GetValidNewItemJson();
var token = ApiTokenHelper.GetNormalUserToken();
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await Client.PostAsync("api/catalog-items", jsonContent);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
[Fact]
public async Task ReturnsSuccessGivenValidNewItemAndAdminUserToken()
{
var jsonContent = GetValidNewItemJson();
var adminToken = ApiTokenHelper.GetAdminUserToken();
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", adminToken);
var response = await Client.PostAsync("api/catalog-items", jsonContent);
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var model = stringResponse.FromJson<CreateCatalogItemResponse>();
Assert.Equal(_testBrandId, model.CatalogItem.CatalogBrandId);
Assert.Equal(_testTypeId, model.CatalogItem.CatalogTypeId);
Assert.Equal(_testDescription, model.CatalogItem.Description);
Assert.Equal(_testName, model.CatalogItem.Name);
Assert.Equal(_testUri, model.CatalogItem.PictureUri);
Assert.Equal(_testPrice, model.CatalogItem.Price);
}
private StringContent GetValidNewItemJson()
{
var request = new CreateCatalogItemRequest()
{
CatalogBrandId = _testBrandId,
CatalogTypeId = _testTypeId,
Description = _testDescription,
Name = _testName,
PictureUri = _testUri,
Price = _testPrice
};
var jsonContent = new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
return jsonContent;
}
}
}

View File

@@ -0,0 +1,48 @@
using Microsoft.eShopWeb.FunctionalTests.PublicApi;
using Microsoft.eShopWeb.FunctionalTests.Web.Api;
using Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers
{
[Collection("Sequential")]
public class DeleteEndpoint : IClassFixture<ApiTestFixture>
{
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
public DeleteEndpoint(ApiTestFixture factory)
{
Client = factory.CreateClient();
}
public HttpClient Client { get; }
[Fact]
public async Task ReturnsSuccessGivenValidIdAndAdminUserToken()
{
var adminToken = ApiTokenHelper.GetAdminUserToken();
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", adminToken);
var response = await Client.DeleteAsync("api/catalog-items/12");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var model = stringResponse.FromJson<DeleteCatalogItemResponse>();
Assert.Equal("Deleted", model.Status);
}
[Fact]
public async Task ReturnsNotFoundGivenInvalidIdAndAdminUserToken()
{
var adminToken = ApiTokenHelper.GetAdminUserToken();
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", adminToken);
var response = await Client.DeleteAsync("api/catalog-items/0");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
}

View File

@@ -0,0 +1,43 @@
using Microsoft.eShopWeb.FunctionalTests.PublicApi;
using Microsoft.eShopWeb.PublicApi.CatalogItemEndpoints;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.eShopWeb.FunctionalTests.Web.Controllers
{
[Collection("Sequential")]
public class GetByIdEndpoint : IClassFixture<ApiTestFixture>
{
JsonSerializerOptions _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
public GetByIdEndpoint(ApiTestFixture factory)
{
Client = factory.CreateClient();
}
public HttpClient Client { get; }
[Fact]
public async Task ReturnsItemGivenValidId()
{
var response = await Client.GetAsync("api/catalog-items/5");
response.EnsureSuccessStatusCode();
var stringResponse = await response.Content.ReadAsStringAsync();
var model = stringResponse.FromJson<GetByIdCatalogItemResponse>();
Assert.Equal(5, model.CatalogItem.Id);
Assert.Equal("Roslyn Red Sheet", model.CatalogItem.Name);
}
[Fact]
public async Task ReturnsNotFoundGivenInvalidId()
{
var response = await Client.GetAsync("api/catalog-items/0");
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
}