Websockets authorization nestjs
The solution for “Websockets authorization nestjs” can be found here. The following code will assist you in solving the problem.
// 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 {
const data = context.switchToWs().getData();
const authHeader = data.headers.authorization;
const authToken = authHeader.substring(7, authHeader.length);
const verify: (…args: any[]) => Observable = 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}`
}
},
});
More questions on [categories-list]
- tss from gene granges
- ixl ansers ixl ansers
- get coin prices node-binance
- how to setup netflix workflow worker
- spritesheets in pyqt spritesheets in pyqt
- cahokia mounds pictures cahokia mounds pictures cahokia mounds pictures
- python 2 decimal places how to get decimal part of a double in python set number of decimals python
- how to find nuber of tweets per day using python how to find nuber of tweets per day using python how to find nuber of tweets per day using python how to find nuber of tweets per day using python how to find nuber of tweets per day using python
- haskell get specific elements of a String
- vb net code snippets for storing password
- error TS2307: Cannot find module ‘@ngx-meta/core’.
- inline scripts encapsulated in tags