【问题标题】:RestSharp HttpBasicAuthentication - exampleRestSharp HttpBasicAuthentication - 示例
【发布时间】:2015-10-28 06:48:26
【问题描述】:

我有一个使用 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)。

【问题讨论】:

标签: c# authentication restsharp


【解决方案1】:

以下内容对我有用:

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;
}

【讨论】:

    【解决方案2】:
    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);
    

    【讨论】:

    • 请解释一下你的代码是做什么的以及它是怎么做的;永远不要自己发布代码。
    【解决方案3】:

    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);
    

    【讨论】:

      【解决方案4】:

      另外回答您关于从How can I retrieve Basic Authentication credentials from the header? 检索 Auth 标头值(服务器端)的第一个问题:

      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();
      

      也可以看看:A-WebAPI-Basic-Authentication-Authorization-Filter

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

      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;
      

      【讨论】:

        【解决方案5】:

        来自 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

        希望对你有帮助

        【讨论】:

        • 我的第二个问题呢?
        • 我认为饼干是要走的路
        • 我考虑过使用 CookieContainer 和 FormsAuthentication.SetAuthCookie 方法。但它更像是一种浏览器方式(我有 WPF 客户端)。我不确定 cookie 是否正确。
        • 据我所知,您可以在 WPF 中使用 cookie。我在答案中添加了链接
        • 需要注意的是,如果你没有在顶部包含“using RestSharp.Authenticators”,或者只是将“SimpleAuthenticator”替换为“RestSharp.Authenticators.SimpleAuthenticator”,上述代码将会失败。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多