sjclark76 / Bard

https://docs.bard.net.nz
MIT License
28 stars 9 forks source link

Handling authentication? #60

Closed dennisroche closed 3 years ago

dennisroche commented 3 years ago

Hi 👋.

Finally getting around to using this library for some API testing. Starting with a basic test.

[Fact]
public void Get200()
{
    Scenario.When
        .Get(GetRoute<ValuesController>(c => c.GetAll()));

    Scenario
        .Then
        .Response
        .ShouldBe
        .Ok();
}

However, this fails with a 401 as authentication is enforced.

Options are:

  1. Disable authentication for testing
  2. Generate a token to pass through

Prefer option 2 as I want to be able to test authentication and role authorization, e.g.

Given a user with role A, When requesting api with role B, Then response should be 403.

Have you given any thought how this could work with Bard? At the moment, it doesn't appear to be a way to append a header to a request and IApi cannot be replaced https://github.com/sjclark76/Bard/blob/8db60d788f3e78cdcfc11724d53e3c29668f824a/src/Bard/Internal/Scenario.cs#L80

sjclark76 commented 3 years ago

Hi,

Thanks for getting round to using Bard.

Specifying headers by request. This is a good idea. You couldn't do that before so i've added the ability to in this PR

If you update to the latest version 4.10.0 you should have access to the latest functionality.

If you look at the test below it shows how can add a custom header. I hope this helps.

https://github.com/sjclark76/Bard/blob/f93bdfcfcc96aec1caa015ff9c66a796efa1da59/src/Bard.Tests/GET/When_retrieving_a_bank_account.cs#L108-L126

There are also a few other options.

  1. This is what I do and is probably the most complicated. But I swap out the authentication provider in my API at startup. With one that i can control in my tests.
  2. When you configure you're scenario you have access to the http client, you can add any default headers there. https://github.com/sjclark76/Bard/blob/f93bdfcfcc96aec1caa015ff9c66a796efa1da59/src/Bard.Tests/BankingTestBase.cs#L27-L39
dennisroche commented 3 years ago

@sjclark76 thanks for the quick response.

Exposing the message on per request implement will work. I'll update to 4.10.0 and try it.

It looks like you missed default value Post. This will break existing users 😮.

https://github.com/sjclark76/Bard/blob/5d9f011528c09d46e1e09308686664394e5bb512/src/Bard/IApi.cs#L28

dennisroche commented 3 years ago

Modifying the HTTP Client also works. I didn't think of that...

sjclark76 commented 3 years ago

Thanks for that.. I fixed up that bug. Shout out if you need any more help.