我为 Rails 创建了一个自定义中间件,它将拦截所有请求并确保它来自授权的 IP,否则它应该提示输入基本的 http 身份验证用户/名密码。
目前看起来是这样的:
require 'net/http'
class AuthorizeEnvironment
def initialize(app)
@app = app
end
def call(env)
if AppConstants.approved_doximity_ips.include?(env["REMOTE_ADDR"])
@app.call(env)
elsif authorized?(env)
@app.call(env)
else
[403, {"Content-Type" => "text/html"}, ["Not Authorized on this environment."]]
end
end
def authorized?(env)
@auth ||= Rack::Auth::Basic::Request.new(env)
@auth.provided? && @auth.basic? && @auth.credentials && @auth.credentials == ['username', 'password']
end
end
Run Code Online (Sandbox Code Playgroud)
这段代码的问题是我似乎无法找到一种方法来触发浏览器上的 http 身份验证窗口。我查看了此内容,但没有看到任何明显的迹象表明这是如何完成的。
你能指出我正确的方向吗?
我正在开发(我和我的同事)一个应用程序,express js并且当您在服务器配置中添加太多中间件功能时,我一直在寻找有关任何性能问题的信息,但我没有找到任何相关信息。
例如,就我而言,我添加了典型的中间件:静态资源的处理程序、cookie解析器、body解析器、压缩器……我们正在考虑添加更多中间件,甚至是我们开发的自定义函数。
所以我的问题是,是否有任何时刻、任意数量的处理程序可能会导致应用程序出现性能问题?或者是否有与此相关的摘要或某人所做的任何测试?
谢谢。
我创建了一些带有一些逻辑的标准中间件,根据逻辑我需要调用一些第三方中间件。
中间件是使用 app.use() 添加的,这是我添加自定义中间件的地方。
一旦进入我的中间件,我就无法再访问 app.use(),如何调用中间件?
这是一些代码:
有任何想法吗 ?
const customerData = (req, res, next) => {
try {
console.log('Started');
if (process.env.STORE_CUSTOMER_DATA === 'true') {
// Here is some custom middleware that doesn't belong to me
//
// Returns a function (I confirmed it) ready to be called with res,req, next
//
let externalMiddlware = logger({
custom:true
});
// Do I return it ? Call it ? Trying everything and nothing seems to work
externalMiddlware(req,res,next); // ???
} else { …Run Code Online (Sandbox Code Playgroud) 我有一个应用程序,需要将其限制为少数几个 IP。我可以编写一个中间件,如果请求 IP 不在允许列表中,则返回,但是我希望这个过程尽可能高效。即我想尽早断开连接。我最早可以在什么阶段断开连接,最好是通过 HTTP 响应。我无法控制主机防火墙或边界防火墙来过滤流量,并且即使我控制了防火墙,我也无法提供 HTTP 响应。
另外,我希望能够获得 gin 中 HTTP 请求生命周期的描述。
我有自定义中间件。我尝试构造函数注入来注入我的 DbContext。但这不起作用。以下内容不起作用并给出 InvalidOperationException:无法从根提供程序解析作用域服务“MyDbContext”;
private MyDbContext _context;
public RequestResponseMiddleware(RequestDelegate next, MyDbContext context)
{
_next = next;
_context = context;
}
Run Code Online (Sandbox Code Playgroud)
但是当我在 InvokeAsync 方法中使用它作为参数时,它就可以工作。以下作品
public Task InvokeAsync(HttpContext context, MyDbContext _context)
{
}
Run Code Online (Sandbox Code Playgroud)
有谁知道原因吗?
我想弄清楚如何使用我的 ConfigService创建的,如此处所述。在我的应用程序的最顶层。
我的main.js文件看起来像这样:
import { NestFactory } from '@nestjs/core';
import { TypeormStore } from 'connect-typeorm';
import * as session from 'express-session';
import { getRepository } from 'typeorm';
import { Session } from '../../domains/session/Session';
import { AppModule } from './AppModule';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(session({
resave: false,
saveUninitialized: false,
store: new TypeormStore({
cleanupLimit: 2,
ttl: 86400
}).connect(getRepository(Session)),
secret: process.env.COOKIE_SECRET as string
}))
await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
我想要的是移动process.env.COOKIE_SECRET到内部的吸气剂ConfigService。我可以访问此级别的服务吗?
我的目标是编写一个中间件,负责记录对我的 API 的请求以及 API 对数据库中这些请求的响应。我已经制作了一个以类似方式处理异常的中间件,但我对此感到困惑。当你阅读有关中间件的 MSDN 时,你可以看到这张漂亮的图片:
这让您认为中间件 2 接收请求,对其进行某些操作并将其传递到中间件 3,然后一旦中间件 3 完成所有处理,它将控制权传递回中间件 2 进行其他处理。
我唯一不明白的是,如果 Middleware 2 Invoke() 方法仅在请求期间调用一次并且在响应期间不调用,如何记录响应?
启动.cs:
app.UseMiddleware<RequestLoggingMiddleware>();
Run Code Online (Sandbox Code Playgroud)
中间件:
public class RequestLoggingMiddleware
{
private readonly RequestDelegate nextMiddleware;
public RequestLoggingMiddleware(RequestDelegate nextMiddleware)
{
this.nextMiddleware = nextMiddleware;
this.options = options;
}
public async Task Invoke(HttpContext context)
{
System.Diagnostics.Debug.WriteLine("Middleware runs");
await nextMiddleware(context);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,我仅在初始请求期间但在做出响应之前在控制台中看到“中间件运行”一次。如何让它在响应周期内运行?
我正在使用 TypeScript 编写我的第一个 expressJs 应用程序。我得到了用于令牌验证的静态中间件方法,我需要将数据传递到下一个中间件:
static verifyAccessToken(req: Request, resp: Response, next: NextFunction) {
const AUTH_TOKEN = AccessTokenValidator.getTokenFromHeader(req, resp);
jwt.verify(AUTH_TOKEN, Config.JWT_SECRET, async (error: VerifyErrors | null, payload: any) => {
if (error) {
resp.status(401).send({message: "Token is invalid"});
}
// @ts-ignore
req.userRole = payload.rol;
next();
});
}
Run Code Online (Sandbox Code Playgroud)
如何在不使用“@ts-ignore”的情况下正确地将数据传递到下一个中间件?
在访问此路由之前通过中间件对用户进行身份验证。
当我tokenController.authUser作为中间件传递时,tokenService内部tokenController是undefined. 但是,当我将此方法作为路由内的函数而不是中间件运行时,它工作得很好。
server.post('/api/admin/test', { preHandler: [tokenController.authUser] }, async (request: any, reply: any) => {
return null
});
Run Code Online (Sandbox Code Playgroud)
令牌控制器:-
import { Users } from "@prisma/client";
import ITokenService from "../../services/tokenService/ITokenService";
import ITokenController from "./ITokenController";
export default class TokenController implements ITokenController {
private readonly tokenService: ITokenService;
constructor(_tokenService: ITokenService) {
this.tokenService = _tokenService;
}
async authUser(request: any, reply: any): Promise<Users | Error> {
const authHeader = request.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if …Run Code Online (Sandbox Code Playgroud) 我正在开发我的中间件,我想在用户登录后重定向用户。问题是 api 没有到达终点并且卡在中间件部分(根据我的观察)并且页面也没有重定向。
import { NextRequest, NextResponse } from "next/server";
export function middleware(req) {
const url = req.url;
if (url.includes("login")) {
return NextResponse.redirect("localhost:3000/home", req.url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/", "/api/login"],
};
Run Code Online (Sandbox Code Playgroud) middleware ×10
express ×3
node.js ×3
typescript ×3
javascript ×2
.net ×1
.net-core ×1
asp.net-core ×1
c# ×1
fastify ×1
go ×1
go-gin ×1
nestjs ×1
next.js ×1
rack ×1
ruby ×1