RestSharp HttpBasicAuthentication - example

后端 未结 5 1478
梦毁少年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<Dictionary<string, object>>(responseJson)["access_token"].ToString();
        if(token.Length == 0)
        {
            throw new AuthenticationException("API authentication failed.");
        }
        return token;
    }
    
    0 讨论(0)
  • 2021-01-03 21:27

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

    The following however worked:

    var client = new RestClient("http://example.com");
    client.Authenticator = new HttpBasicAuthenticator(userName, password);
    
    var request = new RestRequest("resource", Method.GET);
    client.Execute(request);
    
    0 讨论(0)
  • 2021-01-03 21:39
    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);
    
    0 讨论(0)
  • 2021-01-03 21:41

    Alternative answer your first question about retrieval of Auth Header values (Server Side) from How can I retrieve Basic Authentication credentials from the header?:

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

    Usage of this method might be:

    UserLogin userLogin = GetUserLoginCredentials();
    

    Also have a look at: A-WebAPI-Basic-Authentication-Authorization-Filter

    Alternative answer on second question about returning the token (Server Side):

    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;
    
    0 讨论(0)
  • 2021-01-03 21:44

    From RestSharp documentation:

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

    The URL generated for this request would be http://example.com/resource?username=foo&password=bar

    So you get the password just as any other parameter (although, it's recommended to use POST method then GET, for security reasons).

    As for the cookies, check this out: https://msdn.microsoft.com/en-us/library/system.windows.application.setcookie.aspx

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

    Hope it helps

    0 讨论(0)
提交回复
热议问题