Error unknown authentication strategy local

Ошибка с паспортомjs: неизвестная стратегия аутентификации «локальная» Я разрабатываю приложение nodejs и использую паспортные данные для аутентификации. Я использую локальную стратегию паспорта. Но когда я пытаюсь войти в систему, я получаю следующую ошибку: Вот мой файл паспорт-config.js: И ниже мой файл RegistrationsController.js, в котором находится мой api аутентификации, Я просматривал код последние 2 дня, […]

Содержание

  1. Ошибка с паспортомjs: неизвестная стратегия аутентификации «локальная»
  2. 3 ответа
  3. Unknown authentication strategy «local» #18
  4. Comments
  5. Error: Unknown authentication strategy «local.signup» #1
  6. Comments

Ошибка с паспортомjs: неизвестная стратегия аутентификации «локальная»

Я разрабатываю приложение nodejs и использую паспортные данные для аутентификации. Я использую локальную стратегию паспорта. Но когда я пытаюсь войти в систему, я получаю следующую ошибку:

Вот мой файл паспорт-config.js:

И ниже мой файл RegistrationsController.js, в котором находится мой api аутентификации,

Я просматривал код последние 2 дня, но пока не смог определить ошибку. Я установил оба модуля: passport и passport-local . Любая помощь будет принята с благодарностью.

3 ответа

В этом коде есть синтаксическая ошибка. usernameField: ’emailAddress’ Необходимо передать в конструкторе LocalStrategy вот так .

Сделать npm install —save passport-local затем в app.js включите эту строку var LocalStrategy = require(«passport-local»); затем используйте это промежуточное ПО:

Это происходило со мной, потому что, хотя мой файл app.ts импортировал конфигурацию паспорта, я не назначал ее никаким маршрутам, поэтому файл никогда не анализировался. Я использовал его внутри контроллера для аутентификации POST /login .

Заявление об ограничении ответственности . Я не уверен, что слово «проанализировано» является правильным, но, похоже, так оно и было, потому что console.log(‘xfngr’) в этом файле не выводился до тех пор, пока я не поставил маршрут в.

Я добавил маршрут, который использовал свойство из passportConfig , и он снова начал работать.

Источник

Unknown authentication strategy «local» #18

Hi,my english is a little.
I Install and run the code, I register a new user and send messages, but when I logout and try to login again with the username and password the app show error 500

Unknown authentication strategy «local»

error: Sending 500 («Server Error») response:
Error: Unknown authentication strategy «local»
at attempt (c:nodejssailngnode_modulespassportlibmiddlewareauthentica
te.js:166:37)
at authenticate (c:nodejssailngnode_modulespassportlibmiddlewareauthe
nticate.js:342:7)
at Authenticator.passport.callback (c:nodejssailngapiservicespassport.j
s:250:40)
at Authenticator.bound [as callback](c:nodejssailngnode_modulessailsno
de_moduleslodashdistlodash.js:729:21)
at Object.AuthController.callback (c:nodejssailngapicontrollersAuthCont
roller.js:121:14)
at bound (c:nodejssailngnode_modulessailsnode_moduleslodashdistlodas
h.js:729:21)
at routeTargetFnWrapper (c:nodejssailngnode_modulessailslibrouterbind
.js:179:5)
at callbacks (c:nodejssailngnode_modulessailsnode_modulesexpresslibr
outerindex.js:164:37)
at param (c:nodejssailngnode_modulessailsnode_modulesexpresslibroute
rindex.js:138:11)
at pass (c:nodejssailngnode_modulessailsnode_modulesexpresslibrouter
index.js:145:5)
at nextRoute (c:nodejssailngnode_modulessailsnode_modulesexpresslibr
outerindex.js 💯 7)
at callbacks (c:nodejssailngnode_modulessailsnode_modulesexpresslibr
outerindex.js:167:11)
at c:nodejssailngnode_modulessailslibrouterbind.js:187:7
at c:nodejssailngapipoliciespassport.js:32:7
at SessionStrategy.strategy.pass (c:nodejssailngnode_modulespassportlib
middlewareauthenticate.js:318:9)
at SessionStrategy.authenticate (c:nodejssailngnode_modulespassportlib
strategiessession.js:67:10) [Error: Unknown authentication strategy «local»]

I use Windows 8 and Firefox 36.0.4 for this test

The text was updated successfully, but these errors were encountered:

Источник

Error: Unknown authentication strategy «local.signup» #1

I did everything the same up to «local. signup», and it gives me this error.
I wish you could help me.

Error: Unknown authentication strategy «local.signup».

at attempt (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulespassportlibmiddlewareauthenticate.js:186:37)
at authenticate (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulespassportlibmiddlewareauthenticate.js:362:7)
at handleReturn (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpress-promise-routerlibexpress-promise-router.js:24:27)
at C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpress-promise-routerlibexpress-promise-router.js:56:9
at handleReturn (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpress-promise-routerlibexpress-promise-router.js:24:27)
at C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpress-promise-routerlibexpress-promise-router.js:56:9
at Layer.handle [as handle_request] (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpresslibrouterroute.js:137:13)
at Route.dispatch (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpresslibrouterroute.js:112:3)
at Layer.handle [as handle_request] (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpresslibrouterlayer.js:95:5)
at C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpresslibrouterindex.js:281:22
at Function.process_params (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpresslibrouterindex.js:335:12)
at next (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpresslibrouterindex.js:275:10)
at Function.handle (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpresslibrouterindex.js:174:3)
at router (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpresslibrouterindex.js:47:12)
at Layer.handle [as handle_request] (C:UsersSEJEZARA.SEJEZARADocumentsPMmod_projnode_modulesexpresslibrouterlayer.js:95:5)

The text was updated successfully, but these errors were encountered:

It will be best if i saw your code.
Send me github link to your code

Источник

These are the partial NestJS code snippets I have. I am trying to implement the passport local strategy for getting the username and password. I am getting -Error: Unknown authentication strategy «local», in the controller file when using the auth guard.

AuthModule.ts

import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { UserModule } from 'src/user/user.module';
import { JwtAuthController } from './jwt-auth.controller';
import { JwtAuthService } from './jwt-auth.service';
import { JwtStrategy } from './jwt.strategy';
import { LocalStrategy } from './local.strategy';

@Module({
  imports: [
    UserModule,
    PassportModule,
    JwtModule.register({
      secret: process.env.SECRETKEY,
      signOptions: { expiresIn: '3600s' }
    })
  ],
  controllers: [JwtAuthController],
  providers: [JwtAuthService, LocalStrategy, JwtStrategy],
  exports: [JwtAuthService],
})
export class JwtAuthModule {}

local.strategy.ts

import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtAuthService } from './jwt-auth.service';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy, 'local') {
  constructor(private authService: JwtAuthService) {
    super();
  }

  async validate(username: string, password: string): Promise<any> {
    const user = await this.authService.validateUser({username, password});
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

app.controller.ts

import { Body, Controller, Get, Post, Req, UnauthorizedException, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { JwtAuthService } from './jwt-auth/jwt-auth.service';

@Controller()
export class AppController {

  constructor(private readonly authService: JwtAuthService)  {}
  
  @UseGuards(AuthGuard('local'))
  @Post('/auth/login')
  async login(@Req() req) {
    return this.authService.login(req.user)
  }
  
}

I am getting the following error on calling /auth/login API

[Nest] 26753  - 10/31/2021, 22:08:18   ERROR [ExceptionsHandler] Unknown authentication strategy "local"
Error: Unknown authentication strategy "local"

Am I missing anything? Thanks in advance.

1) Solution

just add the PassportModule and LocalStrategy in app.module .it will be fixed

@Module({
  imports: [PassportModule],
  providers: [AuthService,LocalStrategy],
 })
 export class AppModule {}
2) Solution

Fix Bug https://github.com/nestjs/nest/issues/4646

File AUTH.ts

enter code here

import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { UserModule } from 'src/user/user.module';
import { JwtAuthController } from './jwt-auth.controller';
import { JwtAuthService } from './jwt-auth.service';
import { JwtStrategy } from './jwt.strategy';
import { LocalStrategy } from './local.strategy';

@Module({
imports: [
UserModule,
PassportModule.register({defaultStrategy:'local'}),
JwtModule.register({
  secret: process.env.SECRETKEY,
  signOptions: { expiresIn: '3600s' }
})
],
controllers: [JwtAuthController],
providers: [JwtAuthService, LocalStrategy, JwtStrategy],
exports: [JwtAuthService],
})
export class JwtAuthModule {}
3) Solution

Such an old question with no answers…

In my case I was having sort of an cyclic dependency issue. Or at least it was what it looked like. Cyclic deps can be either on nest side or even on node.js require side (on the second case we end up with empty imports).

