RestSharp HttpBasicAuthentication - 示例

时间:2015-08-05 13:05:49

标签: c# authentication restsharp

我有一个使用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. 如何将安全令牌从服务器返回到客户端并将其保存在客户端?
  3. 我需要基于安全令牌进行简单的身份验证,但找不到描述此过程所有方面的示例。有人能指出我的一些完整的例子,包括客户端和服务器端(并使用RestSharp)。

5 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分: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);

为此请求生成的网址为http://example.com/resource?username=foo&password=bar

所以你得到的密码就像任何其他参数一样(但是出于安全考虑,建议使用POST方法然后GET)。

关于cookies,请查看: https://msdn.microsoft.com/en-us/library/system.windows.application.setcookie.aspx

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

希望有所帮助

答案 2 :(得分:1)

替代回答您关于从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;

答案 3 :(得分:0)

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

答案 4 :(得分:0)

以下内容对我有用:

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