是否有可能用控制器/方法范围一覆盖全局范围后卫

时间:2019-07-19 17:01:00

标签: nestjs

我正在使用NestJS框架编写webAPI。我无法用放置在方法或控制器级别的那个来覆盖全局作用域保护。我的所有端点都将使用JWT验证防护,但其中一个用于登录系统。是否可以在根级别创建一个防护,而仅在单个方法级别使用private void UploadResizeImage() { string codigo = ""; string dano = ""; string nav = ""; string nombreArchivo = ""; string extension = ""; int cont = 0; int MaxWidthHeight = 1024; // This is the maximum size that the width or height file should have int factorConversion = 0; int newWidth = 0; int newHeight = 0; int porcExcesoImg = 0; Bitmap newImage = null; string directory = "dano"; System.Drawing.Image image = null; string targetPath = ""; try { if (!String.IsNullOrEmpty(Request.QueryString["codigo"]) && !String.IsNullOrEmpty(Request.QueryString["dano"]) && !String.IsNullOrEmpty(Request.QueryString["nav"])) { codigo = Request.QueryString["codigo"].ToString(); dano = Request.QueryString["dano"].ToString(); nav = Request.QueryString["nav"].ToString(); Directory.CreateDirectory(Server.MapPath(directory)); Directory.CreateDirectory(Server.MapPath(directory + "/" + nav)); string fechaHora = DateTime.Now.ToString("yyyyMMdd-HHmmss"); nombreArchivo = codigo + "-" + dano + "-" + fechaHora; string html = "<h4>Se cargaron con éxito estos archivos al servidor:</h4>"; if (UploadImages.HasFiles) { html += "<ul>"; foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles) { cont++; extension = System.IO.Path.GetExtension(UploadImages.FileName); targetPath = Server.MapPath("~/" + directory + "/" + nav + "/").ToString() + nombreArchivo + "-" + cont.ToString() + extension; if (extension.ToLower() == ".png" || extension.ToLower() == ".jpg") { Stream strm = null; strm = uploadedFile.InputStream; //strm = UploadImages.PostedFile.InputStream; using (image = System.Drawing.Image.FromStream(strm)) { string size = image.Size.ToString(); int width = image.Width; int height = image.Height; if (width > MaxWidthHeight || height > MaxWidthHeight) { porcExcesoImg = (width * 100) / MaxWidthHeight; // excessive size in percentage factorConversion = porcExcesoImg / 100; newWidth = width / factorConversion; newHeight = height / factorConversion; newImage = new Bitmap(newWidth, newHeight); var graphImage = Graphics.FromImage(newImage); graphImage.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphImage.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphImage.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; var imgRectangle = new Rectangle(0, 0, newWidth, newHeight); graphImage.DrawImage(image, imgRectangle); newImage.Save(targetPath, image.RawFormat); } else { uploadedFile.SaveAs(targetPath); } html += "<li>" + String.Format("{0}", uploadedFile.FileName) + "</li>"; } } } html += "</ul>"; listofuploadedfiles.Text = html; } else { listofuploadedfiles.Text = "No se ha selecionado ninguna imagen!"; } } else { listofuploadedfiles.Text = "No se recibieron los parámetros para poder cargar las imágenes!"; } } catch (Exception ex) { listofuploadedfiles.Text = ex.Message.ToString(); } } 装饰器覆盖此全局防护?

我尝试在@UseGuard()函数调用之前使用保护功能,并且还使用listen提供程序,但是在两种情况下,我都无法覆盖此行为。

代码示例: this blog post

2 个答案:

答案 0 :(得分:4)

只需加上我的2美分。

我没有定义OP那样的2个防护(rejectaccept),而是定义了一个自定义装饰器:

import { SetMetadata } from '@nestjs/common'

export const NoAuth = () => SetMetadata('no-auth', true)

拒绝防护(AuthGuard)使用Reflector来访问装饰器的元数据,并决定是否基于它来激活。

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { Observable } from 'rxjs'

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {

    const noAuth = this.reflector.get<boolean>('no-auth', context.getHandler())

    if(noAuth) return true

    // else your logic here
  }
}

然后在某个模块中全局绑定reject防护:

@Module({
  providers: [{
    provide: APP_GUARD,
    useClass: AuthGuard
  }]
})

并在需要的地方继续使用装饰器:

@NoAuth()
@Get() // anyone can access this
getHello(): string {
  return 'Hello Stranger!'
}

@Get('secret') // protected by the global guard
getSecret(): string {
  return 'ssshhh!' 
}

答案 1 :(得分:1)

发布问题后,我找到了解决问题的方法。我应该将一些自定义元数据添加到控制器中,并在防护装置中放置逻辑以读取该元数据。 我已经更新了代码示例。

相关问题