-
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Websockets auth #1254
Comments
|
Here is an example implementation:
Where on the client you would authenticate by passing 'dummy' headers in the
|
@jsdevtom Thanks for the inspiration 😄 |
This is how I achieved it : Guard : import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
/*
Custom imports for AuthService, jwt secret, etc...
*/
import * as jwt from 'jsonwebtoken';
@Injectable()
export class WsJwtGuard implements CanActivate {
constructor(private authService: AuthService) {}
async canActivate(context: ExecutionContext) {
const client = context.switchToWs().getClient();
const cookies: string[] = client.handshake.headers.cookie.split('; ');
const authToken = cookies.find(cookie => cookie.startsWith('jwt')).split('=')[1];
const jwtPayload: JwtPayload = <JwtPayload> jwt.verify(authToken, yourSecret);
const user: User = await this.authService.validateUser(jwtPayload);
// Bonus if you need to access your user after the guard
context.switchToWs().getData().user = user;
return Boolean(user);
}
} Gateway : @UseGuards(WsJwtGuard)
@SubscribeMessage('events')
onEvent(client, data) {
// data.user contains your user if you set it in the guard
} |
@TristanMarion it does not work to me... Actually getting two kind of issues, one of them is the following when I am doing it: @UseGuards(JwtWsGuard)
@SubscribeMessage('nuevoUsuario')
onEvent(client, data) {
this.logger.log(client);
this.logger.log(data);
} I am not able to run start:dev since I get the following: [nodemon] starting `node dist/main`
[Nest] 4292 - 2019-06-07 21:04 [NestFactory] Starting Nest application...
[Nest] 4292 - 2019-06-07 21:04 [InstanceLoader] AppModule dependencies initialized +40ms
[Nest] 4292 - 2019-06-07 21:04 [InstanceLoader] MongooseModule dependencies initialized +1ms
[Nest] 4292 - 2019-06-07 21:04 [ExceptionHandler] Nest can't resolve dependencies of the UsersService (?). Please make sure that the argument at index [0] is available in the WssModule context. +1msError: Nest can't resolve dependencies of the UsersService (?). Please make sure that the argument at index [0] is available in the WssModule context.
at Injector.lookupComponentInExports (D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\injector\injector.js:180:19)
at processTicksAndRejections (internal/process/task_queues.js:89:5)
at async Injector.resolveComponentInstance (D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\injector\injector.js:143:33)
at async resolveParam (D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\injector\injector.js:96:38)
at async Promise.all (index 0)
at async Injector.resolveConstructorParams (D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\injector\injector.js:112:27)
at async Injector.loadInstance (D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\injector\injector.js:78:9)
at async Injector.loadProvider (D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\injector\injector.js:35:9)
at async Promise.all (index 3)
at async InstanceLoader.createInstancesOfProviders (D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\injector\instance-loader.js:41:9)
at async D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\injector\instance-loader.js:27:13
at async Promise.all (index 9)
at async InstanceLoader.createInstances (D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\injector\instance-loader.js:26:9)
at async InstanceLoader.createInstancesOfDependencies (D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\injector\instance-loader.js:16:9)
at async D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\nest-factory.js:75:17
at async Function.asyncRun (D:\wamp\www\learn\nestjs\nestjs-restapi\node_modules\@nestjs\core\errors\exceptions-zone.js:17:13)
1: 00007FF7D3CA674F napi_wrap+120927
2: 00007FF7D3C4FE26 uv_loop_fork+44550
3: 00007FF7D3BF93B9 v8::internal::StackGuard::ArchiveSpacePerThread+26393
4: 00007FF7D4238A69 v8::internal::OFStreamBase::xsputn+5065
5: 00007FF7D4237FA8 v8::internal::OFStreamBase::xsputn+2312
6: 00007FF7D42382D8 v8::internal::OFStreamBase::xsputn+3128
7: 00007FF7D42380FD v8::internal::OFStreamBase::xsputn+2653
8: 00007FF7D47F2C16 v8::internal::NativesCollection<0>::GetScriptsSource+662454
[nodemon] app crashed - waiting for file changes before starting... Any work around? Thanks in advance! |
Did you resolved the problem with dependencie injection? |
@TristanMarion your solution does not work with WebSocket, and |
I do not know if this works with WsAdapter, but here is my solution. Hope this helps someone. My ws server is socket.io openid.guard.ts
AuthService.ts
gateway
|
Hi, I am using the same strategy as @TristanMarion but getting a |
Found the issue, package conflict between "@nestjs/websockets": "^6.8.2" & "@nestjs/core": "^6.0.0",. I need to upgrade all @nestjs packages |
Is using switchToWs safe to use? Socket.io might be using WS or it might be using another protocol for communication. In the later case, is using |
@mranon0007 yes |
I'm submitting a...
Current behavior
There is no information about auth in websockets microservice in the docs.
Can we use middlewares / interceptors / guards / nest-passport for it ?
As I see, it was issue Middleware for socket.io not working #637 . In the end @adrien2p suggest to use such one:
But as I see it's no longer supported, isn't it?
From the docs I understood that
guards
is like access policy. It executes before every method call and check permission to handler. But auth logic might not be here, isn't it?Interceptors is not called at connection time. Only on emiting, so I think it's not our case.
handleConnection()
inside gateway.Is this is the place where auth might be?
Can you explain plz the best practices how to do it inside Nestjs ecosystem? ;)
Thanks.
Environment
The text was updated successfully, but these errors were encountered: