npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nestjs-oauth2-library

v0.1.4

Published

nestjs-oauth2-library es una librería que proporciona una solución sencilla y flexible para la autenticación OAuth2 en aplicaciones NestJS. Esta librería está diseñada para facilitar la integración con servidores de identidad que soportan el flujo de cont

Downloads

16

Readme

nestjs-oauth2-library

nestjs-oauth2-library es una librería que proporciona una solución sencilla y flexible para la autenticación OAuth2 en aplicaciones NestJS. Esta librería está diseñada para facilitar la integración con servidores de identidad que soportan el flujo de contraseña (password grant type).

Instalación

Para instalar la librería, usa npm o yarn:

  npm install nestjs-oauth2-library

Configuración

Paso 1: Configurar las Variables de Entorno Crea un archivo .env en el directorio raíz de tu aplicación con las siguientes configuraciones Si deseas utilizar validación por usuario y contraseña:

OAUTH2_BASIC_USER=user
OAUTH2_BASIC_PASSWORD=password
OAUTH2_TOKEN_URL=https://localhost:9443/oauth2/token
OAUTH2_AUTH_BASIC=true
OAUTH2_INTROSPECTION_URL=https://localhost:9443/oauth2/introspect
OAUTH2_USERINFO_URL=https://localhost:9443/oauth2/userinfo

o utilizas validación por client credentials:

OAUTH2_TOKEN_URL=https://localhost:9443/oauth2/token
OAUTH2_CLIENT_ID=client_id
OAUTH2_CLIENT_SECRET=client_secret
OAUTH2_INTROSPECTION_URL=https://localhost:9443/oauth2/introspect
OAUTH2_USERINFO_URL=https://localhost:9443/oauth2/userinfo

Paso 2: Importar y Configurar el Módulo en tu Aplicación En tu módulo principal (AppModule), importa y configura ConfigModule y AuthModule Si utilizas validación por usuario y contraseña

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { OAuth2Module } from 'nestjs-oauth2-library';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    OAuth2Module.register({
      tokenUrl: process.env.OAUTH2_TOKEN_URL,
      authBasic: process.env.OAUTH2_AUTH_BASIC,
      userBasic: process.env.OAUTH2_BASIC_USER,
      passwordBasic: process.env.OAUTH2_BASIC_PASSWORD
      introspectionUrl: process.env.OAUTH2_INTROSPECTION_URL,
    }),
  ],
})
export class AppModule {}

o validación por client credentials

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { OAuth2Module } from 'nestjs-oauth2-library';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    OAuth2Module.register({
      tokenUrl: process.env.OAUTH2_TOKEN_URL,
      clientId: process.env.OAUTH2_CLIENT_ID,
      clientSecret: process.env.OAUTH2_CLIENT_SECRET,
      introspectionUrl: process.env.OAUTH2_INTROSPECTION_URL,
    }),
  ],
})
export class AppModule {}

Paso 3: Usar los Guards en tus Controladores Para proteger tus endpoints, usa los guards proporcionados por la librería en tus controladores:

import { Controller, Get, UseGuards } from '@nestjs/common';
import { OAuth2AuthGuard, OAuth2ScopesGuard, Scopes } from 'nestjs-oauth2-library';
import { ApiOAuth2 } from '@nestjs/swagger';

@Controller('secure')
export class AppController {
  @Get()
  @UseGuards(OAuth2AuthGuard, OAuth2ScopesGuard)
  @Scopes('my_scope')
  @ApiOAuth2(['my_scope'])
  getSecureData() {
    return { message: 'This is a secure endpoint' };
  }
}

Opcional: Para obtener datos del usuario mediante el token asegurarse de agregar la url de userInfo en OAUTH2_USERINFO_URL:

import { Controller, Get, UseGuards } from '@nestjs/common';
import { OAuth2AuthGuard, OAuth2ScopesGuard, Scopes, OAuth2Strategy } from 'nestjs-oauth2-library';
import { ApiOAuth2 } from '@nestjs/swagger';

@Controller('secure')
export class AppController {
  constructor(
    private readonly oauth2Strategy: OAuth2Strategy
  ) {}

  @Get()
  @UseGuards(OAuth2AuthGuard, OAuth2ScopesGuard)
  @Scopes('my_scope')
  @ApiOAuth2(['my_scope'])
  getSecureData(@Req() request: Request) {
    const token = request.headers.authorization?.split(' ')[1];
    if (!token) {
      throw new UnauthorizedException('Token is missing');
    }
    const userInfo = await this.oauth2Strategy.getUserInfo(token);
    return { message: 'This is a secure endpoint' };
  }
}

Licencia

Este proyecto está licenciado bajo la licencia MIT.