angular2-jwt icon indicating copy to clipboard operation
angular2-jwt copied to clipboard

No Auth header in request

Open vadym-k21 opened this issue 10 years ago • 3 comments

I cannot send Authorization header in request even if it exists in localstorage.

    public login(email: String, password: String) {
        var self = this;
        var headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.post('/tokens', JSON.stringify({
            email: email,
            password: password
        }), { headers: headers }).toPromise()
            .then(response => {
                localStorage.setItem('token', response._body);
                var token = this.jwtHelper.decodeToken(localStorage.getItem('token'));
                return this.authHttp.get('request' + '/' + token.uid, {headers: headers})
                    .subscribe(
                     (d) => console.log(d);
                     (err) => console.log(err);
                     () => console.log('complete');
                     )
            })
            .catch(this._handleError);
    }

Result is:

Request Method:OPTIONS Status Code:401 Unauthorized Remote Address:54.154.185.114:443

Accept:/ Accept-Encoding:gzip, deflate, sdch Accept-Language:en-US,en;q=0.8,ru;q=0.6 Access-Control-Request-Headers:content-type Access-Control-Request-Method:GET Cache-Control:no-cache Connection:keep-alive Host:... Origin:.. Pragma:no-cache Referer:http://localhost:3000/ User-Agent:Mozilla/5.0 (Macintosh)

And fails with authorize 401. What it can be? All of this requests work in ng1. But with ng2 it cannot send auth token. But for another request it works fine. Its weird for me, why it works not for all of them, what I am doing wrong?

vadym-k21 avatar May 20 '16 22:05 vadym-k21

I encountered same issue, what's the solution?

        let token = localStorage.getItem('id_token');
        let headers = new Headers({
          'Authorization': 'Bearer ' + token,
           'Content-Type': 'application/json'  
         });

        let options = new RequestOptions({ headers: headers });
         
        return this.http.get(this.serviceHost + 'change-request/get-new?category='+category
            +'&ugid='+localStorage.getItem('user_guid'), options)
         .map((response: Response) => response.json())
         .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

zzy0705 avatar Dec 20 '16 08:12 zzy0705

if the request being sent out is OPTIONS and not GET/PUT/POST you have a CORS issue and you need to fix it on the server side.

escardin avatar Dec 20 '16 16:12 escardin

Closing as old/out of scope

chenkie avatar May 10 '18 11:05 chenkie