RestSharp HttpBasicAuthentication - example

后端 未结 5 1477
梦毁少年i
梦毁少年i 2021-01-03 20:51

I have a WPF client using RestSharp and WEB API Service. I try to use HttpBasicAuthenticator as follows:

RestRequest login = new RestRequest(\"/         


        
5条回答
  •  伪装坚强ぢ
    2021-01-03 21:24

    The following worked for me:

    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>(responseJson)["access_token"].ToString();
        if(token.Length == 0)
        {
            throw new AuthenticationException("API authentication failed.");
        }
        return token;
    }
    

提交回复
热议问题