RestSharp HttpBasicAuthentication - example

本文关键字:example HttpBasicAuthentication RestSharp | 更新日期: 2023-09-27 18:06:25

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

RestSharp HttpBasicAuthentication - example

new SimpleAuthenticator("username", username, "password", password) did NOT with me。

var client = new RestClient("http://example.com");
client.Authenticator = new HttpBasicAuthenticator(userName, password);
var request = new RestRequest("resource", Method.GET);
client.Execute(request);

来自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方法)。

关于饼干,看看这个:https://msdn.microsoft.com/en-us/library/system.windows.application.setcookie.aspx

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

希望有所帮助

我使用了以下方法:

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

可选的回答你的第一个问题关于检索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;

到目前为止,上面的大多数例子都是我过去的做法。但是今天早上我更新到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);
var byteArray = System.Text.Encoding.ASCII.GetBytes("username:password");
request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(byteArray));