使用外部REST api进行身份验证

本文关键字:身份验证 api REST 外部 | 更新日期: 2024-09-23 11:09:00

我正在尝试使用一个外部REST api,该api最近由一家外部公司开发。他们为我提供了一些Java代码来展示如何连接到它并检索数据,但到目前为止,我在C#MVC 4中没有得到任何结果。目前我甚至无法登录系统。凭据是正确的,使用我在其他地方找到的示例似乎没有帮助。

工作的Java代码:

try{
  ClientConfig client_config = new ClientConfig();
  client_config.register(new HttpBasicAuthFilter(username,password));
  Client client = ClientBuilder.newClient(client_config);
  WebTarget web_target = client.target(url);
  Invocation.Builder invocation_builder = web_target.request();
  //This GET does the login with basic auth
  this.populateFromResponse(invocation_builder.get());
}
catch(final Exception e){
  System.out.println(e.toString());
}

好吧,这里有一些我在C#中没有的对象,很明显,但我所尝试的一切都还没有成功。

我已经尝试在请求的标题中放置信息:

request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(username + ":" + password));

没有cookie,也尝试过:

request.Credentials = new NetworkCredential(username, password);

什么都没有。如果我尝试这样做,没有收到cookie,并且仍然试图访问api的任何其他部分,那么我会收到401(未授权)错误。如果我只是尝试访问api的登录部分,request.GetResponse();不会抛出错误。

我是REST服务的新手,所以任何帮助/指导都将不胜感激。我之所以这么问,是因为我查到的其他东西似乎都不起作用。

编辑以下是我构建请求的方式:

var request = (HttpWebRequest)WebRequest.Create(HostUrl + path);
request.Method = "GET";
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
var response = request.GetResponse() as HttpWebResponse;

编辑#2感谢@BrianP的回答,这让我更好地解决了这个问题。以下是我当前的代码(以及从这个问题的回答中收集cookie的添加内容),它最终返回了一个成功代码:

var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;
var client = new HttpClient(handler);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password)));
client.BaseAddress = new Uri(HostUrl);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(HostUrl + "/api/login/").Result;
var responseCookies = cookies.GetCookies(new Uri(HostUrl)).Cast<Cookie>()

告诉我此代码是否有改进。再次感谢!

使用外部REST api进行身份验证

public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
    string authInfo = userName + ":" + userPassword;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
    req.Headers["Authorization"] = "Basic " + authInfo;
}

提取自:http://blog.kowalczyk.info/article/at3/Forcing-basic-http-authentication-for-HttpWebReq.html

编辑:基于评论。

HttpRequestMessage requestMsg = new HttpRequestMessage();
string data = username + ":" + password;
requestMsg.Headers.Authorization = new AuthenticationHeaderValue("Basic", data);