Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8779803
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T19:53:21+00:00 2026-06-13T19:53:21+00:00

I’ve created a custom voter that denies access to my API if the request

  • 0

I’ve created a custom voter that denies access to my API if the request doesn’t contain a valid auth header. It’s based on a combination of two cookbook entries:
http://symfony.com/doc/current/cookbook/security/voters.html and http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html

<?php

namespace Acme\RestBundle\Security\Authorization\Voter;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\NonceExpiredException;
use Monolog\Logger;

class ApiClientVoter implements VoterInterface
{
    protected $container;
    protected $nonceCacheDir;

    /**
     * We inject the full service container due to scope issues when
     * injecting the request.
     *
     * @param ContainerInterface $container
     * @param string $nonceCacheDir
     */
    public function __construct(ContainerInterface $container, $nonceCacheDir)
    {
        $this->container     = $container;
        $this->nonceCacheDir = $nonceCacheDir;
    }

    public function supportsAttribute($attribute)
    {
        // we won't check against a user attribute, so we return true
        return true;
    }

    public function supportsClass($class)
    {
        // our voter supports all type of token classes, so we return true
        return true;
    }

    public function vote(TokenInterface $token, $object, array $attributes)
    {
        if ($this->authenticate()) {
            return VoterInterface::ACCESS_ABSTAIN;
        }

        return VoterInterface::ACCESS_DENIED;
    }


    /**
     * Checks for an authentication header in the request and confirms
     * the client is valid.
     *
     * @return bool
     */
    protected function authenticate()
    {
        $request = $this->container->get('request');

        if ($request->headers->has('x-acme-auth')) {

            $authRegex = '/ApiKey="([^"]+)", ApiDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';

            if (preg_match($authRegex, $request->headers->get('x-acme-auth'), $matches)) {
                $apiClient = $this->container->get('in_memory_user_provider')->loadUserByUsername($matches[1]);

                if ($apiClient && $this->validateDigest($matches[2], $matches[3], $matches[4], $apiClient->getPassword())) {
                    return true;
                }
            }
        } else {
            $this->container->get('logger')->err('no x-acme-auth header present in request');
        }

        return false;
    }

    /**
     * Performs checks to prevent replay attacks and to validate
     * digest against a known client.
     *
     * @param string $digest
     * @param string $nonce
     * @param string $created
     * @param string $secret
     * @return bool
     * @throws AuthenticationException
     * @throws NonceExpiredException
     */
    protected function validateDigest($digest, $nonce, $created, $secret)
    {
        // Expire timestamp after 5 minutes
        if (time() - strtotime($created) > 300) {
            $this->container->get('logger')->err('Timestamp expired');

            return false;
        }

        if (!is_dir($this->nonceCacheDir)) {
            mkdir($this->nonceCacheDir, 0777, true);
        }

        // Validate nonce is unique within 5 minutes
        if (file_exists($this->nonceCacheDir.'/'.$nonce) && file_get_contents($this->nonceCacheDir.'/'.$nonce) + 300 > time()) {
            $this->container->get('logger')->err('Previously used nonce detected');

            return false;
        }

        file_put_contents($this->nonceCacheDir.'/'.$nonce, time());

        // Validate Secret
        $expected = base64_encode(sha1(base64_decode($nonce).$created.$secret, true));

        return $digest === $expected;
    }
}

The problem I’m having is that when my voter returns ACCESS_DENIED, I get a 500 error when the firewall redirects to the authentication entry point:

[2012-10-05 11:09:16] app.ERROR: no x-acme-auth header present in request [] []
[2012-10-05 11:09:16] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall\ExceptionListener::onKernelException". [] []
[2012-10-05 11:09:16] security.DEBUG: Access is denied (user is not fully authenticated) by "/home/phil/projects/acme/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/AccessListener.php" at line 70; redirecting to authentication entry point [] []
[2012-10-05 11:09:16] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelException". [] []
[2012-10-05 11:09:16] event.DEBUG: Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ExceptionListener::onKernelException". [] []
[2012-10-05 11:09:16] request.CRITICAL: Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException: Full authentication is required to access this resource. (uncaught exception) at /home/phil/projects/acme/vendor/symfony/symfony/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php line 109

What I actually want to happen is just to return a 403 response. Is it possible to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T19:53:22+00:00Added an answer on June 13, 2026 at 7:53 pm

    Exceptions caught by the kernel always return HTTP 500. (code).

    You’ll have to return your own response if authentication is invalid.

    use Symfony\Component\HttpFoundation\Response;
    $response = new Response();
    
    $response->setContent('<html><body><h1>Bad Credentials</h1></body></html>');
    $response->setStatusCode(403);
    $response->headers->set('Content-Type', 'text/html');
    
    // prints the HTTP headers followed by the content
    $response->send();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a small JavaScript validation script that validates inputs based on Regex. I
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I am doing a simple coin flipping experiment for class that involves flipping a
I know there's a lot of other questions out there that deal with this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.