Как реализовать Passport. js Azure Стратегия переноса AD (OpenID) в NestJS - PullRequest
0 голосов
/ 04 марта 2020

Следуя документации для гнезда js и паспорта, у меня есть следующая реализация.

Я начал с настройки гнезда по умолчанию, новый тест проверки гнезда, затем я добавил папку аутентификации в sr * 1033. * папка, в которой находятся расположенные ниже модули aad-auth.gaurd, aad.strategy и auth.module.

Затем я добавил новую охрану к маршруту по умолчанию в app.controller.ts

I подтвердил настройку Azure App Registration, успешно использовав ее в качестве C# Web API, поэтому сторона Azure настроена правильно.

Мне не нужно выдавать JWT, поскольку это передний конец Azure AD, этот токен-носитель передается в API в заголовке. Там нет никаких полезных ошибок, просто 500 внутренних ошибок. Я замечаю много запросов Github на документацию по внедрению Azure AD с гнездом вместе с любым провайдером потока OAuth (facebook, google), но пока этот запрос все еще открыт.

Не уверен, что реализовано неправильно Любые рекомендации или предложения будут оценены по исправлению кода ниже.

Документация: Гнездо JS: https://docs.nestjs.com/techniques/authentication Паспорт: http://www.passportjs.org/packages/passport-azure-ad/

// auth / aad.strategy.ts

import { BearerStrategy } from 'passport-azure-ad';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, ValidationPipe } from '@nestjs/common';

@Injectable() 
export class AADStrategy extends PassportStrategy(BearerStrategy) {
    constructor () {
        super({
            identityMetadata: "https://login.microsoftonline.com/<tenant>.onmicrosoft.com/v2.0/.well-known/openid-configuration",
            clientID: "<clientid>",
            issuer: null,
            audience: null,
            loggingLevel: "info",
            passReqToCallback: false
        })
    }

    async validate(payload: any){
        console.log(payload);
        return(payload);    
    }
}

// auth / aad-auth.gaurd

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

@Injectable()
export class AADAuthGaurd extends AuthGuard('aad') {}

// auth / auth.module.ts

import { Module } from '@nestjs/common';
import { AADStrategy } from './aad.strategy'

@Module({
    imports: [
        AADStrategy,
    ],
    providers: [
        AADStrategy,
    ]
})
export class AuthModule {}

// app.controller.ts

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { AADAuthGaurd } from './auth/aad-auth.gaurd';


@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @UseGuards(AADAuthGaurd)
  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

1 Ответ

0 голосов
/ 05 марта 2020

Я решил проблему, вот рабочий код, сжатый в один файл.

//app.controller.ts

import { Controller, Get, UseGuards } from '@nestjs/common';
import { AppService } from './app.service';
import { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { BearerStrategy } from 'passport-azure-ad'
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class AzureADStrategy extends PassportStrategy(BearerStrategy, 'oauth-bearer')
{
  constructor()
  {
    super({
      identityMetadata: `https://login.microsoftonline.com/<tenant>.onmicrosoft.com/.well-known/openid-configuration`,
      clientID: 'client id from azure app',
    })
  }

  async validate(response: any)
  {
    const { unique_name }: {unique_name: string} = response;
    if (unique_name) return unique_name;
    else return null;
  }
}

@Controller()
export class AppController {
  constructor() {}

  @Get('unprotected')
  unprotected() : string {
    return 'Unprotected';
  }

  @UseGuards(AuthGuard('oauth-bearer'))
  @Get('protected')
  protected() : string {
    return 'Protected';
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...