Case 1:

@Injectable()
export class MyLocalStrategy extends PassportStrategy(PassportLocalStrategy) {
  hello = 'hello'

  constructor(private authService: AuthService) {
    console.log('load local strategy')
  }
}


@Module({
  imports: [
    CommonModule,
    PassportModule,
    JwtModule.registerAsync({
      async useFactory(config: ConfigService) {
        const jwtSecret = config.get('APP_KEY')
        const expiresIn = config.get('AUTH_TOKEN_EXPIRED')
        return {
          secret: jwtSecret,
          signOptions: {
            expiresIn,
          },
        }
      },
      inject: [ConfigService],
    }),
  ],
  providers: [
    RoleService,
    JwtStrategy,
    JwtService,
    AuthService,
  ],
  controllers: [AuthController],
  exports: [AuthService],
})
export class AuthModule {
  constructor(private moduleRef: ModuleRef) {}

  onModuleInit() {
    const moduleRef = this.moduleRef
    console.log('init auth module')
    const local = moduleRef.get(MyLocalStrategy)
    const auth = moduleRef.get(AuthService)
    console.log('my modules', { local, auth }, local?.hello)
  }
}

In this case the «load local strategy» never got logged. Yet «my modules» logged an empty localStrategy instance, without my «hello» property. Weird!

I hacked a fix by moving the class instantiation to a factory provider, and by requiring the dependencies with ModuleRef. The following excerpt worked fine.

@Module({
  imports: [
    CommonModule,
    PassportModule,
    JwtModule.registerAsync({
      async useFactory(config: ConfigService) {
        const jwtSecret = config.get('APP_KEY')
        const expiresIn = config.get('AUTH_TOKEN_EXPIRED')
        return {
          secret: jwtSecret,
          signOptions: {
            expiresIn,
          },
        }
      },
      inject: [ConfigService],
    }),
  ],
  providers: [
    RoleService,
    JwtStrategy,
    JwtService,
    AuthService,
    {
      provide: MyLocalStrategy,
      useFactory: (moduleRef: ModuleRef) => {
        const auth = moduleRef.get(AuthService)
        console.log('local strat factory', { auth })
        return new MyLocalStrategy(auth)
      },
      inject: [ModuleRef],
    },
  ],
  controllers: [AuthController],
  exports: [AuthService],
})
export class AuthModule {
  constructor(private moduleRef: ModuleRef) {}

  onModuleInit() {
    const moduleRef = this.moduleRef
    console.log('init auth module')
    const local = moduleRef.get(MyLocalStrategy)
    const auth = moduleRef.get(AuthService)
    console.log('local', { local, auth }, local?.hello)
  }
}

I also tried factory + injecting AuthService directly (through providers array, instead of using ModuleRef). I got a null AuthService.

Probably some dependency cycle on the node.js module imports, tough neither eslint or nest wouldn’t say anything.

4) Solution

Check to see if your auth module is being imported in your entry file. app.module.ts.

My auth-module.ts

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { UsersModule } from 'src/users/users.module';
import { AuthService } from './auth.service';
import { LocalStrategy } from './local.strategy';

@Module({
 imports:[UsersModule,PassportModule],
 providers: [AuthService,LocalStrategy]
})
export class AuthModule {}

My app module

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';
import { UsersModule } from 'src/users/users.module';
import { AuthService } from './auth.service';
import { LocalStrategy } from './local.strategy';

@Module({
  imports:[UsersModule,PassportModule],
 providers: [AuthService,LocalStrategy]
})
export class AuthModule {}
5) Solution

NestJs encourages scalability and therefore organizes your code in modules.
Instead of calling JwtAuthService method in the AppController, do it in the JwtAuthController. Your code should look like this:

import { Body, Controller, Get, Post, Req, UnauthorizedException, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { JwtAuthService } from './jwt-auth.service';

@Controller('auth')
export class JwtAuthController {
  constructor(private readonly authService: JwtAuthService)  {}
  
  @Post('/login')
  @UseGuards(AuthGuard('local'))
  async login(@Req() req) {
    return req.user
  }
  
}

Nest will then instantiate all providers in the JwtAuthModule such that it will be available in it’s controller (JwtController).

You Can always optimize your code by moving AuthGuard to it own file local.guard.ts given you the possibility to do any additional business logic.

import { ExecutionContext } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Request } from 'express';

