RestSharp HttpBasicAuthentication - 示例

43

我有一个使用RestSharp和WEB API服务的WPF客户端。我尝试按照以下方式使用HttpBasicAuthenticator

```HTML

我有一个使用RestSharp和WEB API服务的WPF客户端。我尝试按照以下方式使用HttpBasicAuthenticator

```
RestRequest login = new RestRequest("/api/users/login", Method.POST);
var authenticator = new HttpBasicAuthenticator("admin","22");
authenticator.Authenticate(Client, login);
IRestResponse response = Client.Execute(login); 

POST请求看起来像这样:

POST http://localhost/api/users/login HTTP/1.1
Authorization: Basic YWRtaW46MjI=
Accept: application/json, application/xml, text/json, text/x-json, text/javascript, text/xml
User-Agent: RestSharp/105.1.0.0
Host: dellnote:810
Content-Length: 0
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
  1. 如何在服务器端处理这个字段:Authorization: Basic YWRtaW46MjI=?我需要从这个头文件中获取用户名和密码吗?
  2. 如何将安全令牌从服务器返回给客户端,并在客户端保存它?

我需要基于安全令牌实现简单身份验证,但找不到描述该过程各方面的完整示例。请问有没有人能提供一个包含客户端和服务器端的完整示例(并使用RestSharp)。


您可以在下面看到我的答案。 - Felix Av
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/basic-authentication - ljgww
7个回答

68
< p > new SimpleAuthenticator("username", username, "password", password) 对我来说没有起作用。

然而,以下方法有效:

var client = new RestClient("http://example.com");
client.Authenticator = new HttpBasicAuthenticator(userName, password);

var request = new RestRequest("resource", Method.GET);
client.Execute(request);

9

来自 RestSharp 文档:

var client = new RestClient("http://example.com");
client.Authenticator = new SimpleAuthenticator("username", "foo", "password", "bar");

var request = new RestRequest("resource", Method.GET);
client.Execute(request);

这个请求生成的URL将会是http://example.com/resource?username=foo&password=bar
所以你可以像获取其他参数一样获取密码(虽然出于安全考虑,建议使用POST方法而非GET)。
至于Cookie,请查看此链接:https://msdn.microsoft.com/en-us/library/system.windows.application.setcookie.aspx

https://msdn.microsoft.com/en-us/library/system.windows.application.getcookie.aspx

希望有所帮助

我的第二个问题呢? - RomaS
我认为Cookie是一个不错的选择。 - Felix Av
我考虑过使用CookieContainer和FormsAuthentication.SetAuthCookie方法。但这更像是浏览器的方式(而我有WPF客户端)。我不确定cookie是否是正确的方式。 - RomaS
据我所知,您可以在WPF中使用cookies。我已经在答案中添加了链接。 - Felix Av
需要注意的是,如果您在代码顶部不包含“using RestSharp.Authenticators”,或者将“SimpleAuthenticator”替换为“RestSharp.Authenticators.SimpleAuthenticator”,则上述代码将失败。 - Kris Craig

8
以下方法适用于我:
private string GetBearerToken()
{
    var client = new RestClient("http://localhost");
    client.Authenticator = new HttpBasicAuthenticator("admin", "22");
    var request = new RestRequest("api/users/login", Method.POST);
    request.AddHeader("content-type", "application/json");
    request.AddParameter("application/json", "{ \"grant_type\":\"client_credentials\" }", ParameterType.RequestBody);
    var responseJson = _client.Execute(request).Content;
    var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
    if(token.Length == 0)
    {
        throw new AuthenticationException("API authentication failed.");
    }
    return token;
}

5
迄今为止,上面大多数的例子都是我以前的做法。然而,今天早上我更新到了109.0.1版本,并发现他们已经弃用了RestClient.Authenticator,现在使用RestClientOptions.Authenticator,如下所示:
string baseUrl = "https://yoururl.com";
var options = new RestClientOptions(baseUrl);
options.Authenticator = new HttpBasicAuthenticator("username", "password");

var client = new RestClient(options);

4
RestClient restClient = new RestClient(baseUrl);
restClient.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("admin","22");

RestRequest login = new RestRequest("/api/users/login", Method.POST);
IRestResponse response = restClient.Execute(login);

请解释您的代码是做什么的以及它如何实现;不要单独发布代码。 - M-Chen-3

2

关于从服务器端检索Auth Header值(Server Side)的替代答案,可以参考以下链接:如何从头部检索基本身份验证凭据?

private UserLogin GetUserLoginCredentials()
{
    HttpContext httpContext = HttpContext.Current;
    UserLogin userLogin;
    string authHeader = httpContext.Request.Headers["Authorization"];

    if (authHeader != null && authHeader.StartsWith("Basic"))
    {
        string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
        Encoding encoding = Encoding.GetEncoding("iso-8859-1");
        string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
        int seperatorIndex = usernamePassword.IndexOf(':');

        userLogin = new UserLogin()
        {
            Username = usernamePassword.Substring(0, seperatorIndex),
            Password = usernamePassword.Substring(seperatorIndex + 1)
        };
    }
    else
    {
        //Handle what happens if that isn't the case
        throw new Exception("The authorization header is either empty or isn't Basic.");
    }
    return userLogin;
}

这种方法的使用可能包括:

UserLogin userLogin = GetUserLoginCredentials();

同时也可以参考:WebAPI基础认证授权过滤器

关于第二个问题返回令牌的备选答案(服务器端):

var httpResponseMessage = Request.CreateResponse();

TokenResponse tokenResponse;
bool wasAbleToGetAccesToken = _identityServerHelper.TryGetAccessToken(userLogin.Username, userLogin.Password,
            platform, out tokenResponse);

httpResponseMessage.StatusCode = wasAbleToGetAccesToken ? HttpStatusCode.OK : HttpStatusCode.Unauthorized;
httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(tokenResponse),
            System.Text.Encoding.UTF8, "application/json");

return httpResponseMessage;

0
var byteArray = System.Text.Encoding.ASCII.GetBytes("username:password");
request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(byteArray));

您可以通过添加更多关于代码的信息和它如何帮助OP的内容来改进您的答案。 - Tyler2P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接