Magento – 401 unauthorized due to directory protection on magento 2 project

.htaccesshttp-error-401magento-2.1magento2

Is there a way to pass basic authorization and bearer authorization in postman for accessing Magento 2 rest api's. I have defined the directory protection using .htaccess and .htpassword.
For getting a token I can pass basic auth to get a token. But to use that token in other rest calls I need to pass the token using bearer in Authorization
When I submit a call it says 401 unauthorized. It is due to the directory protection credentials when the are not supplied. I need to know either we could bypass or is there a way we could both pass basic and bearer authorization for testing in postman or something to do in .htaccess file.

In short directory protection is for Magento 2 store and I need this, but for api's is there any solution to handle this?

Best Answer

In short, I don't think there's a way to pass both Auth headers and have it work. What you can do is add the following line to your apache2 config:

Require expr %{REQUEST_URI} =~ m#^/index.php/rest/.*#

Or, in context:

    <Directory /path/to/directory/>
        AuthType Basic
        AuthName "Password Required"
        AuthUserFile "/etc/apache2/.htpasswd"
        AllowOverride all
        Require valid-user
        Require expr %{REQUEST_URI} =~ m#^/index.php/rest/.*#
   </Directory>

This will allow you to access the REST API without having to provide Basic Auth while preserving Basic authentication for the rest of the site.