Skip to content

Instantly share code, notes, and snippets.

@DhyanRathore
Last active March 20, 2021 10:09
Show Gist options
  • Save DhyanRathore/083d6417a46e7ffac121d6f4f9a4f209 to your computer and use it in GitHub Desktop.
Save DhyanRathore/083d6417a46e7ffac121d6f4f9a4f209 to your computer and use it in GitHub Desktop.
Get user Claims from the Request Headers
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Security.Claims;
using System.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
// DEMO: Get user Claims from the Request Headers
// Adopted from https://github.com/MaximRouiller/MaximeRouiller.Azure.AppService.EasyAuth
namespace ClaimsDemo.Function
{
public static class ClaimsDemo
{
[FunctionName("ClaimsDemo")]
public static IActionResult Run
([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
HttpRequest req, ILogger log)
{
//Extract User ID and Claims from the request headers
var principal_name = req.Headers["X-MS-CLIENT-PRINCIPAL-NAME"].FirstOrDefault();
var principal_Id = req.Headers["X-MS-CLIENT-PRINCIPAL-ID"].FirstOrDefault();
string easyAuthProvider = req.Headers["X-MS-CLIENT-PRINCIPAL-IDP"].FirstOrDefault();
string clientPrincipalEncoded = req.Headers["X-MS-CLIENT-PRINCIPAL"].FirstOrDefault();
log.LogInformation("User ID: " + principal_name);
log.LogInformation("User Principal ID: " + principal_Id);
log.LogInformation("EasyAuth Provider: " + easyAuthProvider);
log.LogInformation("Encoded Client Principal: " + clientPrincipalEncoded);
//Decode the Client Principal
byte[] decodedBytes = Convert.FromBase64String(clientPrincipalEncoded);
string clientPrincipalDecoded = System.Text.Encoding.Default.GetString(decodedBytes);
// log.LogInformation("Decoded Client Principal: " + clientPrincipalDecoded);
ClientPrincipal clientPrincipal = JsonConvert.DeserializeObject<ClientPrincipal>(clientPrincipalDecoded);
IEnumerable<Claim> claims = clientPrincipal.Claims.Select(x => new Claim(x.Type, x.Value));
log.LogInformation("Claim Type : Claim Value");
foreach (Claim claim in claims)
{
log.LogInformation(claim.Type + " : " + claim.Value + "\n");
}
return new OkObjectResult("Success");
}
}
public class ClientPrincipal
{
[JsonProperty("auth_typ")]
public string AuthenticationType { get; set; }
[JsonProperty("claims")]
public IEnumerable<UserClaim> Claims { get; set; }
[JsonProperty("name_typ")]
public string NameType { get; set; }
[JsonProperty("role_typ")]
public string RoleType { get; set; }
}
public class UserClaim
{
[JsonProperty("typ")]
public string Type { get; set; }
[JsonProperty("val")]
public string Value { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment