Request identity information
Code samples
C#
public async Task<ClaimsPrincipal> GetIdentity(string accessToken)
{
var httpClient = _httpClientFactory.CreateClient(NamedHttpClients.GeosecureHttpClient);
httpClient.DefaultRequestHeaders.SetOAuthToken(accessToken, _certificateRetriever.Get(_configuration[ResourceServerCertificateKey]));
var response = await httpClient.GetAsync($"{_oAuthConfiguration.OAuthServiceEndpointKey}{WsOauthV2Identity}");
var content = response.Content;
if (content == null)
{
Log.Warning($"Failed to authenticate using token ({accessToken}) for the identity endpoint ({_oAuthConfiguration.OAuthServiceEndpointKey}{WsOauthV2Token}). Response status code: {response.StatusCode}");
return new ClaimsPrincipal();
}
var token = await content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.OK)
{
if (JsonWebTokenHandler.TryReadToken(token, out var jsonWebToken))
{
var claimsPrincipal = jsonWebToken.ToClaimsPrincipal();
if (claimsPrincipal?.Identity != null && !string.IsNullOrEmpty(claimsPrincipal.Identity.Name) && claimsPrincipal.Identity.IsAuthenticated)
return claimsPrincipal;
return new ClaimsPrincipal();
}
Log.Warning($"Failed to authenticate using token ({accessToken}) for the identity endpoint ({_oAuthConfiguration.OAuthServiceEndpointKey}{WsOauthV2Token}). The content contained no valid jwt. Content: {token}");
}
else
Log.Warning($"Failed to authenticate using token ({accessToken}) for the identity endpoint ({_oAuthConfiguration.OAuthServiceEndpointKey}{WsOauthV2Token}). Response status code: {response.StatusCode}");
return new ClaimsPrincipal();
}
public static void SetOAuthToken(this HttpRequestHeaders headers, string token, X509Certificate2 signingCertificate)
{
if (headers == null)
{
throw new ArgumentNullException("headers", "the headers can not be null");
}
if (signingCertificate == null)
{
throw new ArgumentNullException("signingCertificate", "the signing certificate can not be null");
}
headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
headers.Add("X-Client-Cert", Convert.ToBase64String(signingCertificate.Export(X509ContentType.Cert)));
headers.Add("X-Token-Signature", CreateSignature(token, signingCertificate));
}
public static bool TryReadToken(string token, out JsonWebToken jsonWebToken)
{
jsonWebToken = null;
if (string.IsNullOrEmpty(token))
return false;
var strArray = token.Split('.');
if (strArray.Length < 2)
return false;
jsonWebToken = new JsonWebToken();
ReadHeader(strArray[0], jsonWebToken);
ReadClaimSets(strArray[1], jsonWebToken);
return true;
}