I have a controller that is taking a JWT Claim, and if the claim is correct, then I am returing a Json string of categories as follows :-
[Authorize(Policy = "OnlyValidUsers")]
[Route("api/[controller]")]
public class CategoriesController : Controller
{
private readonly IGenericService<Category> _categoriesService;
public CategoriesController(IGenericService<Category> categoriesService)
{
_categoriesService = categoriesService;
}
[Authorize(Policy = "GenericUser")]
[HttpGet("/api/Categories/Get", Name = "GetCategories")]
public async Task<IActionResult> Get()
{
var categories = await _categoriesService.GetAll();
return Json(categories);
}
}
This happens after the user logins in to my system, and gets a bearer token.
I am trying to test that in an integration test as follows:-
[TestFixture]
public class CategoriesControllerIntegrationTests
{
private HttpClient _client;
private Category _testCategory;
private string _request;
[SetUp]
public void Setup()
{
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var projectPath = Path.GetFullPath(Path.Combine(basePath, "../../../../SportsStore.Tests"));
var server = new TestServer(Utils.GetHostBuilder(new string[] { })
.UseContentRoot(projectPath)
.UseEnvironment("Development")
.UseStartup<Startup>());
_client = server.CreateClient();
_testCategory = new Category
{
Name = Enums.GetEnumDescription(Enums.CategoryTestData.Name)
};
_request = Enums.GetEnumDescription(Enums.Requests.Categories);
}
[Test]
public async Task Get_ReturnsAListOfCategories_CategoriesController()
{
var response = await _client.GetAsync(_request + "Get");
response.EnsureSuccessStatusCode();
Assert.IsTrue(true);
}
The Utils class is as follows:-
public class Utils
{
public static IWebHostBuilder GetHostBuilder(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
return new WebHostBuilder()
.UseConfiguration(config)
.UseKestrel()
.UseStartup<Startup>();
}
}
When I run the test, I am getting a 401 (Unauthorized) which is expected. How can I make this test pass? How can I pass the claim in the test to verify that its working?
Also, if I remove the [Authorize] filters, I am still getting a 401 (Unauthorized) which I think should not happen.
Any help will be greatly appreciated!
Thanks
Aucun commentaire:
Enregistrer un commentaire