Question

The FOSRestBundle is working perfectly in my project but without authentication. Now, my goal is to make my requests with auth.

To do so, I added this firewall in security.yml

firewalls:
    # ...
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            remember_me: true
            login_path:     /login
            check_path:     /login_check
            default_target_path: minn_ads_default_index 
            csrf_provider: form.csrf_provider
        remember_me: 
            key: %secret%    
    rest_api:
        pattern: ^/api/
        stateless: true
        http_basic:
            provider: fos_userbundle
    # ...    
access_control:
    # ...    
    - { path: ^/api/, role: IS_AUTHENTICATED_FULLY }

To check authentification in curl command, I tried this command:

curl -i \
-H 'Accept: application/json' \
-H 'Authorization:Basic dG9uaXZkdjoxMjM0' \
http://localhost/tuto/app_dev.php/api/test/1

where dG9uaXZkdjoxMjM0 = encode_base64('tonivdv:1234')

The result is:

HTTP/1.1 302 Found
Date: Fri, 11 Apr 2014 13:56:08 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: PHP/5.4.9-4ubuntu2.4
Set-Cookie: PHPSESSID=4dtr168vmj1eg523a07kbkjkh1; path=/
Cache-Control: no-cache
Location: http://localhost/tuto/web/app_dev.php/login
Vary: Accept-Language
X-Debug-Token: 220df7
Transfer-Encoding: chunked
Content-Type: application/json

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="refresh" content="1;url=http://localhost/tuto/web/app_dev.php/login" />

        <title>Redirecting to http://localhost/tuto/web/app_dev.php/login</title>
    </head>
    <body>
        Redirecting to <a href="http://localhost/tuto/web/app_dev.php/login">http://localhost/tuto/web/app_dev.php/login</a>.
    </body>
</html>

So I am wondering if the CSRF token of the FOSUserBundle is the cause for not being able to get authenticated in the CURL command?

Was it helpful?

Solution

well, your rest_api firewall will never be used, as it is after the main firewall which will always match. This means that your API is secured through the stateful form_login auth, not through http_basic.

firewalls:

   rest_api:
     pattern: ^/api/
     stateless: true
     http_basic:
        provider: fos_userbundle

main:
    pattern: ^/
    form_login:
        provider: fos_userbundle
        remember_me: true
        login_path:     /login
        check_path:     /login_check
        default_target_path: minn_ads_default_index 
        csrf_provider: form.csrf_provider
    remember_me: 
        key: %secret%    

access_control:
# ...    
- { path: ^/api/, role: IS_AUTHENTICATED_FULLY }

OTHER TIPS

I found the solution.

I just need to define my rest_api firewall before the main firewall.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top