简体   繁体   中英

Angular 2 not sending Authorization header using JWT authentication

i'm trying to create an app using Angular2 as the frontend and cakephp 3 as the REST Api, the authentication works fine, but when i try to acces any other url i get the 401 Unauthorized status, and i noticed that the Request Method is OPTIONS instead of GET that i used in my code, and the Authorization header with my token is not sent to the server:

在此处输入图片说明

Here's my user.service.ts code:

constructor(private http: Http,
          private router: Router,
) { }

login(email: string, password: string){
    let headers: Headers = new Headers({ 'Accept': 'application/json','Content-Type': 'application/json' });
    let options: RequestOptions = new RequestOptions({headers: headers});

    return this.http.post('http://www.students.com/api/users/token.json', {email: email, password: password}, options)
  .map((data: Response)=> data.json())
  .subscribe(
    (data)=> this.handlData(data),
    (error)=> this.handlError(error)
  );
}

getSessionData(){
    let token = localStorage.getItem('usr_token');
    let headers = new Headers({ 'Accept': 'application/json', 'Authorization': 'Bearer ' + token });
    let options: RequestOptions = new RequestOptions({headers: headers});

    return this.http.get('http://www.students.com/api/users/getSessionData', options).subscribe(
       data => console.log(data),
       err => console.log(err)
     );
}

handlData(data){

    if(data.success){
        let usrData = data.data.user;
        this.user = new User(usrData.email, usrData.firstname, usrData.lastname, usrData.role, data.data.token);
        localStorage.setItem('id_token', data.data.token);
    }
}

handlError(error){
   console.log(error);
}

i tried to use angular2-jwt module but i had the same error, and to make sure that my API works fine, i tested it with Postman chrome extension and it worked as expected:

在此处输入图片说明

and here's my Apache2 VirtualHost configuration

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html/students
    ServerName www.students.com
    <Directory /var/www/html/students>                        
        Require all granted  
        Options Indexes FollowSymLinks Includes
        AllowOverride all
    </Directory>
    Header always set Access-Control-Allow-Origin "*"                   
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS"
    Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization"
</VirtualHost>

any one had the same problem? any ideas why is that happening?

This is not an issue with Angular but with your backend. Angular is trying to make a preflight request by checking if the server returns OK on a OPTIONS request. You should set-up your backend to respond with 200 or 204 for OPTIONS requests.

If you are using node.js:

app.use('/api', (req, res, next) => {
    /** Browser check for pre-flight request to determine whether the server is webdav compatible */
    if ('OPTIONS' == req.method) {
        res.sendStatus(204);
    }
    else next();
});

Or laravel (PHP):

App::before(function($request)
{
    // Sent by the browser since request come in as cross-site AJAX
    // The cross-site headers are sent via .htaccess
    if ($request->getMethod() == "OPTIONS")
        return new SuccessResponse();
});

This will tell the browser that the server can handle webdav request methods appropriately.

UPDATE: added by asker on CakePHP:

public function initialize() {
    parent::initialize();

    if($this->request->is('options')) {
        $this->response->statusCode(204);
        $this->response->send();
        die();
    }

    $this->Auth->allow(['add', 'token']);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM