RestSharp无法使用Django Rest Framework进行身份验证

时间:2014-06-05 18:16:52

标签: rest django-rest-framework restsharp

我正在使用RestSharp在Djnago中使用基本身份验证的API。 我已经在Chrome的其余客户端工具中成功测试了API。但我无法使用RestSharp进行相同的API调用,它总是返回:

{"detail": "Authentication credentials were not provided."}

如果我使用设置:'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny',),解除Django中的身份验证,它可以工作,但是没有身份验证,这不是解决方案。

以下是RestSharp的代码:

        var client = new RestClient(host);

        client.Authenticator = new HttpBasicAuthenticator(username, password);

        var request = new RestRequest(service, Method.GET);

        var response = client.Execute(request) as RestResponse;

        Console.WriteLine(response.Content);

我不确定是否需要修复Django端或RestSharp端。 RestSharp的请求是否需要任何其他请求标头? 或者它是Django上的配置?

2 个答案:

答案 0 :(得分:1)

看看你的网址映射, 可能你需要以“' /'”结束你的名字。 例如。 您需要更改以下代码:

request.Resource = "myinfo";

为:

request.Resource = "myinfo/";

可能是因为它没有正确处理重定向。使用正确的URL应该修复它。

答案 1 :(得分:1)

您的问题在于此类身份验证。您正在使用"会话"种类身份验证,因此您必须先登录,然后存储会话cookie

示例:

 private RestClient RestCliente = new RestClient("http://yoursiteurl.com");

    private CookieContainer SessionCookie = new CookieContainer();

     private void ServiceSession() // once per session only
        {
            RestRequest login = new RestRequest("/api-auth/login/", Method.POST); // path to your login on rest-framework
            RestCliente.Authenticator = new HttpBasicAuthenticator("username", "password");


            IRestResponse loginresponse = RestCliente.Execute(login);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var cookie = loginresponse .Cookies.FirstOrDefault();
                SessionCookie.Add(new Cookie(cookie.Name, cookie.Value, cookie.Path, cookie.Domain));

            }

            RestCliente.CookieContainer = SessionCookie;


        }

然后,您可以简单地请求您的信息

示例:

private void InfoRequest()
    {
        RestRequest infoneeded= new RestRequest("/info/path/?format=json", Method.GET);

        IRestResponse response = RestCliente.Execute(infoneeded);

        Console.WriteLine(response.Content);
    }
相关问题