你如何使用curl授权C#web api调用?

时间:2014-03-04 17:41:09

标签: c# php curl asp.net-web-api

我有一个使用Forms身份验证的标准C#web api:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace API
{
    [Authorize]
    public class TestController : ApiController
    {
        public object Get(string tunnel)
        {

            return new
                {
                    test = "whatever"
                };
        }
    }
}

我想通过PHP curl请求访问它:

$ch = curl_init();

$data = array();
$username = 'test';
$password = 'test';

$auth_header = 'Authorization: Basic ' . base64_encode($username . ':' . $password);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', $auth_header)); // doesn't work
curl_setopt($ch, CURLOPT_HEADER, TRUE);
//curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  //Also doesn't work
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

// execute cURL
$result = curl_exec($ch);
curl_close($ch);

我已尝试使用CURLOPT_USERPWD和头文件进行授权基本操作,如上面的代码,但都不起作用。他们都回来了“消息”:“此请求已拒绝授权。”

添加CORS标头后,这是完整的错误消息:

"HTTP/1.1 401 Unauthorized Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.0 X-AspNet-Version: 4.0.30319 X-MiniProfiler-Ids: ["a26902e9-d6ef-4a7b-910f-be8a8cd99c85","4db4f730-97c9-4492-9b57-b97ab72f0b49","f524ee6f-c8a6-47aa-8db7-681f7f15c162"] X-SourceFiles: =?UTF-8?B?QzpcZGV2XHR1bm5lbGRhdGFcVHVubmVsRGF0YVxhcGlcU2FsZXNDb3N0Y29UZXN0?= X-Powered-By: ASP.NET Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS Access-Control-Allow-Headers: Content-Type Date: Wed, 05 Mar 2014 17:01:44 GMT Content-Length: 61 {"Message":"Authorization has been denied for this request."}"

您如何对API进行身份验证?

1 个答案:

答案 0 :(得分:0)

服务器api是否允许跨域允许?

header('Access-Control-Allow-Origin:*'); header('Access-Control-Allow-Methods:GET,POST');

试试。