Echodaa
Echodaa

Reputation: 55

How do I retrieve the JWT token in C#?

I retrieve an id_token from AzureAD which I can see in inspect element.

I am simply trying to retrieve the token in C# so I can decrypt it but I am unable to do so.

I have tried:

var authHeader = Request.Headers["id_token"];
var authHeader = Request.Form["id_token"];

JwtSecurityToken token = new JwtSecurityToken(authHeader);

Both return null.

Upvotes: 3

Views: 835

Answers (1)

Tony Ju
Tony Ju

Reputation: 15619

You can get the id token by override OnSecurityTokenReceived method.

Add custom OnSecurityTokenReceived to the Notifications.

Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed,
                    SecurityTokenReceived= OnSecurityTokenReceived
                }

Then you can get id token like this

private Task OnSecurityTokenReceived(SecurityTokenReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            var idtoken = context.ProtocolMessage.IdToken;
            return Task.FromResult(0);
        }

Upvotes: 2

Related Questions