Skip to content

Authorization

Stanislav Molchanovskiy edited this page Jul 17, 2022 · 5 revisions

Use WithTokenAuthorization method to pass access tokens to the request:

var client = NClientGallery.Clients.GetRest()
    .For<IMyClient>(host: "http://localhost:5000")
    .WithTokenAuthorization(scheme: "Bearer", token: "<token>")
    .Build();

You can use your implementation of IAccessTokens to get a token for a specific host:

internal class MyAccessTokens : IAccessTokens
{
    private static readonly Uri FirstUri = new Uri("http://localhost:5000");
    private static readonly Uri SecondUri = new Uri("http://localhost:8000");

    public IAccessToken? TryGet(Uri uri)
    {
        if (uri == FirstUri)
            return new AccessToken(scheme: "Bearer", token: "<token>");
        if (uri == SecondUri)
            return new AccessToken(scheme: "Basic", token: "<token>");
        return null;
    }
}

...

var myAccessTokens = new MyAccessTokens();

var client1 = NClientGallery.Clients.GetRest()
    .For<IMyClient>(host: "http://localhost:5000")
    .WithTokenAuthorization(myAccessTokens)
    .Build();

var client2 = NClientGallery.Clients.GetRest()
    .For<IMyClient>(host: "http://localhost:8000")
    .WithTokenAuthorization(myAccessTokens)
    .Build();

When using IAccessTokens, the token is obtained at every request, so you can update the token in runtime:

internal class MyAccessTokens : IAccessTokens
{
    public IAccessToken? TryGet(Uri uri)
    {
        if (uri.ToString() != "http://localhost:5000")
            return null;

        var tokenValue = GetTokenFromConfig();
        return new AccessToken(scheme: "Bearer", token: tokenValue);
    }
    
    private string GetTokenValueFromConfig()
    {
        ...
    }
}

If you do not have enough functionality for authorization, use the transport layer settings for authorization. For example, if you use NClient.Providers.Transport.SystemNetHttp package (default package) at the transport layer, then you can configure authorization in System.Net.Http.HttpClient and then use it in NClient.

Clone this wiki locally