我正在使用最新的 MEAN Stack 技术创建一个博客。登录用户可以创建一个具有“管理员”和“主持人”角色的新用户。
该路由受到保护,目前只有登录用户才能访问它。这是用于检查用户是否经过身份验证的中间件。
//check_auth.js
const jwt = require('jsonwebtoken');
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(' ')[1];
jwt.verify(token, 'my_jwt_secret');
next();
} catch (error) {
res.status(401).json({ message: 'Auth failed!'});
}
};Run Code Online (Sandbox Code Playgroud)
我应用这个中间件来保护对我的某些路由的未经授权的访问。我想创建一个类似的中间件,在其中检查用户是否是管理员。所以我可以在创建用户的路由上应用这个中间件,这样只有授权用户和具有“admin”角色的用户才能创建新用户。
我认为这有助于创建中间件。当用户登录时,id、电子邮件和角色存储在 jwt 中。
router.post("/login", (req, res, next) => {
let fetchedUser;
User.findOne({ email: req.body.email })
.then(user => {
if (!user) {
return res.status(401).json({
message: "Auth failed"
});
}
fetchedUser = user;
return bcrypt.compare(req.body.password, user.password);
})
.then(result => {
if (!result) { …Run Code Online (Sandbox Code Playgroud)我正在使用 slim 3 构建控制器/中间件,我希望从附加到一个组的中间件中将一些数据传递到我的控制器 - 操作中的 $args 参数。
这是一些代码:
class MyController
{
protected $container;
public function __construct(ContainerInterface $container) {
$this->container = $container;
}
public function index(Request $request, Response $response, $args) {
return $this->container->get('renderer')->render($response, "index.html.twig", $args);
}
}
Run Code Online (Sandbox Code Playgroud)
class MyMiddleware
{
public function __invoke(Request $request, Response $response, $next)
{
// do some stuff to inject further down to $args some data
return $next($request, $response);
}
}
Run Code Online (Sandbox Code Playgroud)
$app->group('/group', function () use ($app){
//routes
})->add(new MyMiddleware());
Run Code Online (Sandbox Code Playgroud)
我的用例是将内容发送到由这些控制器的操作呈现的所有视图,因此我也可以使用其他方法来执行此操作:)
谢谢。
我有一个中间件来记录此服务访问。但我在谷歌上搜索了几次后,对进行单元测试感到困惑。我还没有找到解决这个问题的正确方法
package accesslog
import (
"net/http"
"time"
"github.com/go-chi/chi/middleware"
"transactionService/pkg/log"
)
func Handler(logger log.Logger) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = log.WithRequest(ctx, r)
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
start := time.Now()
defer func() {
logger.With(ctx, "duration", time.Since(start), "status", ww.Status()).
Infof("%s %s %s %d %d", r.Method, r.URL.Path, r.Proto, ww.Status(), ww.BytesWritten())
}()
next.ServeHTTP(ww, r.WithContext(ctx))
}
return http.HandlerFunc(fn)
}
}
Run Code Online (Sandbox Code Playgroud) 我创建了一个中间件来检查新用户电子邮件是否已得到验证middleware/verify_email.js:
export default function (context) {
if (context.$auth.loggedIn && !context.$auth.user.email_verified_at) {
console.log('logged in with email not verified');
return context.redirect('/auth/verify');
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我在全局设置了这个中间件nuxt.config.js:
router: {
middleware: ['auth', 'verify_email']
},
Run Code Online (Sandbox Code Playgroud)
但似乎我遇到了无限循环,页面没有响应。当我评论重定向行时,它会再次响应。
NavigationDuplicated:避免冗余导航到当前位置:“/auth/verify”。
我可能需要为页面的中间件添加一个例外,auth/verify但我不知道如何添加。
知道我应该如何解决这个问题吗?
我对特定的路由集使用特定的中间件
r.Route("/platform", func(r chi.Router) {
r.Use(authService.AuthMiddleware)
r.Get("/{id}/latest", RequestPlatformVersion)
})
Run Code Online (Sandbox Code Playgroud)
现在我如何访问这个中间件id中的 url 参数AuthMiddleware
func (s *Service) AuthMiddleware(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
fmt.Println(chi.URLParam(r, "id"))
id := chi.URLParam(r, "id")
if id > 100 {
http.Error(w, errors.New("Error").Error(), http.StatusUnauthorized)
return
}
}
return http.HandlerFunc(fn)
}
Run Code Online (Sandbox Code Playgroud)
但是,即使正在运行中间件并且正在调用特定路由,id 参数也会打印为空字符串
我正在尝试使用 JWT 验证通过中间件进行身份验证,但不幸的是,我遇到了一些无法找到解决方案的错误。
./node_modules/jwa/index.js:3:0
Module not found: Can't resolve 'crypto'
Import trace for requested module:
./node_modules/jws/lib/sign-stream.js
./node_modules/jws/index.js
./node_modules/jsonwebtoken/verify.js
./middleware.ts
https://nextjs.org/docs/messages/module-not-found
You're using a Node.js module (crypto) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
Run Code Online (Sandbox Code Playgroud)
包.json
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@emotion/react": "^11.9.3",
"@emotion/styled": "^11.9.3",
"@mui/material": "^5.8.6",
"@prisma/client": "^4.0.0",
"axios": "^0.27.2",
"buffer": "^6.0.3",
"cookie": "^0.5.0",
"jsonwebtoken": "^8.5.1",
"next": "12.2.0",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-hook-form": "^7.33.0" …Run Code Online (Sandbox Code Playgroud) 我在 nextjs 中使用一个中间件(https://nextjs.org/docs/advanced-features/middleware)
但我无法向 api 发送请求并且它向我显示错误
unhandledRejection:类型错误:无法删除属性“Symbol(set-cookie)”
我的 miiddleware.js
import { get } from 'Base'
import { redirect } from 'next/dist/server/api-utils'
import { NextResponse } from 'next/server'
export async function middleware(req) {
const data = await fetch(process.env.NEXT_PUBLIC_API_BASE+"/seosite/getallredirect" )
console.log(data )
const { pathname ,origin } = req.nextUrl
const redirect = data?.redirects?.find(i.oldUrl == pathname);
if(redirect){
if(redirect?.code == 301 || redirect?.code == null )
return NextResponse.redirect(origin+redirect.oldUrl)
}
return NextResponse.next()
}Run Code Online (Sandbox Code Playgroud)
我确实有很多域,我想将它们重定向到一个主域。
域列表:
example.comexample1.comexample2.comexample3.com我想从其他域重定向的主域是example.com
有一个很好的答案可以将服务器端的 Next.js 重定向到不同的路径。
Next.js >= 12现在您可以使用中间件进行重定向,在pages文件夹(或pages内的任何子文件夹)内创建一个_middleware.js文件
Run Code Online (Sandbox Code Playgroud)import { NextResponse, NextRequest } from 'next/server' export async function middleware(req, ev) { const { pathname } = req.nextUrl if (pathname == '/') { return NextResponse.redirect('/hello-nextjs') } return NextResponse.next() }
注意:对于 Next.js v13,您必须middleware.js在 Next.js 的根目录中创建该文件,而不是像pages/_middleware.js该答案中提到的那样。
如果我尝试重定向到另一个域,根目录中的 middleware.ts 中的 TypeScript 代码如下所示:
/* eslint-disable @next/next/no-server-import-in-page */
import { NextResponse, NextRequest } from 'next/server'
export async function middleware(req: NextRequest) {
const …Run Code Online (Sandbox Code Playgroud) export default defineNuxtRouteMiddleware(async(to, from) => {
const loggedIn = useState('loggedIn', () => false)
if(loggedIn.value == false) {
if(to.path == '/auth/login') {
await navigateTo(to.path)
}else if(to.path == '/') {
await navigateTo('/auth/login')
}else if(!(to.path == '/auth/login') or !(to.path == '/')) {
//return abortNavigation()
await navigateTo('/auth/login')
}else {
return abortNavigation()
}
}else {
console.log('to:', to.path)
console.log('from:', from.path)
await navigateTo(to.path)
}
})
Run Code Online (Sandbox Code Playgroud)
如果我浏览到以下几行,问题是"await navigateTo('/auth/login')"上面的代码不起作用".../dashboard",但当任何页面至少有一个"await navigateTo('/dashboard')". 它也适用于"return abortNavigation"
---
"else if(!(to.path == '/auth/login') or !(to.path == '/')) { …Run Code Online (Sandbox Code Playgroud) 我是Ring的新手(以及一般的Clojure服务器端编程).我有一个基于铃声的应用程序,在"开发模式"下运行良好,即它可以监听localhost:3000并且它会做出适当的响应.作为部署此应用程序的一部分,我想将应用程序的基本URL更改为类似的内容myserver.com/analytics/v1,以便例如localhost:3000/foo现在应该转到的请求myserver.com/analytics/v1/foo.
我想我在这里有两个密切相关的问题:我怎么能告诉Ring/Jetty只听一个不是服务器根URL的某个URL?我如何设置它以便我可以添加另一个应用程序(例如myserver.com/analytics/v2),而不会停止第一个应用程序的停机时间?我是否需要编写另一个Ring应用程序来监听myserver.com/并将请求路由到我的其他应用程序?
middleware ×10
next.js ×3
go ×2
go-chi ×2
node.js ×2
nuxt.js ×2
action ×1
clojure ×1
controller ×1
docker ×1
express ×1
javascript ×1
jetty ×1
jwt ×1
mongodb ×1
navigation ×1
nuxt3 ×1
parameters ×1
php ×1
proxy ×1
redirect ×1
ring ×1
slim-3 ×1
unit-testing ×1
url ×1
vuejs3 ×1