Last active
March 15, 2021 23:15
-
-
Save DhyanRathore/ea9264cf6951efd42962d254ca603510 to your computer and use it in GitHub Desktop.
Get user Identity and Claims from HTTP Request Headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.IdentityModel.Tokens.Jwt; | |
// DEMO: Get user Identity and Claims from the Token Headers | |
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 Name and AAD ID Token from the request headers | |
var userId = req.Headers["X-MS-CLIENT-PRINCIPAL-NAME"]; | |
var userIDToken = req.Headers["X-MS-TOKEN-AAD-ID-TOKEN"]; | |
log.LogInformation("User ID: " + userId); | |
log.LogInformation("User ID Token: " + userIDToken); | |
//Read and decode the JWT | |
var jwttoken = new JwtSecurityTokenHandler().ReadJwtToken(userIDToken) as JwtSecurityToken; | |
//Extract the claims from the JWT | |
foreach (Claim claim in jwttoken.Claims) | |
{ | |
log.LogInformation(claim.Type + " : " + claim.Value + "\n"); | |
} | |
return new OkObjectResult("Success"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment