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