export class LocalGuard extends AuthGuard('local') {}
6) Solution

You need to import the module that implements the authentications.

It can be inside app.module.ts or inside another module that is connected to it.

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';
import { UsersModule } from './users/users.module';

@Module({
    imports: [UsersModule, AuthModule],
    controllers: [AppController],
    providers: [AppService],
})
export class AppModule {}
7) Solution

I have the same issue with you. My solution is importing LocalStrategy class to module file, in which I use AuthGuard for API endpoint.

For example: in file user.controller.ts I have AuthGuard('local') in the endpoint /login with method POST

//user.controller.ts

@UseGuards(AuthGuard('local'))
@Post('login')
async login (@Request() req: any) {
  return req.user;
}

In my case, I just add LocalStrategy class (I also have this class in local.strategy.ts like you) in module file:

//user.module.ts

@Module({
  imports: [
    ...
    LocalStrategy,
  ],
  controllers: [UserController],
  ...
}

Conclusion, NestJs is quite complicated in importing modules, don’t forget to import what you want into other modules. Good luck!

Comments Section

in which module AppController lives?

AppController is in app.module.ts. I have exported auth.service.ts from the auth.module and auth.module is imported in app.module.ts

Is your JwtAuthService REQUEST scoped?

I tried adding defaultStrategy, but it still is not working. I am getting the same error.

I am new to NESTjs. How can I find out if the JwtAuthService REQUEST scoped?

Try to add the AuthModule to your imports of app.module.ts.

@adhinarayan did you get a solution? I am also facing the same problem not sure how to resolve this.

how did you resolve this @adhinarayan?

Had the same issue here with cyclic dependency. I was injecting the @Inject(REQUEST) in a service.

Related Topics
javascript
authentication
passport.js
nestjs
passport-local

Mentions
Adhi Narayan
Prakit Worarakuksorn
Marco Kuidja
Wkrueger
Mhmmdamiwn
Abdurrahman Y
Ampomah Winston

References
stackoverflow.com/questions/69788605/nestjs-error-unknown-authentication-strategy-local

I am following this tutorial on creating an authentication system with passport in Nodejs

Currently I am trying to make the signup form work, but it gives this error:

Error: Unknown authentication strategy "local-signup"
    at attempt (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules/passport/lib/middleware/authenticate.js:173:37)
    at authenticate (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules/passport/lib/middleware/authenticate.js:349:7)
    at Layer.handle [as handle_request] (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/jarno/0__projects/nodejs/EasyOrders_2.3.0/node_modules...

I am pretty sure that the config/passport.js file isn’t seen by the routes/users.js file, but as I am a beginner I can’t seem to find a solution to my problem.

/routes/users.js

var express = require('express');
var router = express.Router();
var passport = require('passport');
require('../config/passport');

/* GET users listing. */
router.get('/login', function(req, res){
  res.render('login', {
    title: 'Login'
  });
});

router.get('/signup', function(req, res){
  res.render('signup', {
    title: 'signup'
  });
});

router.get('/logout', function(req, res){
  res.logout();
  res.redirect('/users/login')
});

/* POST users listing */
router.post('/signup', passport.authenticate('local-signup', {
  successRedirect : '/profile', // redirect to the secure profile section
  failureRedirect : '/signup', // redirect back to the signup page if there is an error
  failureFlash : true // allow flash messages
}));

/* functions */
function isLoggedIn(req, res, next) {

  if (req.isAuthenticated())
    return next();

  res.redirect('/users/login');
}

module.exports = router;

/config/passport.js

// config/passport.js
var passport = require('passport');
// load all the things we need
var LocalStrategy   = require('passport-local').Strategy;

// load up the user model
var User            = require('../models/user');

// expose this function to our app using module.exports
module.exports = function(passport) {

    // =========================================================================
    // passport session setup ==================================================
    // =========================================================================
    // required for persistent login sessions
    // passport needs ability to serialize and unserialize users out of session

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    // =========================================================================
    // LOCAL SIGNUP ============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use('local-signup', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
      function(req, email, password, done) {

          // asynchronous
          // User.findOne wont fire unless data is sent back
          process.nextTick(function() {

          // find a user whose email is the same as the forms email
          // we are checking to see if the user trying to login already exists
            User.findOne({ 'local.email' :  email }, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(err);

                // check to see if theres already a user with that email
                if (user) {
                    return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
                } else {

                    // if there is no user with that email
                    // create the user
                    var newUser            = new User();

                    // set the user's local credentials
                    newUser.local.email    = email;
                    newUser.local.password = newUser.generateHash(password);

                    // save the user
                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }

            });

            });

      }));

};

