Can't add header Authorization for jwt token
Hi,
I'm trying to login to an API before execute some behat tests with this function. It seems not to accept the header.
/**
* @BeforeScenario @login
*
*/
public function login(BeforeScenarioScope $scope)
{
$user = $this->doctrine->getManager()->getRepository('App:User')->findOneByEmail('[email protected]');
$token = $this->jwtManager->create($user);
$this->restContext = $scope->getEnvironment()->getContext(RestContext::class);
$this->restContext->iAddHeaderEqualTo('Authorization', "Bearer $token");
$this->restContext->printLastResponseHeaders();
}
The last line return following output, where authorization header is missing
content-type: application/ld+json; charset=utf-8
x-content-type-options: nosniff
x-frame-options: deny
cache-control: no-cache, private
date: Tue, 23 Oct 2018 15:58:14 GMT
link: <https://localhost/api/docs.jsonld>; rel="http://www.w3.org/ns/hydra/core#apiDocumentation"
Hello,
You are printing the response headers instead of the request. On my end, I used this context for the authorization header and it was working great.
Ok for the response but executing this scenario and testing header return Behatch\Context\RestContext::theHeaderShouldContain() The header 'authorization' doesn't exist (OutOfBoundsException)
@login
Scenario: Create a result as admin
When I add "Content-Type" header equal to "application/ld+json"
And I add "Accept" header equal to "application/ld+json"
And the header "Authorization" should contain "Bearer"
And I send a "POST" request to "/api/results" with body:
I guess (not sure) it's because $scope->getEnvironment()->getContext(RestContext::class) returns a new instance of RestContext.
You can try to extend Behatch RestContext and use this new class in your context configuration instead of the one from Behatch.
A bit like this https://www.bgalati.fr/blog/php-matcher-with-behat-to-assert-unpredictable-json/.
There is a context problem for sure, following features don't work either and return the same output :
Behatch\Context\RestContext::theHeaderShouldContain() The header 'authorization' doesn't exist (OutOfBoundsException)
When I add "Content-Type" header equal to "application/ld+json"
And I add "Accept" header equal to "application/ld+json"
And I add "Authorization" header equal to "Bearer token"
And the header "Authorization" should contain "Bearer"
Did you try what I proposed? Real world example:
- https://github.com/EnMarche/en-marche.fr/blob/master/features/bootstrap/RestContext.php#L85
- https://github.com/EnMarche/en-marche.fr/blob/master/features/oauth.feature#L64
I found the bug. When I put @logout annotation anywhere in my features, the authorization header is missing, even if a @login annotation is present on next scenario.
/**
* @BeforeScenario @logout
*/
public function logout() {
$this->restContext->iAddHeaderEqualTo('Authorization', '');
}