Unable to retrieve access token for use in authorisation headers in request to API

I apologize in advance for this being quite a long post, its just the situation is rather specific and I can’t find a solution anywhere.

I have been designing a Single Sign On system for the company I work for using ASP.NET and OpenIddict. As part of this work I have created a new “Admin” area for user management which acts as a client app separate from the Identity Provider. As the Identity Provider has access to the user database, I developed API calls that the Admin client app can send requests to in order for the Identity Provider to either retrieve or change user information on behalf of said client, meaning the access to user database lies solely with the Identity Provider rather than storing or accessing the information in two places.

At the moment, the HttpRequests that are sent to the API calls in the Identity Provider for user management are secured on the Admin client side, but not on the Identity Provider side. In the Admin client, the use of Authorization policies are in place and are implemented via the [Authorize (Policy = "AdminUser")] tag. Therefore, when the user makes the request on the Admin client, it checks that they are authenticated and that they have the valid role claim before authorizing the request. That’s all fine, but then the same Authorization policy is employed on the Identity Provider side on the controller where these API calls are but it will try to return the Login page because the request from the Admin client was unauthorized.

I believe the problem is I am not passing the access token back with the request properly, so the Identity Provider API calls don’t see what the user’s role is or if they are even authenticated. I have been unable to figure out how to retrieve it and then pass it through correctly. Here is what I have at the moment:

In the Admin client app, the Index method in the HomeController.cs which is used to display users on the Admin landing page. This method uses the GetAllUsersAsync() method to get all the users via the request made to the Identity Provider API call.

[HttpGet("~/")]
public async Task<IActionResult> Index()
{
    List<UserInfoModel> userModel = new();
    var users = await _adminClient.GetAllUsersAsync();

    foreach ( var user in users )
    {
        UserInfoModel userInfo = new();

        userInfo.Id = user.Id;
        userInfo.Role = user.Role;
        userInfo.UserName = user.UserName;
        userInfo.Email = user.Email;

        userModel.Add(userInfo);
    }

    return View(userModel);
}

AdminClient.cs is registered as a Singleton service and takes a few parameters mainly for the client ID and secret.

AdminClient.cs:

private readonly HttpClient client = new();
private readonly string clientId;
private readonly string clientSecret;
private readonly ILogger logger;
private readonly object accessTokenLock = new object();
private DateTime accessTokenExpiry = DateTime.MinValue;
private readonly IHttpContextAccessor _httpContextAccessor;

public AdminClient(string baseAddress, string clientId, string clientSecret, ILogger<AdminClient> logger, IHttpContextAccessor httpContextAccessor)
{
    client.BaseAddress = new Uri(baseAddress);
    this.clientId = clientId;
    this.clientSecret = clientSecret;
    this.logger = logger;
    _httpContextAccessor = httpContextAccessor;
}

Program.cs:

builder.Services.AddSingleton<IAdminClient>(serviceProvider => new AdminClient(
    clientDetails.GetSection("IssuerUrl").Value?.ToString(),
    clientDetails.GetSection("ClientId").Value?.ToString(),
    clientDetails.GetSection("ClientSecret").Value?.ToString(),
    serviceProvider.GetRequiredService<ILogger<AdminClient>>(),
    new HttpContextAccessor()));

GetAllUsersAsync() is from the AdminClient.cs. This method attempts to get the user’s Authorization Code from the Http Context and then uses the Authorization Code to get an access token using the GetAccessTokenAsync() method (shown further in this post). It then creates a Http Request to the user administration controller in the Identity Provider and includes the access token in the Authorization Header. It sends this request and then the rest of the method is deserialzing the JSON upon a successful request.

public async Task<List<UserDTO>> GetAllUsersAsync()
{
    try
    {
        // Get authorisation code
        string? authCode = _httpContextAccessor?.HttpContext?.Request.Query["code"];
        string? accessToken = await GetAccessTokenAsync(authCode);

        HttpRequestMessage request = new()
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri($"useradministration/getallusersdetailsandclaims", UriKind.Relative),
            Headers =
            {
                Authorization = new AuthenticationHeaderValue("Bearer", accessToken)
            }
        };

        var response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();

        var content = await response.Content.ReadAsStringAsync();
        var userData = System.Text.Json.JsonSerializer.Deserialize<List<UserDTO>>(content,
            new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });

        return userData;
    }
    catch (Exception ex)
    {
        throw new InvalidOperationException(ex.Message);
    }
}

The GetAccessTokenAsync() method is also in the AdminClient.cs class. It creates a request to the Identity Provider’s token endpoint and in the content of the request contains the grant type (using the Authorisation Code Flow), the authorisation code passed through the parameter and the client’s ID and secret. It then sends the request and, if successful, deserializes the JSON response to extract the access token and returns it ready to be used in the request in GetAllUsersAsync()

private async Task<string> GetAccessTokenAsync(string authCode)
{
    HttpRequestMessage request = new()
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri($"{client.BaseAddress}connect/token"),
        Content = new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "authorization_code"),
            new KeyValuePair<string, string>("code", authCode),
            new KeyValuePair<string, string>("client_id", clientId), 
            new KeyValuePair<string, string>("client_secret", clientSecret)
        })
    };
    try
    {
        HttpResponseMessage? response = await client.SendAsync(request);
        response.EnsureSuccessStatusCode();

        string responseContent = await response.Content.ReadAsStringAsync();
        JObject json = JObject.Parse(responseContent);
        string accessToken = json["access_token"].ToString();
        return accessToken;
    }
    catch (Exception ex) 
    {
        throw new Exception(ex.Message);
    }
}

At the moment I get a null value from the Http Context query to get the authorisation code, therefore the access token does not get returned from GetAccessTokenAsync(), resulting in a bad or unauthorized request in GetAllUsersAsync(). On top of that I am still unsure this is even the right way to do it, even if I did get the authorization code. If I could get some advice on what I am missing, or if I need to do this process in a different way, that would be great.

If anymore information or context is needed, please let me know and I will send anything you need.

Thank you in advance.

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật