Pass JWT to api after successful login and JWT storage


#1

I am able to successfully login to an api and return a JWT with the following:
login(credentials) {
let json = JSON.stringify({ username: ‘someuser’, password: “somepass” });
let headers = new Headers({ ‘Content-Type’: ‘application/json’ });
let options = new RequestOptions({ headers: headers });

        return new Promise((resolve, reject) => {
            this.authHttp.post(this.LOGIN_URL, json, options)
                .map(res => res.json())
                .subscribe(
                data => {
                    if (data.id_token) {
                        this.local.set('id_token', token);
                        this.user = this.jwtHelper.decodeToken(token).username;
                    }
                    resolve(data);
                },
                err => {
                    this.error = err;
                    reject(err)
                }
                );
        });
    }

However, I cannot seem to pass the token back to the api for any further calls.
This used to work before RC0:

getPostLoginData(property): Observable<Object> {
        let json = JSON.stringify({ extradata: 'somdata' });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.authHttp.post(this.appURL + "api/protected/getmoredata", json, options)
            .map(res => res.json())
            .catch(this.handleError);
    }

Do I need to pass the token in the headers? Or is this handled in authHttp?


#2

I had a combination of factors that were working against me making this work.

Ultimately the major points I missed were:

  1. passing the token in the headers:
    let headers: Headers = new Headers
    headers.append(‘Content-type’, ‘application/json’);
    headers.append(‘Authorization’, 'Bearer ’ + token);

  2. Using local.set was not working but window.localStorage.setItem does
    this.local.set('id_token', token); // did not work or local.get was not working - not sure. It saved something but it was not correct

but window.localStorage.setItem('id_token', token); does work


#3

Need to use Ionic storage