How to add token in http request angular

Viewed 5511

I am tring to do login using angluar and spring boot. I use JWT authentication and after successful athentication i got token in response. After submitting the login i am redirecting to the another url but i need to add bearer token into the url otherwise it returns anonymousUser. I am new to angular please tell me how can i add token into request.

LoginService

loginUser(data: Student): Observable<any> {
    const url = '/login';
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/text; charset=utf-8');
    return this.httpClient.post(this.serverUrl + url, data, {responseType: 'text' as 'json'});
}

getuserInfo(): Observable<any> {
    const url = '/userinfo';
    return this.httpClient.get(this.serverUrl + url);
}

Login form submit

Loginform

submitForm(submission: any): void {
    console.log(submission);
    if (submission && submission.submit) {
        delete submission.submit;
    }
    this.loginService.loginUser(submission)
        .subscribe(result => {
            console.log(result);
            this.userinfo();
        }, err => {
            alert(err);
        });
}

userinfo() {
    this.loginService.getuserInfo()
    .subscribe(result => {
        console.log(result);
    }, err => {
        alert(err);
    });
}

Response

How can i add this token in userinfo please help me.

6 Answers

Store your token in localStorage:

localStorage.setItem('token', 'yourToken');

and use interceptor to set the token in request:

@Injectable({
    providedIn: 'root'
})
export class UserEmulationInterceptor implements HttpInterceptor {

    private readonly token: string;

    constructor() {
        this.token = localStorage.getItem('your_sso_token');
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.token) {
            const modReq = req.clone({
                setHeaders: {
                    'your_sso_token': this.token
                }
            });
            return next.handle(modReq);
        }
        return next.handle(req);
    }
}

In userinfo() function store the token in localStorage

e.g localStorage.setItem('token', 'yourToken') and then in loginUser(data: Student) retrieve the value like

const token = localStorage.getItem('token')

// Add a header
header.set('Authorization', `Bearer ${token}`)

If you using this on more request then it would best to investigate HttpInterceptor.

Angular provides us HTTP_INTERCEPTOR stratergy to take care of this scenario, where we need to pass some common data to every HTTP calls, and this make sure the request pattern are consistent and clean.

Following are things which you can use depending on the type of app you are building.

  1. Store the token received from the login responsive in:
- LocalStorage: if you want the session to be continued even after the user closes the tab.
- Redux/Service: If you want the session to end as soon as the user closes the tab.
  1. Create a new service and extend HttpInterceptor to it. The end class should look something like this.
@Injectable()
export class HttpConfigInterceptor implements HttpInterceptor {

  constructor(
    private authService: AuthService
  ) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

     // This is my helper method to fetch the data from localStorage.
      const token: string = this.authService.getToken(); 
      if (request.url.includes(environment.apiURL)) {

          const params = request.params;
          let headers = request.headers;

          if (token) {
            // set the accessToken to your header
            headers = headers.set('accessToken', token);
          }

          request = request.clone({
            params,
            headers
          });
        }

      return next.handle(request);
    }
}

  1. Register this in your Provider on app.module.ts.
@NgModule({
  declarations: [
   ...
 ],
  imports: [
   ...
  ],
  providers: [
    ...
    { provide: HTTP_INTERCEPTORS, useClass: HttpConfigInterceptor, multi: true },
  ],
  exports: [
   ...
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
 ---
}

That's it.

Happy Coding. :)

token = localStorage.getItem('token') // Will return if it is not set 

this.token = "Bearer " + this.token
let httpOptions = {
  headers: new HttpHeaders({
    'Authorization': this.Token
  })
}
return this.httpClient.post(yourendpoint + '/path', httpOptions)

Try this:-

      tokenType  = 'Bearer ';
      loginUser(data: Student): Observable<any> {
            const url = '/login';
            const header = new HttpHeaders().set('Authorization', this.tokenType + this.cookieService.get('token')); // may be localStorage/sessionStorage
            const headers = { headers: header };
            return this.httpClient.post(this.serverUrl + url, data, headers);
        }
        
        getuserInfo(): Observable<any> {
            const url = '/userinfo';
            const header = new HttpHeaders().set('Authorization', this.tokenType + this.cookieService.get('token')); // may be localStorage/sessionStorage
            const headers = { headers: header };
            return this.httpClient.get(this.serverUrl + url,headers);
        }
        
        submitForm(submission: any): void {
            console.log(submission);
            if (submission && submission.submit) {
                delete submission.submit;
            }
            this.loginService.loginUser(submission)
                .subscribe(result => {
                    console.log(result);
                    this.userinfo();
                }, err => {
                    alert(err);
                });
        }
        
        userinfo() {
            this.loginService.getuserInfo()
            .subscribe(result => {
                console.log(result);
            }, err => {
                alert(err);
            });
        }

Can use append also instead of concating the value with "+"

const header = new HttpHeaders()
  header.append('Authorization', this.tokenType); 
  header.append('Authorization', this.cookieService.get('token'));
Related