Rom*_*maS 16 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);
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Authorization: Basic YWRtaW46MjI=在服务器端处理此字段?我从这个标题中获取用户名和密码吗?我需要基于安全令牌进行简单的身份验证,但找不到描述此过程所有方面的示例.有人能指出我的一些完整的例子,包括客户端和服务器端(并使用RestSharp).
Ger*_*ell 19
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);
Run Code Online (Sandbox Code Playgroud)
以下对我有用:
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;
}
Run Code Online (Sandbox Code Playgroud)
来自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);
Run Code Online (Sandbox Code Playgroud)
为此请求生成的网址为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
希望能帮助到你
到目前为止,上面的大多数例子都是我以前的做法。然而今天早上我更新到版本 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33543 次 |
| 最近记录: |