【发布时间】:2013-05-05 17:59:54
【问题描述】:
我想访问由 symfony2 和 FOSRestBundle 提供的 REST Web 服务。我使用 HTTP 基本身份验证。不幸的是,如果没有(正确)提供身份验证内容,我无法弄清楚如何取回 HTTP 代码 401 和 403。
这就是我使用 jquery/AJAX 调用服务的方式:
$.ajax({
url: url + "/api/places.json",
type: 'GET',
data: {data},
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader('Authorization', auth);
}
}).done( function(data, textStatus, xhr) {
console.log('JSONAdapter.findPlacesByUser '+xhr.status);
callback(data);
}).fail( function(xhr, err) {
console.log('JSONAdapter.findPlacesByUser ERROR '+err+': '+xhr.status+' '+xhr.responseText);
});
当我提供错误或没有授权数据时,“完成”和“失败”功能都不会执行。
即使有这些东西(在与我放置上述 AJAX 调用的文件相同的文件中)我也无法收到任何错误消息或状态代码:
$(document).ajaxError(function(event, jqxhr, settings, exception) {
console.log('ajaxError');
if(jqxhr.status == 403)
{
console.log('Not authorized');
}
});
这是我在 symfonys config.yml 中的 FOSRestBundle 配置:
twig:
debug: %kernel.debug%
strict_variables: %kernel.debug%
exception_controller: 'FOS\RestBundle\Controller\ExceptionController::showAction'
fos_rest:
view:
view_response_listener: 'force'
failed_validation: HTTP_BAD_REQUEST
default_engine: php
formats:
json: true
xml: false
rss: false
format_listener:
prefer_extension: true
body_listener:
decoders:
json: fos_rest.decoder.json
param_fetcher_listener: true
allowed_methods_listener: true
access_denied_listener:
json: true
exception:
codes:
'Symfony\Component\Routing\Exception\ResourceNotFoundException': 404
'Doctrine\ORM\OptimisticLockException': HTTP_CONFLICT
'Symfony\Component\Security\Core\Exception\AuthenticationException': 401
'Symfony\Component\Security\Core\Exception\AccessDeniedException': 403
security.yml:
jms_security_extra:
secure_all_services: false
expressions: true
security:
encoders:
XXXX\UserBundle\Entity\User:
algorithm: sha1
iterations: 1
encode_as_base64: false
providers:
api_users:
entity: { class: XXXXUserBundle:User, property: email }
firewalls:
rest_webservice:
pattern: ^/api
stateless: true
http_basic:
provider: api_users
realm: "XXXX API"
你看,我已经尝试了一些东西(例如最后两行)。但是现在我被卡住了,不知道从哪里开始调试。
当需要认证或认证失败时如何接收 HTTP 状态码?
任何帮助将不胜感激:-)
【问题讨论】:
-
你可以添加你的security.yml吗?
-
security.yml 添加 :-)
标签: jquery ajax symfony basic-authentication fosrestbundle