Search
 
SCRIPT & CODE EXAMPLE
 

TYPESCRIPT

Websockets authorization nestjs

// source https://github.com/nestjs/nest/issues/1254

import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { bindNodeCallback, Observable, of } from 'rxjs';
import { JwtPayload } from './jwt-payload.interface';
import * as jwt from 'jsonwebtoken';
import { catchError, flatMap, map } from 'rxjs/operators';
import { User } from '../user/user.entity';
import { AuthService } from './auth.service';

@Injectable()
export class JwtWsGuard implements CanActivate {
  constructor(
    protected readonly authService: AuthService,
  ) {
  }

  canActivate(
    context: ExecutionContext,
  ): Observable<boolean> {
    const data = context.switchToWs().getData();
    const authHeader = data.headers.authorization;
    const authToken = authHeader.substring(7, authHeader.length);
    const verify: (...args: any[]) => Observable<JwtPayload> = bindNodeCallback(jwt.verify) as any;

    return verify(authToken, process.env.JWT_SECRET_KEY, null)
      .pipe(
        flatMap(jwtPayload => this.authService.validateUser(jwtPayload)),
        catchError(e => {
          console.error(e);
          return of(null);
        }),
        map((user: User | null) => {
          const isVerified = Boolean(user);

          if (!isVerified) {
            throw new UnauthorizedException();
          }

          return isVerified;
        }),
      );
  }
}

// Where on the client you would authenticate by passing 'dummy' headers in the data object like so:

 const websocket = this.websocketService
      .createConnection(`ws://localhost:8080`);
    const jsonWebToken = getJwtSomehow();

    websocket.subscribe(
      (msg) => console.log('message received: ',  msg),
      (err) => console.log(err),
      () => console.log('complete')
    );

    websocket.next({
      event: 'YOUR_EVENT_NAME',
      data: {
        // ...
        headers: {
          authorization: `Bearer ${jsonWebToken}`
        }
      },
    });
Comment

PREVIOUS NEXT
Code Example
Typescript :: top 100 employers in the united states 
Typescript :: rapists near me 
Typescript :: how to get values from api and iterate through array in typescript and angular 
Typescript :: ag-grid cell renderer dropdown example 
Typescript :: is there somone controlling the puppets in peppermint park 
Typescript :: angular8 PrimeNg tabview 
Typescript :: Powershell show inactive account in active directory 
Typescript :: concat to String structs rust 
Typescript :: Do you use data structures in your current automation project 
Typescript :: nest js config from yaml 
Typescript :: pptxgenjs bullet 
Typescript :: how to save plots into raster format from r 
Typescript :: convert angle to 0-360 godot 
Typescript :: ht office 
Typescript :: carousel not moving unless reload the page 
Typescript :: render html contents from url in asp.net razor 
Typescript :: devide the subplot into subplots in mathplotlib 
Typescript :: fieldmatch cannot be resolved to a type 
Typescript :: if a directive called 10000 times screen getting struck 
Typescript :: aws lambda cache gets to next response 
Typescript :: fs readFile binary 
Typescript :: server sent events httpclient java.net 
Typescript :: destroy object on collision phaser 
Typescript :: writhing requests to text file 
Typescript :: creating different objects in node.js 
Typescript :: ts string lowercase 
Typescript :: angular input change event datatype typescript 
Typescript :: .net framework core scaffhold exists table 
Cpp :: sfml local mouse position 
Cpp :: qt qstring to float 
ADD CONTENT
Topic
Content
Source link
Name
1+8 =