docs.nestjs.com icon indicating copy to clipboard operation
docs.nestjs.com copied to clipboard

NestJS Authenticated sessions documentation has major gaps and is seemingly wrong

Open Offlein opened this issue 7 years ago • 44 comments

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

"Session" instructions in "Authentication" section of documentation is erroneous and this functionality is otherwise undocumented. (And non-obvious.)

Expected behavior

It should be clear how to implement AuthGuard with a cookie-based sessions.

Please see my comment from Sept. 14 here.

At this point I DO have my browser at least storing a cookie after adding stuff directly to my main.ts, which I think is bad form:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';
import * as passport from 'passport';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
    app.use(session({
        secret: 'a secret',
        name: 'abcd',
        resave: true,
        saveUninitialized: true
    }));

    app.use(passport.initialize());
    app.use(passport.session());
  await app.listen(3000);
}
bootstrap();

This at least gets me a cookie with key "abcd" in my Chrome Developer Tools "Application" > "Cookies" section, with a long value (s%3Ac1xPblaYplJQL2DLmfIUVoLdLIbkjsYQ.e8Q69kfkdn1Mm96Clk6BMg4Ea0k647RnIkT2bP60Lwc).

In my custom Guard, I can actually inspect the request and see that it has a session property with a Session object in it. The Session object has an id RUHHx_IvcDIPFWt-9MHeZHruw1bSO7-O which is different from what's stored in my cookie -- but that may be normal. The request object also has a sessionID property, with the same ID... And a sessionStore property with a MemoryStore object that has as property of sessions in it, that's just an empty object.

Going back to the documentation's recommended code: just calling super.logIn(theRequestObject) sends me directly to my Google Auth strategy's serializeUser function, which is supposed to callback with the user that gets passed to it and/or an error.

Unfortunately, there is never any user that gets passed to it. I'm not sure how the User is intended to be retrieved from the session memory store, or where it's intended to be set to the memory store...

So there's a ton of stuff missing here. :(

Environment

Nest version: 5.4.0

For Tooling issues:

  • Node version: 8.11.3
  • Platform: Fedora 25; Windows 10 x64

Other: @kamilmysliwiec It seems at least 3 other people are confused about this. It's very frustrating. I think NestJS is so cool, but I took a break from it largely because I was spinning my wheels with this very issue. It would be one thing if I felt like I was just confused, but as it stands the docs are clearly wrong (or at least misleading), so I don't feel like I can move forward.

Offlein avatar Oct 20 '18 21:10 Offlein

Hey, I was tackling with this same issue, and after digging around the code, I found out the docs aren't entirely wrong - just misleading. This seems to work (in your custom AuthGuard):

async canActivate(context: ExecutionContext): Promise<boolean> {
  const request = context.switchToHttp().getRequest();
  const result = (await super.canActivate(context) as boolean);
  await super.logIn(request);
  return result;
}

The reason the User never gets passed to serializeUser in your case is because super.canActivate(context) is actually what runs the strategy's authentication function, which results in the User object. Hence calling super.logIn() (which calls request.logIn(), which sets up sessions etc.) before that (like the docs suggest) doesn't work, since it doesn't have the User object yet.

That being said, I think the docs could be clarified around this:

  • It's not immediately clear that AuthGuard passes its own callback to passport.authenticate(), thus bypassing a lot of the usual stuff passport does after a successful authentication - like serializing the user to a session (see here for more details)
  • Calling super.logIn(request) like the docs suggest will result in an error. The function needs to be called after super.canActivate(context).

Dragory avatar Dec 09 '18 01:12 Dragory

@Dragory yours was the only example I've found on how to extend the AuthGuard, however I get

[Nest] 91203   - 2/16/2019, 4:30:02 PM   [ExceptionsHandler] passport.initialize() middleware not in use +5756ms
Error: passport.initialize() middleware not in use

I don't think we need to use passport.initialize() do we? Btw I'm just trying to make sure that that the user has the active property true, so trying to use request.user after the logIn call

alex88 avatar Feb 17 '19 00:02 alex88

