<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Fastify - No Authorization was found in request.headers]]></title><description><![CDATA[<p dir="auto">Кароче, попробовал я этот ваш Fastify, бля ну все шло гладко, уже там и репозитории и логику в сервисах прикрути.</p>
<p dir="auto">Дело дошло до регистрации и авторизации пользователей. И тут начались проблемы, эта <strong>дура</strong> по непонятным мне приничал нихуя не регистрирует заголовок <code>Authentication</code>.<br />
Кстати в <code>fastify.d.ts</code> я тоже все четко прописал по инструкции:</p>
<pre><code class="language-ts">import 'fastify';

declare module 'fastify' {
interface FastifyInstance {
    authenticate: (request: FastifyRequest, reply: FastifyReply) =&gt; Promise&lt;void&gt;;
  }
}
</code></pre>
<p dir="auto">Так вот эта сука, отдает токен можно посмотреть в <code>fastifyInstance.post('/token'...</code><br />
Казалось бы заебись, но по непонятным мне причинам не записывает нихуя в заголовок <code>Authentication</code>, я уже и так и сяк, но не пойму почему.</p>
<p dir="auto">Вынес пока все дерьмище в index.ts, может подскажет кто нибудь в чем может быть причина ? Молю <img src="https://forum.exlends.ru/assets/plugins/nodebb-plugin-emoji/emoji/android/1f625.png?v=1bd9ff6b60a" class="not-responsive emoji emoji-android emoji--disappointed_relieved" style="height:23px;width:auto;vertical-align:middle" title=":disappointed_relieved:" alt="😥" /></p>
<pre><code class="language-ts">import fastifyInstance from "./infrastructure/server/fastify";
import { registerRoutes } from "./app/app-module";
import { dataSourceInit } from "./infrastructure/lib/db/postgresql/connect-typeorm";
import fastifyFormbody from "@fastify/formbody";
import fastifyJwt from "@fastify/jwt";
import fp from 'fastify-plugin';

(async () =&gt; {
  try {
    
    fastifyInstance.register(fastifyFormbody);
    
    const authenticate = fp(async function (instance, opts) {
      instance.register(fastifyJwt, {
        secret: 'super-strong-secret',
        sign: { expiresIn: '7d' }
      });
      
      instance.decorate('authenticate', async function (request, reply) {
        try {
          console.log('Authorization header:', request.headers.authorization);
          await request.jwtVerify();
          console.log('User verified:', request.user);
        } catch (err) {
          console.log('Authentication error:', err);
          reply.send(err);
        }
      });
    });
    
    fastifyInstance.register(authenticate);
    
    fastifyInstance.post('/token', async (request, reply) =&gt; {
      const user = "user=exampleUser"
      if (!user) {
        reply.code(400).send({ error: 'User is required' });
      }
      const token = fastifyInstance.jwt.sign({ user });
      return { token };
    });
    
    fastifyInstance.get('/', { onRequest: fastifyInstance.authenticate }, async function (request, reply) {
      console.log(request.user);
      
      return request.user;
    });
    
    fastifyInstance.get("/protected", { onRequest: fastifyInstance.authenticate }, async (request, reply) =&gt; {
      try {
        return { message: "You are authenticated!", user: request.user };
      } catch (err) {
        return { message: "хуй за щеку" };
      }
    });
    
    fastifyInstance.register(registerRoutes);
    
    await fastifyInstance.listen({ port: 3009 });
    fastifyInstance.ready((err) =&gt; {
      dataSourceInit();
      if (err) {
        fastifyInstance.log.error(err);
        process.exit(1);
      } else {
        const address = fastifyInstance.server.address();
        if (typeof address === "string") {
          console.log(`Fastify прослушивание сокета ${address}`);
        } else {
          console.log(`Fastify прослушивание http://localhost:${address.port}`);
        }
      }
    });
  } catch (err) {
    fastifyInstance.log.error(err);
    process.exit(1);
  }
})();
</code></pre>
]]></description><link>https://forum.exlends.ru/topic/38/fastify-no-authorization-was-found-in-request-headers</link><generator>RSS for Node</generator><lastBuildDate>Wed, 20 May 2026 08:15:30 GMT</lastBuildDate><atom:link href="https://forum.exlends.ru/topic/38.rss" rel="self" type="application/rss+xml"/><pubDate>Sat, 09 Nov 2024 19:01:41 GMT</pubDate><ttl>60</ttl><item><title><![CDATA[Reply to Fastify - No Authorization was found in request.headers on Sat, 09 Nov 2024 20:34:41 GMT]]></title><description><![CDATA[<p dir="auto">Кароче решил проблему, все регистрировалось корректно - это я про регистрацию плагина и прочее.</p>
<p dir="auto">Вообщем, я забывал передавать в заголовке сам токен когда проверял защищенные роуты</p>
<p dir="auto"><img src="/assets/uploads/files/1731184460889-%D1%81%D0%BD%D0%B8%D0%BC%D0%BE%D0%BA-%D1%8D%D0%BA%D1%80%D0%B0%D0%BD%D0%B0-2024-11-09-%D0%B2-23.34.18.png" alt="Снимок экрана 2024-11-09 в 23.34.18.png" class=" img-fluid img-markdown" /></p>
<p dir="auto">Проблема решена!)</p>
]]></description><link>https://forum.exlends.ru/post/81</link><guid isPermaLink="true">https://forum.exlends.ru/post/81</guid><dc:creator><![CDATA[kirilljsx]]></dc:creator><pubDate>Sat, 09 Nov 2024 20:34:41 GMT</pubDate></item></channel></rss>