0

In my application I try to add JWT security. In response text i add authorities of user and username. All worked, but if i try split response text, it not working.

login(username: string, password: string): Observable<boolean> {
    return this.http.post(AUTH_USER_PATH, JSON.stringify({username: username, password: password}),
        this.getPlainRequestOptions())
        .map((response: Response) => {


            let token: string = response.headers.get('Authorization').slice(7); //working
            let authorities: string[] = JSON.parse(response.text().split('|')[0]); //not working
            let username: string = JSON.parse(response.text().split('|')[1]); //not working


            console.log(authorities);
            console.log(username);
            if (token) {
                localStorage.setItem('token', JSON.stringify(token));
                localStorage.setItem('authorities', response.text());
                localStorage.setItem('username', response.text());
                return true;
            } else {
                return false;
            }
        })
        .catch((error: any) => Observable.throw(error));
}

If I dont use split, then in console I see:

[ROLE_USER, ROLE_ADMIN]|user1

How easily split this string(array) to get this result?

authorities = [ROLE_USER, ROLE_ADMIN];
username = "user1";
Paul
  • 19,704
  • 14
  • 78
  • 96
  • Based on what you wrote, you will not get an array of `[ROLE_USER, ROLE_ADMIN]` into `authorities`. `response.text().split('|')[0]` should get you a string `"[ROLE_USER, ROLE_ADMIN]"`, which you can further parse into an array. – Emin Laletovic Oct 23 '17 at 15:19
  • But after I add this split nothing show in console. I cant log in. – Gerzog The Bat Oct 23 '17 at 15:34

1 Answers1

0

The | character is a special character when it comes to regex. Try escape the special character using \

let authorities: string[] = JSON.parse(response.text().split('\|')[0]);

Here is a link that should help What special characters must be escaped in regular expressions?

Yoni Affuta
  • 284
  • 1
  • 5