Логотип Security Authentication

Security Authentication

Сообщество
fatonh
security-authentication

Use when configuring Symfony Security — firewalls, authenticators, the User entity, password hashing, access control, and voters. Use when the task mentions login, authentication, authorization, roles, voter, firewall, or password.

Обзор

Издательfatonh
Репозиторийsymfony-skills
Название навыкаsecurity-authentication
Звёзды
36
Форки
3
Встроенные файлы
Только инструкции
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Файл SKILL.md, который модель загружает по необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Всё необходимое — в инструкциях

    Всё необходимое для модели содержится в инструкциях — никаких дополнительных файлов для синхронизации.

  • Открытый исходный код

    Опубликовано на GitHub: fatonh. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Security Authentication в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/fatonh/symfony-skills/tree/main/skills/security-authentication
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Новый навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/fatonh/symfony-skills.git /tmp/symfony-skills
mkdir -p .claude/skills
cp -r /tmp/symfony-skills/skills/security-authentication .claude/skills/security-authentication
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Security Authentication в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Security Authentication, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Security Authentication не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими API-ключами.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Symfony Security: Authentication & Authorization

The User entity

php
#[ORM\Entity(repositoryClass: UserRepository::class)]
#[ORM\Table(name: 'users')]
#[ORM\UniqueConstraint(name: 'uniq_users_email', fields: ['email'])]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    #[ORM\Id, ORM\Column(type: UuidType::NAME, unique: true)]
    private Uuid $id;

    #[ORM\Column(length: 180, unique: true)]
    private string $email;

    /** @var string[] */
    #[ORM\Column]
    private array $roles = [];

    #[ORM\Column]                          // the *hash*, never the plaintext
    private string $password;

    public function __construct(string $email)
    {
        $this->id = Uuid::v7();
        $this->email = $email;
    }

    public function getUserIdentifier(): string { return $this->email; }

    /** @return string[] */
    public function getRoles(): array
    {
        $roles = $this->roles;
        $roles[] = 'ROLE_USER';            // everyone is at least ROLE_USER
        return array_unique($roles);
    }

    public function getPassword(): string { return $this->password; }

    public function setHashedPassword(string $hash): void { $this->password = $hash; }

    public function eraseCredentials(): void { /* no plaintext held */ }
}

Password hashing — never roll your own

Use the hasher service; configure auto so Symfony picks the best algorithm (currently bcrypt/argon2) and can rehash on upgrade.

yaml
# config/packages/security.yaml
security:
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
php
// Hashing at registration
$user->setHashedPassword($this->passwordHasher->hashPassword($user, $plainPassword));
php
// ❌ NEVER
$user->setPassword(md5($plain));          // broken
$user->setPassword(hash('sha256', $plain)); // unsalted, fast = crackable

Firewalls & access control

yaml
security:
    providers:
        app_user_provider:
            entity: { class: App\Entity\User, property: email }

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        api:
            pattern: ^/api
            stateless: true                 # APIs are stateless (token auth)
            provider: app_user_provider
            jwt: ~                          # see jwt-authentication
        main:
            lazy: true
            provider: app_user_provider

    access_control:
        - { path: ^/api/login,  roles: PUBLIC_ACCESS }
        - { path: ^/api/admin,  roles: ROLE_ADMIN }
        - { path: ^/api,        roles: ROLE_USER }

access_control is coarse-grained (path + role). For per-object decisions, use voters.

Custom authenticator (when the built-ins don't fit)

php
final class ApiKeyAuthenticator extends AbstractAuthenticator
{
    public function __construct(private readonly UserRepository $users) {}

    public function supports(Request $request): ?bool
    {
        return $request->headers->has('X-API-KEY');
    }

    public function authenticate(Request $request): Passport
    {
        $apiKey = $request->headers->get('X-API-KEY');
        if (!$apiKey) {
            throw new CustomUserMessageAuthenticationException('No API key provided');
        }

        return new SelfValidatingPassport(
            new UserBadge($apiKey, fn (string $key) => $this->users->findByApiKey($key)),
        );
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $e): Response
    {
        return new JsonResponse(['title' => 'Authentication failed'], Response::HTTP_UNAUTHORIZED);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
    {
        return null; // continue the request
    }
}

Voters for object-level authorization

Authorization that depends on the specific object (owner, tenant, state) belongs in a voter, not in access_control or scattered if checks.

php
/** @extends Voter<string, Order> */
final class OrderVoter extends Voter
{
    public const VIEW = 'ORDER_VIEW';
    public const CANCEL = 'ORDER_CANCEL';

    protected function supports(string $attribute, mixed $subject): bool
    {
        return in_array($attribute, [self::VIEW, self::CANCEL], true) && $subject instanceof Order;
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();
        if (!$user instanceof User) {
            return false;
        }

        return match ($attribute) {
            self::VIEW   => $subject->getCustomerEmail() === $user->getUserIdentifier(),
            self::CANCEL => $subject->getCustomerEmail() === $user->getUserIdentifier()
                            && $subject->getStatus() === OrderStatus::Pending,
            default      => false,
        };
    }
}
php
// In the controller / handler
$this->denyAccessUnlessGranted(OrderVoter::CANCEL, $order);

Conventions

  • stateless: true for API firewalls — no session cookie.
  • Check authorization as close to the action as possible (#[IsGranted] attribute or denyAccessUnlessGranted).
  • Return 401 for unauthenticated, 403 for authenticated-but-forbidden.
  • Never trust $request for identity — read the authenticated user from the token / #[CurrentUser].
  • Enforce CSRF protection on session-based browser forms; stateless token APIs don't need it.

Gotchas

  • Agent hashes passwords with md5/sha1/sha256 — use the password_hasher (auto).
  • Agent stores or logs plaintext passwords — only the hash is persisted; eraseCredentials() clears any plaintext.
  • Agent puts owner/tenant checks in access_control or inline if — use a voter for object-level rules.
  • Agent makes the API firewall stateful (session) — set stateless: true.
  • Agent reads the user id from a request param/body — use the authenticated token / #[CurrentUser].
  • Agent returns 403 for unauthenticated requests (or 401 for forbidden) — 401 = who are you, 403 = not allowed.
  • Agent forgets ROLE_USER default in getRoles() — every authenticated user should have it.
  • Agent writes a custom login form auth from scratch — use form_login / the built-in authenticators, or json_login for APIs.

Часто задаваемые вопросы

Что делает навык ИИ Security Authentication?

Use when configuring Symfony Security — firewalls, authenticators, the User entity, password hashing, access control, and voters. Use when the task mentions login, authentication, authorization, roles, voter, firewall, or password.

Зачем использовать Security Authentication в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Security Authentication — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Security Authentication в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/fatonh/symfony-skills/tree/main/skills/security-authentication. TypingMind прочитает файл SKILL.md и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Security Authentication?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Security Authentication?

С любым количеством. Если модель поддерживает навыки, вы можете использовать с ней Security Authentication: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama и другие — всё в TypingMind с вашими собственными ключами API.

Бесплатен ли навык ИИ Security Authentication?

Да. Навык опубликован на GitHub автором fatonh по лицензии MIT. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это многоразовый набор инструкций, который объясняет модели ИИ, как выполнять конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты для вызова — код, который где-то выполняется и возвращает результат. Навык ИИ вместо этого даёт модели знания и порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все

Создайте свою рабочую ИИ-среду сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