How to create a service that manages user sessions and authentication tokens

0 votes
Can i know How to create a service that manages user sessions and authentication tokens?
5 days ago in Node-js by Nidhi
• 15,620 points
28 views

1 answer to this question.

0 votes

1. Create the Auth Service (auth.service.ts)

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })

export class AuthService {

  private currentUserSubject: BehaviorSubject<any>;

  public currentUser: Observable<any>;

  constructor(private http: HttpClient) {

    this.currentUserSubject = new BehaviorSubject<any>(

      JSON.parse(localStorage.getItem('currentUser') || null

    );

    this.currentUser = this.currentUserSubject.asObservable();

  }

  public get currentUserValue() {

    return this.currentUserSubject.value;

  }

  login(username: string, password: string) {

    return this.http.post<any>('/api/auth/login', { username, password })

      .pipe(map(user => {

        // Store user details and token in local storage

        localStorage.setItem('currentUser', JSON.stringify(user));

        this.currentUserSubject.next(user);

        return user;

      }));

  }

  logout() {

    // Remove user from local storage

    localStorage.removeItem('currentUser');

    this.currentUserSubject.next(null);

  }

  getToken(): string {

    const user = this.currentUserValue;

    return user?.token;

  }

  isAuthenticated(): boolean {

    return !!this.currentUserValue;

  }

  refreshToken() {

    return this.http.post<any>('/api/auth/refresh-token', { 

      token: this.getToken() 

    }).pipe(map(user => {

      this.currentUserSubject.next(user);

      return user;

    }));

  }

}

2. Key Features

Token Storage: Uses localStorage to persist session

Observable State: Provides reactive user state via BehaviorSubject

Core Methods:

login(): Authenticates and stores session

logout(): Clears session

getToken(): Retrieves JWT

isAuthenticated(): Checks auth status

refreshToken(): Handles token renewal

3. Usage Example


// In component

constructor(private authService: AuthService) {}

login() {

  this.authService.login(username, password)

    .subscribe(

      () => this.router.navigate(['/dashboard']),

      error => this.error = error

    );

}

logout() {

  this.authService.logout();

  this.router.navigate(['/login']);

}

answered 2 days ago by anonymous

Related Questions In Node-js

0 votes
1 answer

How to create a Functional Component that returns a greeting?

To create a Functional Component that returns ...READ MORE

answered Mar 21 in Node-js by Dua
104 views
0 votes
0 answers
0 votes
0 answers

How to create a responsive navbar that collapses on smaller screens in Bootstrap 3?

With the help of proper code example ...READ MORE

Apr 1 in Node-js by Nidhi
• 15,620 points
41 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to design a pipe that accepts configuration options for flexible transformations?

Angular Pipe Implementation import { Pipe, PipeTransform } ...READ MORE

answered 2 days ago in Node-js by anonymous
23 views
0 votes
1 answer
0 votes
1 answer

How to develop a service that handles centralized event broadcasting across components?

To develop a centralized event broadcasting service ...READ MORE

answered 2 days ago in Node-js by anonymous
40 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP