hi, i have a SPA which use cors for http request. My api is phalcon Micro. before i added cors to phalcon, i only used the before event for authentification (send a request to an identity server to check if the SPA allowed to access the api). After i added CORS the authentification doesn´t work anymore. This is my before event:
$app->before(
function () use ($app) {
$origin = $app->request->getHeader('ORIGIN') ? $app->request->getHeader('ORIGIN') : '*';
$app->response->setHeader("Access-Control-Allow-Origin", $origin)
->setHeader("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE,OPTIONS')
->setHeader("Access-Control-Allow-Headers", 'Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization')
->setHeader("Access-Control-Allow-Credentials", true);
// Get reference token from requestHeader
$referenceToken = $app->request->getHeader('Authorization');
//creating guzzle client for the request to the oauth server
$client = new Client(['base_uri' => BASE_URL]);
$uri = 'connect/introspect';
//sending request to the oauth server to identify the client
$response = $client->post( $uri, [
'auth' => [
'xxx',
'xxx'
],
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded'
],
'form_params' => [
'token' => $referenceToken
],
]
);
//get the body of the response from oauth server
$raw_body = $response->getBody()->getContents();
$body = json_decode($raw_body, true);
//if active false authentication is failed, else response the client request
if (empty($body['active']) != null) {
throw new Exception('authentication failed', 401);
return false;
}
//create data for user
if ($body['sub'] != null)
$app->session->set("userId", $body['sub']);
return true;
}
);
$app->options('/{catch:(.*)}', function() use ($app) {
$app->response->setStatusCode(200, "OK")->send();
});
it seems that the SPA sends the request to the api and the api send a unauthorized 401 back. I think the problem is that the SPA send the ORIGIN Headers and get not the response 200 OK in return . and the authorization process fails always because he finds no authorization token. is there a way to do both: cors check and authorization check?
this is my method from SPA(Angular) where i call the phalcon api:
private header() {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': this.oAuthService.getAccessToken()
})
};
return httpOptions;
}
getClients (): Observable<Client[]> {
const body = '';
console.log(this.fileServerUrl + 'client/list');
return this.http.get<Client[]>(this.fileServerUrl + 'client/list', this.header())
.pipe(
catchError(this.handleError('getClients', []))
);
}