/app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var session = require('express-session');

var configDB = require('./config/database.js');

mongoose.connect(configDB.url);
require('./config/passport');

// init app
var app = express();
var index = require('./routes/index');
var users = require('./routes/users');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use(session({ secret: 'godaddy420' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

app.use(function (req, res, next) {
  res.locals.path = req.path;
  next();
});

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;


config/password.js exports a function but you never call this function. In app.js, you should have something like that :

require('./config/passport')(passport);

#node.js #typescript #passport.js #nestjs #passport-local

#node.js #машинописный текст #passport.js #гнездышко #паспорт-местный

Вопрос:

У меня есть этот код в NestJS со следующими файлами ниже, но теперь в нем написано «Неизвестная стратегия аутентификации «локальная»», я уже искал решения, и все они указывают на ошибку импорта, но у меня есть локальная стратегия, импортированная в auth.module и app.module (я уже протестировал ее удаление из app.module, но это ничего не меняет).

приложение.модуль.ts

 import { Module } from '@nestjs/common';  import { AppController } from './app.controller';  import { AppService } from './app.service';  import { ThrottlerModule } from '@nestjs/throttler';  import { MongooseModule } from '@nestjs/mongoose';  import { AuthModule } from './auth/auth.module';  import { UsersModule } from './users/users.module';  import { LocalStrategy } from './auth/local.strategy';   @Module({  imports: [  MongooseModule.forRoot(  'mongodb srv://user:password@db.db.mongodb.net/db?retryWrites=trueamp;w=majority',  ),  ThrottlerModule.forRoot({  ttl: 60,  limit: 10,  }),  AuthModule,  UsersModule,  ],  controllers: [AppController],  providers: [AppService, LocalStrategy],  })  export class AppModule {}  

auth.модуль.ts

 import { Module } from '@nestjs/common';  import { AuthService } from './auth.service';  import { UsersModule } from '../users/users.module';  import { PassportModule } from '@nestjs/passport';  import { LocalStrategy } from './local.strategy';  import { JwtModule } from '@nestjs/jwt';  import { JwtStrategy } from './jwt.strategy';  import 'dotenv/config';   @Module({  imports: [  UsersModule,  PassportModule,  JwtModule.register({  secret: process.env.JWTSECRET,  signOptions: { expiresIn: '60s' },  }),  ],  providers: [AuthService, LocalStrategy, JwtStrategy],  exports: [AuthService],  })  export class AuthModule {}  

local.strategy.ts

 import { Strategy } from 'passport-local';  import { PassportStrategy } from '@nestjs/passport';  import { Injectable, UnauthorizedException } from '@nestjs/common';  import { AuthService } from './auth.service';   @Injectable()  export class LocalStrategy extends PassportStrategy(Strategy) {  constructor(private authService: AuthService) {  super({ usernameField: 'email' });  }   async validate(email: string, password: string): Promiselt;anygt; {  const user = await this.authService.validateUser(email, password);  if (!user) {  throw new UnauthorizedException();  }  return user;  }  }  

app.controller.ts

 import {  Controller,  Request,  Post,  UseGuards,  Res,  Get,  Body, } from '@nestjs/common'; import { AuthService } from './auth/auth.service'; import { MakeAuthDto } from './auth/dto/make-auth.dto'; import { JwtAuthGuard } from './auth/jwt-auth.guard'; import { LocalAuthGuard } from './auth/local-auth.guard'; import { Roles } from './utils/decorators/roles.decorator'; import { Role } from './utils/enums/role.enum'; import { RolesGuard } from './utils/guards/roles.guard';  @Controller() export class AppController {  constructor(private authService: AuthService) {}   @UseGuards(LocalAuthGuard)  @Post('auth/login')  async login(  @Body() _: MakeAuthDto,  @Request() req,  @Res({ passthrough: true }) res,  ) {  console.log(req.user);  const access_token = await this.authService.login(req.user);  res.cookie('jwt', access_token);  return req.user;  }   @UseGuards(JwtAuthGuard, RolesGuard)  @Roles(Role.Admin)  @Get('tests')  getProfile(@Request() req) {  return req.user;  } }  

local-auth.guard.ts

 import { Injectable } from '@nestjs/common';  import { AuthGuard } from '@nestjs/passport';   @Injectable()  export class LocalAuthGuard extends AuthGuard('local') {}  

auth.service.ts

 import { Injectable } from '@nestjs/common'; import { UsersService } from 'src/users/users.service'; import { JwtService } from '@nestjs/jwt'; import { UserDocument } from 'src/users/entities/user.entity';  @Injectable() export class AuthService {  constructor(  private usersService: UsersService,  private jwtService: JwtService,  ) {}   async validateUser(email: string, pass: string): Promiselt;UserDocument | anygt; {  const user = await this.usersService.findOne(email);  if (user amp;amp; (await user.compareHash(pass))) {  const { password, ...result } = user.toObject();  await this.usersService.updateLastLogin(user._id);  return result;  }  return null;  }   async login(user: UserDocument): Promiselt;stringgt; {  const payload = { email: user.email, sub: user._id, roles: user.roles };  return this.jwtService.sign(payload);  } }  

jwt-auth.guard.ts

 import { Injectable } from '@nestjs/common';  import { AuthGuard } from '@nestjs/passport';   @Injectable()  export class JwtAuthGuard extends AuthGuard('jwt') {}  

jwt.strategy.ts

 import { ExtractJwt, Strategy } from 'passport-jwt'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable } from '@nestjs/common'; import 'dotenv/config';  const cookieExtractor = function (req) {  let token = null;  if (req amp;amp; req.cookies) {  token = req.cookies['jwt'];  }  return token; };  @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) {  constructor() {  super({  jwtFromRequest: ExtractJwt.fromExtractors([cookieExtractor]),  ignoreExpiration: false,  secretOrKey: process.env.JWTSECRET,  });  }   async validate(payload: any) {  return { userId: payload.sub, email: payload.email, roles: payload.roles };  } }  

введите описание изображения здесь

Ни один подобный вопрос о stackoverflow не решил мою проблему, кто-нибудь знает, что это может быть?

Комментарии:

1. Не уверен, что это технически проблема, но с новейшей версией passport 0.5.0 вам нужно позвонить passport.initialize() , например, app.use(passport.initialize()) для приложения на основе express. Интересно, может ли это каким-то образом быть причиной.

2. @AlexanderStaroselsky Куда мне нужно это поместить?

3. Ну, в стандартном экспресс-приложении это было бы просто что-то вроде этого в главном файле app.js . Вы можете попробовать просто выполнить use инструкцию в своем main.ts (файле инициализации) или аналогичном. import * as passport from 'passport'; //.. app.use(passport.initialize());

4. Область действия вашего UsersService запроса ограничена?

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.


Answers of
> Error: Unknown authentication strategy “local”

When I try to login I get an ‘Unknown w3coded strategy passport authentication strategy «local» error’. Can w3coded strategy passport anybody explain what I’m doing wrong?,

w3coded strategy passport

w3coded strategy passport

Changed w3coded strategy passport to module.exports = function(passport). App wil w3coded strategy passport start now, but I get the same error ‘Unknown w3coded strategy passport authentication strategy «local»‘
w3coded strategy passport
– NVO
Jan 11 ’17 at 10:50
w3coded strategy passport

,I’m new to NodeJS and I w3coded strategy passport try to build a login/registration system. w3coded strategy passport Registration works fine but I’m currently unable w3coded strategy passport to login.

import passport config after initializing passport.

app.use(passport.initialize());
app.use(passport.session());
// Add the line below, which you're missing:
require('./path/to/passport/config/file')(passport);
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy; /* this should be after passport*/



 passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
      if (err) { return done(err); }
      if (!user) {
        return done(null, false, { message: 'Incorrect username.' });
      }
      if (!user.validPassword(password)) {
        return done(null, false, { message: 'Incorrect password.' });
      }
      return done(null, user);
    });
  }
));

this fix the error. need to use ‘local’ when you create a new LocalStrategy

passport.use('local', new LocalStrategy({
    usernameField:'useName',
    passwordField: 'password',
    passReqToCallback: true

Current topics : Error: Unknown authentication strategy “local”

Newly Added Questions

Понравилась статья? Поделить с друзьями:
  • Error unknown authentication strategy jwt
  • Error unity log valheim
  • Error unity log missingmethodexception
  • Error unit1 pas 62 missing operator or semicolon
  • Error unit1 pas 37 expected but found