Angular 2+: Harnessing the Power of Web Tokens

After sending a POST request to the backend REST API through a login component, I receive an x-auth token in the response headers. What is the best way to retrieve and save this token for using it in all subsequent API requests throughout the user's logged-in session? Thanks

Answer №1

localStorage.setItem('token', response.access_token);

This is my approach using Angular 5:

Implementation in LoginService:

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpParams } from '@angular/common/http';

import { HttpService } from '../services/http.service';

@Injectable()
export class LoginService{
    constructor(private _http: HttpService) {
    }

    login(user: string, pass: string) {
        const params = new HttpParams()
            .append('grant_type', 'password')
            .append('username', user)
            .append('password', pass);
        const headers = new HttpHeaders()
            .set('Content-Type', 'application/x-www-form-urlencoded');
        return this._http.post('login', params, { headers: headers });
    }
}

Login Component Structure:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { LoginService } from '../../services';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
    public pageTitle = 'User login';
    errorMessage = '';
    loginFormGroup: FormGroup;
    constructor(
        private fb: FormBuilder,
        private _loginService: LoginService) { }
    ngOnInit() {
        this.formBuild();
    }

    formBuild() {
        this.loginFormGroup = this.fb.group({
            loginUser: ['', [Validators.required]],
            loginPass: ['', [Validators.required]],
        });
    }

    onLogin() {
        let response: any;
        this._loginService.login(this.loginFormGroup.value.loginUser, this.loginFormGroup.value.loginPass)
            .subscribe(
                response => { response= response; },
                error => { this.errorMessage = <any>error; },
                () => {

                    localStorage.setItem('token', response.access_token);
                });
    }
}

I store the token in localeStorage.

Interceptors for utilizing the token:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const token = localStorage.getItem('token');
        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${token}`
            }
        });
        return next.handle(request);
    }
}

export const TokenInterceptorProvider = {
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor,
    multi: true
};

This method is tailored for Angular 5 and HTTPClient. Let me know if you require a solution specifically for Angular 2.

Answer №2

Make sure to save the token you receive in the browser's local storage and implement an http interceptor to automatically strip the token from responses and insert it into all requests.

Answer №3

To set a cookie using the NgCookie module, you can do so like this:

$cookies.put("token","your_response_val");

Then, to retrieve the cookie for further use, simply use $cookies.get().

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding attributes to an input element in real-time

I am in the process of generating multiple input elements using an *ngFor loop, and for some of them I would like to include a data-bv-integer="true" attribute, while leaving it out for others. The decision of whether or not to include this attribute depen ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

Upon clicking the button, the Angular Mat-Table with Reactive Forms fails to display any data, instead adding a blank row accompanied by errors

When the AddRow_click() function is executed, I populate the insuranceFormArray and assign its values to the datasource. However, after adding an entry, an empty row appears in the table, and error messages are displayed in the console. Only a subset of th ...

Position components in Angular 2 based on an array's values

Hello all, I am a beginner in terms of Angular 2 and currently facing some obstacles. My goal is to create a board for a board game called Reversi, which has a similar layout to chess but with mono-color pieces. In order to store the necessary information, ...

Experiencing an array of issues while attempting to convert my HTTP request into an

I am currently facing some difficulties in converting my HTTP requests into observables. Within my Angular App, there is a service called API Service which takes care of handling all the requests to the backend. Then, for each component, I have a separate ...

Guide to automatically blur the input field and toggle it upon clicking the checkbox using Angular

<input (click)="check()" class="checkbox" type="checkbox"> <input [(ngModel)]="second_month" value="2019-09" type="month" [class.blurred]="isBlurred">> I need the second input(type=month) field to be initially blurred, and only unblur ...

TS2307 error encountered in Angular 2 TypeScript due to the inability to locate a module for a private npm

I've been working on creating some components for internal company use, with the intention of sharing them through our private npm repository. However, I've hit a roadblock while trying to add these components to an app using npm and systemjs - I ...

"Angular Google Maps module working perfectly on local environment but failing to render on live production site

My little application utilizes the official Angular Google Maps module. While it runs smoothly in my local setup, it simply displays a gray window in production. Upon inspecting the code, I can see that the map, marker, and info window are present, but not ...

Troubleshooting an issue with asynchronous reactive form validators in Angular

I encountered an issue where I need to access a service that sends an http request to an API to verify the existence of a given username. Snippet from Auth component: usernameCheck(username: string){ return this.http.get(this.baseUrl + "usernamecheck?u ...

Difficulty reloading after updating input using AngularJS ngTable

I'm encountering an issue where I need to utilize ngTable with TableParams to load and modify a table. For instance, when the page initializes, entering a number in the textbox for the first time displays the appropriate number of rows in the table. ...

Issue with Angular 2 AOT Compilation when trying to access formArray

This is the formGroup I created this.createOrderForm = this.fb.group({ items: this.fb.array([]) }); To add an item on button click addItem() { const control = <FormArray>this.createOrderForm.controls['items']; const a ...

Using a passport openID strategy to enhance JWT functionality

Encountered an issue when attempting to authenticate with passport.js using openID (passport-steam) and transitioning to tokens (JWT) over sessions. The current code structure is as follows: app.post('/auth/steam', passport.authenticate('s ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

Angular - Sharing data between components with response value

I am currently in the process of restructuring my project, focusing on establishing communication between unrelated components while also waiting for a return value from a function call. Imagine having component1 with function1() and component2 with funct ...

Understanding how to extract and utilize the display name of enums from a C# Web API within an Angular

Within my C# web API, I have established an enum with a designated display name: public enum Countries { Australia, [Display(Name="New Zealand")] NewZealand } To showcase this list in a dropdown menu within my Angular project, I transmit ...

Adding a fresh element to an object array in TypeScript

How can we add a specific value to an array of objects using TypeScript? I am looking to insert the value 1993 into each "annualRentCurrent" property in the sample object. Any suggestions on how to achieve this in TypeScript or Angular? Thank you! #Data ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

Angular asynchronous testing with Observable using karma

I am currently working on testing an asynchronous scenario. Here is a snippet of my component: ngOnInit(private service: MyService) { this.isLoading = true; this.service.getData().subscribe((data) => { this.data = data; this.isLoa ...

Steps for updating the title of a dialog box once it has been opened

When opening the dialog: let dialogRef = dialog.open(UserProfileComponent, { height: '400px', width: '600px', }); The dialog content: <h2 mat-dialog-title>Dele ...

The error at core.js:4002 is a NullInjectorError with a StaticInjectorError in AppModule when trying to inject FilterService into Table

While exploring PrimeNg Table control in my application - as a beginner in PrimeNg & Angular, I encountered an error No provider for FilterService! shown below: core.js:4002 ERROR Error: Uncaught (in promise): NullInjectorError: StaticInjectorError(AppMo ...