Craig Jacobs
Craig Jacobs

Reputation: 1071

Slim Framework 3 401 response can't set WWW-Authenticate header

Have a REST application using Slim Framework v3. All works as expected, but I cannot seem to set headers for the response.

For example:

$app->any('/[{path:.*}]', function(Request $request, Response $response, $args = null ) use ( $objError, $objDBCon, $objUtil ) {
...
return $response->withAddedHeader( 'WWW-Authenticate', 'API-key realm="restricted"' )
                ->withJson($apiResults, $httpcode);
});

Works as expected in terms of getting data, getting the correct http status code, etc.

For example I get a the correct response JSON

{ "message": "You must be logged in to access this resource" }

and I get the expected status code:

Request Method:GET
Status Code:401 Unauthorized

and all the standard, correct headers, content-type, etc, etc.

But cannot seem to set any additional headers.

Reference documentaiton https://www.slimframework.com/docs/objects/response.html

Upvotes: 1

Views: 980

Answers (1)

Joe
Joe

Reputation: 234

My reputation is to low to add a comment:

According to the manual

withAddedHeader method appends the new value to the set of values that already exist for the same header name

Does your header already exists before appending?

I usually create a new header for each response, something like this:

return $response = $next($request, $response)
            ->withHeader('Access-Control-Allow-Origin', $this->allowedhosts)
            ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
            ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->withStatus(200);

hope this helps.

Upvotes: 2

Related Questions