Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refit and authorization header

Currently, I am adding an authorization header to my request like this:

File: SomeFile.cs

public interface ITestApi
{
    [Get("/api/test/{id}")]
    Task<string> GetTest([Header("Authorization")] string authorization, int id);

    [Get("/api/tests/")]
    Task<string> GetTests([Header("Authorization")] string authorization);
}

File: SomeOtherFile.cs

var username = "xxx";
var password = "yyy";
var authHeader = "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
var baseAddress = "https://my.test.net";
ITestApi myApi = RestService.For<ITestApi>(baseAddress);

int id = 123;
var test= myApi.GetTest(authHeader, id);

var tests = myApi.GetTests(authHeader);

Is there a way to set the authHeader globally so that I don't have to pass it as a parameter to every call? (I am using Refit version 4.6.48). In other words, I'd like to be able to do the calls like this:

var test= myApi.GetTest(id);

var tests = myApi.GetTests();
like image 402
thd Avatar asked Oct 19 '18 07:10

thd


People also ask

What is an Authorisation header?

The HTTP Authorization request header can be used to provide credentials that authenticate a user agent with a server, allowing access to a protected resource. The Authorization header is usually, but not always, sent after the user agent first attempts to request a protected resource without credentials.

What is Authorization header in API?

What is an Authorization Request Header? The HTTP Authorization request header contains the credentials to authenticate a user agent with a server. APIs use authorization to ensure that client requests access data securely.

How do I add Authorization header in GET request?

To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.

What is bearer Authorization header?

Bearer authentication (also called token authentication) is an HTTP authentication scheme that involves security tokens called bearer tokens. The name “Bearer authentication” can be understood as “give access to the bearer of this token.”


2 Answers

I found a solution:

[Headers("Authorization: Basic")]
public interface ITestApi
{
    [Get("/api/test/{id}")]
    Task<string> GetTest(int id);

    [Get("/api/tests/")]
    Task<string> GetTests();
}


var username = "xxx";
var password = "yyy";
var authHeader = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
var baseAddress = "https://my.test.net";

var refitSettings = new RefitSettings()
{
    AuthorizationHeaderValueGetter = () => Task.FromResult(authHeader)
};

ITestApi myApi = RestService.For<ITestApi>(baseAddress, refitSettings);

int id = 123;
var test= myApi.GetTest(id);

var tests = myApi.GetTests();
like image 193
thd Avatar answered Sep 19 '22 11:09

thd


Refit has changed its approach. Now it uses the default .NET HttpHandler

var handler = new AuthHandler(credentials.Username, credentials.Password);
var githubApi = RestService.For<IGithubApi>(new HttpClient(handler)
                {
                    BaseAddress = new Uri("https://api.github.com")
                });


public class AuthHandler : HttpClientHandler
{
    private readonly string _username;
    private readonly string _password;

    public AuthHandler(string username, 
        string password)
    {
        _username = username;
        _password = password;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, 
        CancellationToken cancellationToken)
    {
        request.Headers.Add("User-Agent", "<your user name or app name>");
        request.Headers.Authorization = new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(
                $"{_username}:{_password}")));

        return await base.SendAsync(request, cancellationToken)
            .ConfigureAwait(false);
    }
}
like image 26
Andrew Chaa Avatar answered Sep 19 '22 11:09

Andrew Chaa