@alex88 I call both passport.initialize() and passport.session() in my app. I also have 2 guards: 1 for the login itself (which is what's shown above), and 1 for pages that require you to be logged in, which is basically just this:

canActivate(context: ExecutionContext) {
    const req = context.switchToHttp().getRequest();
    if (!req.user) throw new UnauthorizedException();

    return true;
}

Dragory avatar Feb 17 '19 10:02 Dragory

Is there any kick off date to this topic? I implemented my app with jwt authentication, but for some reason I have to change it to cookie based one. However based on the above conversation I leave as is for now and don't mess up my code... :/

bzsozsy avatar Mar 15 '19 18:03 bzsozsy

I was able to get this working -- here's the solution I came up with:

configure sessions and passport to use sessions

In main.ts (or wherever you're settting up nest):

app.use(session({
    secret: 'CHANGEME',
    resave: false,
    saveUninitialized: false,
  }));
  app.use(passport.initialize());
  app.use(passport.session());

session from the express-session package.

guards

I'm using passport-local so my LocalAuthGuard class looks like this:

import { Injectable, ExecutionContext, UnauthorizedException, Logger } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
    async canActivate(context: ExecutionContext): Promise<boolean> {
        const request = context.switchToHttp().getRequest();
        const result = (await super.canActivate(context) as boolean); // THIS MUST BE CALLED FIRST
        await super.logIn(request);
        return result;
    }

    handleRequest(err, user, info) {
        if (err || !user) {
            throw err || new UnauthorizedException();
        }

        return user;
    }
}

configure the serializer

If you look at the implementation of PassportSerializer (from @nestjs/passport) you'll notice that both serializeUser and deserializeUser are abstract....so they need to be implemented by you. Take a look: https://github.com/nestjs/passport/blob/master/lib/passport/passport.serializer.ts

My barebones serializer looks like this:

import { PassportSerializer } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';

@Injectable()
export class CookieSerializer extends PassportSerializer {
    serializeUser(user: any, done: (err: any, id?: any) => void): void {
        done(null, user);
    }

    deserializeUser(payload: any, done: (err: any, id?: any) => void): void {
        done(null, payload);
    }
}

update auth module

Then in the module (for example I'm using AuthModule), this needs to be included. So my AuthModule class looks like this:

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { LocalStrategy } from './strategies/local.strategy';
import { PassportModule } from '@nestjs/passport';
import { CookieSerializer } from './cookie.serializer';

@Module({
    imports: [
        PassportModule.register({session: true}),
    ],
    providers: [AuthService, LocalStrategy, CookieSerializer],
    controllers: [AuthController],
    exports: [PassportModule],
})
export class AuthModule { }

session guard

Create a guard to check to see if the user is in the session.

import { CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';

export class SessionGuard implements CanActivate {
    canActivate(context: ExecutionContext): boolean | Promise<boolean> {
        const httpContext = context.switchToHttp();
        const request = httpContext.getRequest();

        try {
            if (request.session.passport.user) {
                return true;
            }
        } catch (e) {
            throw new UnauthorizedException();
        }

    }
}

putting it all together

Here is how this can be used in a controller:

import { Controller, Get, Post, Param, Body, UseGuards, HttpCode, HttpStatus, Req } from '@nestjs/common';
import { CreateUserDto } from './dto/createUser';
import { AuthGuard } from '@nestjs/passport';
import { LoginCredentialsDto } from './dto/login.dto';
import { LocalAuthGuard } from './guards/local.guard';
import { SessionGuard } from './session.guard';
import { SessionUser } from './sessionuser.decorator';

@Controller('auth')
export class AuthController {
    @Get('me')
    @UseGuards(SessionGuard)
    getMetadataArgsStorage(@SessionUser() user: any) {
        return user;
    }

    @Post('login')
    @HttpCode(HttpStatus.OK)
    @UseGuards(LocalAuthGuard)
    login(@Body() login: LoginCredentialsDto, @Req() req): Promise<any> {
        return;
    }
}

You can test this out with cURL/Postman:

Logging in:

$ curl -X POST http://localhost:3000/auth/login -d "username=jdoe&password=1" -v
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 3000 (#0)
> POST /auth/login HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.54.0
> Accept: */*
> Content-Length: 23
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 23 out of 23 bytes
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Set-Cookie: connect.sid=s%3ADuKdgMobTzL7pHXa9oszUqYRy2J85Eiv.11yD1Gq3NwgdSASUfBYU%2B7sxBIwLH9bqwv1pGtq2T%2BU; Path=/; HttpOnly
< Date: Thu, 25 Apr 2019 21:44:25 GMT
< Connection: keep-alive
< Content-Length: 0
<
* Connection #0 to host localhost left intact

Then to test it out:

$ curl -X GET http://localhost:3000/auth/me -H 'Cookie: connect.sid=s%3AfBdKLAFybLq6xh13NeET3LDEQjfxv7cD.XyZanjMKgAq9SlBUVcDsCdZxJn0auKCgWZCnczaLczQ' -v
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 3000 (#0)
> GET /auth/me HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.54.0
> Accept: */*
> Cookie: connect.sid=s%3ADuKdgMobTzL7pHXa9oszUqYRy2J85Eiv.11yD1Gq3NwgdSASUfBYU%2B7sxBIwLH9bqwv1pGtq2T%2BU
>
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: text/html; charset=utf-8
< Content-Length: 43
< ETag: W/"2b-p23HHgfkAEp1vHx70BYS/ngFWwQ"
< Date: Thu, 25 Apr 2019 21:51:04 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
{"firstName":"John","lastName":"Doe"}

Thanks @kamilmysliwiec for all your work on NestJS -- seems very slick!

ejhayes avatar Apr 25 '19 21:04 ejhayes

@ejhayes You don't happen to have this example in a public git repo? I don't understand where CookieSerializer is used

Abrissirba avatar May 11 '19 19:05 Abrissirba

@Abrissirba add to providers array in module

Insidexa avatar Jul 17 '19 09:07 Insidexa

@Abrissirba This repo implements sessions with a similar pattern: https://github.com/johnbiundo/test-auth-chapter-sample

johnbiundo avatar Jul 17 '19 15:07 johnbiundo

The solutions provided in the issue make absolutely zero sense to me as a new user of NestJS.

It would be great if someone could update the documentation with how sessions work together with NestJS, express, express-session, and passport with the local guard.

NormySan avatar Jul 18 '19 19:07 NormySan

@NormySan The solutions provided in the issue works fine. Its problem not of NestJS its problem people how works sessions.

Insidexa avatar Jul 19 '19 06:07 Insidexa

This article covers sessions in detail. Has been reviewed by the NestJS core team. https://dev.to/nestjs/authentication-and-sessions-for-mvc-apps-with-nestjs-55a4

I'll wait a few days to see if there are any further comments before closing.

johnbiundo avatar Jul 22 '19 16:07 johnbiundo

Example project how to use session in NestJS https://github.com/Insidexa/nestjs-session-example

Insidexa avatar Jul 22 '19 18:07 Insidexa

Would be great to split the documentation example into two paths after setting up everthing: 1. Session, 2. JWT. Session is industry-standard for authentication IMO.

filipjnc avatar Jul 28 '19 11:07 filipjnc

@filipjnc Yeah, I do think it's worth adding something on sessions to the MVC chapter perhaps.

johnbiundo avatar Jul 29 '19 19:07 johnbiundo

@johnbiundo thank you so much for you code, it helped me a lot

the only thing i want to ask you to implement user module, especially controller properly. its kinda not obvious why code doesnt work when I move code from app conteroller to user controller. The answer is I have to add LocalStrategy, SessionSerializer to imports either in user controller or app controller but as i said this is not obvious

TrejGun avatar Aug 20 '19 15:08 TrejGun

@TrejGun Sorry, I'm not clear on what the issue is. Can you clarify or provide a sample repo?

johnbiundo avatar Aug 20 '19 20:08 johnbiundo

@johnbiundo sorry for confussion

your example uses only user.service and there is no implementation of user.controller, instead /login endpoin lives in app.controller which is on my oppinion is wrong. It should live in users.controller so i created one and moved endpoint. After that I spent some time figuring out what dependencies it requires and why it does not work. To save some time for next who want to do this, I ask you to implemen user.controller. I can share my code with you if you want but i guess you dont really need.

Tanks

TrejGun avatar Aug 21 '19 13:08 TrejGun

@TrejGun Thanks for the additional input. I'll give it some thought and see if I can find time to improve the example.

johnbiundo avatar Aug 21 '19 15:08 johnbiundo

you can find my version of solution in my blog, there are also other articles about nest.js https://trejgun.github.io/

TrejGun avatar Oct 26 '19 12:10 TrejGun

Hi all,

After digging into whole Nestjs framework, I find it really cool. But, the security aspects are very painful. Implementing a simple local-strategy session should not be as difficult as the code @TrejGun has provided (thanx for that btw). We have to provide :

  • local strategy class
  • canActivate handler
  • serializer/deserializer
  • findUser service and so forth
  • Custom annotations

Look at this snippet from Spring Security for example :

@RestController
@RequestMapping("/api")

public class TestService {
    @Secured("ROLE_USER")
    @RequestMapping("/currentUser")    
    public Principal information(Principal principal) {    
       return principal;
    }

  @PreAuthorize("hasRole('ROLE_USER') and hasRole('ROLE_TRAINER')")    
  @RequestMapping("/courses")    
   public List<Course> courses() {        
      return courseDAO.getCourses(); 
   }}

This code can be used for LDAP, local strategy, Google/Facebook and whatever you want without changing any single line of code in your controllers.

With UserGuard/Auth annotations, we tie the controllers code with custom annotations. There's no notion of Principal, only req.session.passport user which is very low level.

We should be able to say in app.module that we want a Passport local strategy (session/basic or other) and all the boilerplate code that we generally see should be generated or implemented in NestJS for us.

My 2 cents

Sami

dngconsulting avatar Nov 07 '19 13:11 dngconsulting

@TrejGun Can you add example on how to add openid-client strategy? It would make it very easy to support a broad range of IdPs.

hegelstad avatar Nov 22 '19 21:11 hegelstad

@hegelstad hey! i can, do you have example?

TrejGun avatar Nov 23 '19 07:11 TrejGun

@TrejGun See this: https://github.com/onelogin/onelogin-oidc-node/blob/master/5.%20Auth%20Flow%20-%20PKCE/app.js

This is OpenIDConnect example, using Onelogin as the IdP. How can it be implemented within the boundaries of Nest PassportStrategy? I think I have a solution, but it is currently not working yet, I will share it when it works!

hegelstad avatar Nov 23 '19 09:11 hegelstad

@TrejGun I made an example that seems to work here: https://github.com/nestjs/docs.nestjs.com/issues/99#issuecomment-557878531

Do you see this as a viable approach, do you see any way to improve it? The useFactory for instantiating the strategy feels a little bit odd, but it works.

hegelstad avatar Nov 24 '19 11:11 hegelstad

@hegelstad I don't really like to cretae user on login, otherwise looks nice and clean. i will add this to my repo when I have time

TrejGun avatar Nov 24 '19 13:11 TrejGun

@TrejGun Good point, I think it would be better to create a module that loads all the users and roles from IdP (onelogin in this case) and stores it in the UsersStore. Then updates updates to user accounts in the IdP could be pushed via webhooks to update the UsersStore in nest.

Please do add the example, I think it can be helpful.

hegelstad avatar Nov 24 '19 13:11 hegelstad

@hegelstad I have ported your code to my repo but I did not check it because I dont have account on onelogin. can you please do me a favour - put your keys in my example and check if it still works? here is a PR https://github.com/TrejGun/session-based-authorization-for-nestjs/pull/4 you can review and/or push to the same branch

TrejGun avatar Nov 24 '19 16:11 TrejGun

@TrejGun please see the PR I made https://github.com/TrejGun/session-based-authorization-for-nestjs/pull/5

hegelstad avatar Nov 24 '19 20:11 hegelstad

Just chipping into this just now. I'm using the SAML strategy with our custom in-house SAML authentication source. I need a way to set-up a fake user session in development (so you open the app and you're logged in).

In app.module.js I'm trying to call req.login(fakeUser) which gives me an error message saying: [Nest] 979 - 02/04/2020, 5:21:58 PM [ExceptionsHandler] passport.initialize() middleware not in use +2053ms. and and samlStrategy.success(user) which produces an error saying that samlStraegy.success is not a function.

I know passport does have a req.login method and you have to call passport.initialize() first, but calling passport.initialize() throws saying that initialize is not a function

I have a SAML strategy as follows:

@Injectable()
class SAMLStrategy extends PassportStrategy(Strategy) {
  public constructor(config: ConfigService) {
    super({
      entryPoint: config.get('CAS_URL'),
      issuer: 'passport-saml',
      host: config.get('EXTERNAL_URL'),
    });
  }

  public async validate(profile?: Profile): Promise<User> {
    if (!profile) {
      throw new UnauthorizedException();
    } else {
      return new User({
        eppn: profile.eppn,
        firstName: profile.givenName,
        lastName: profile.sn,
        email: profile.email,
      });
    }
  }
}

export { SAMLStrategy };

rmainwork avatar Feb 04 '20 17:02 rmainwork

@rmainseas just follow my examples https://trejgun.github.io/ ad if it was useful I will appreciate RP with SAML

TrejGun avatar Feb 05 '20 00:02 TrejGun