1

I have a WPF application, it will authenticate with Azure AD and return a Token. While calling the methods Web API, we are passing this token to server machine. In server we need to validate the token is valid or not. Can you please help me for the validation code in server machine

                string aadInstance = service.SelectSingleNode("AADInstance").InnerText;
                string tenant = service.SelectSingleNode("Tenant").InnerText;
                string clientId = service.SelectSingleNode("ClientId").InnerText;
                string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
                authContext = new AuthenticationContext(authority, new FileCache());
                Uri redirectUri = new Uri(service.SelectSingleNode("RedirectUri").InnerText);
                string resourceId = service.SelectSingleNode("ResourceId").InnerText;
                AuthenticationResult result = null;
             try
            {
                result = await authContext.AcquireTokenSilentAsync(resourceId, clientId);
            }
            catch (AdalException ex)
            {
                if (ex.ErrorCode == AdalError.UserInteractionRequired || ex.ErrorCode == AdalError.FailedToAcquireTokenSilently)
                {
                    result = await authContext.AcquireTokenAsync(resourceId, clientId, redirectUri, new PlatformParameters(PromptBehavior.Always));
                }
            }
            tocken = result.AccessToken;
Sijoy Rajan
  • 39
  • 1
  • 5

2 Answers2

1

Its seems you are trying to validate your token from your back end code.

Once you get your token your can use System.IdentityModel.Tokens.Jwt nuget package to validate your token. To do that

Go nuget package manager and browse for System.IdentityModel.Tokens.Jwt add this reference to your project. See the screen shot below:

enter image description here

Add Following Reference:

using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;

Once you set the package set the following code:

Token Validation Method:

private  bool ValidateToken(string yourToken)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var validationParameters = GetValidationParameters();

            SecurityToken validatedToken;
            IPrincipal principal = tokenHandler.ValidateToken(yourToken, validationParameters, out validatedToken);
            return true;
        }

Your Token Validation Param:

static string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

private static TokenValidationParameters GetValidationParameters()
        {
            return new TokenValidationParameters()
            {
                ValidateLifetime = false, // Because there is no expiration in the generated token
                ValidateAudience = false, // Because there is no audiance in the generated token
                ValidateIssuer = false,   // Because there is no issuer in the generated token
                ValidIssuer = "Sample",
                ValidAudience = "Sample",
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)) // The same key as the one that generate the token
            };
        }

Note: hook up all the reference and test. for more details you could refer here. If you sill have any query feel free to share. Thanks and happy coding!

Md Farid Uddin Kiron
  • 16,817
  • 3
  • 17
  • 43
  • From where we get Key? I am getting error IDX10501: Signature validation failed. Unable to match keys: – Sijoy Rajan Jun 03 '19 at 11:10
  • Key is your token that you get from token response – Md Farid Uddin Kiron Jun 03 '19 at 11:37
  • My requirement is Azure AD return a token in client machine, we are passing this token to server side. In server I want to validate the token in Azure AD. – Sijoy Rajan Jun 03 '19 at 11:43
  • Yeah It will do same – Md Farid Uddin Kiron Jun 03 '19 at 11:45
  • IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)) // The same key as the one that generate the token. In my case we are not using any key for generate token – Sijoy Rajan Jun 03 '19 at 11:46
  • I have a client application and it authenticating to our Azure Account portal, at that time Azure returning a Token to client application. This token is passing to Web API. In this Web API Server machine I need to validate the key that send from client in Azure portal. Can you please let me know how to validate token in Azure portal. – Sijoy Rajan Jun 03 '19 at 15:43
0
        {
            string stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration";
            ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
            OpenIdConnectConfiguration config = configManager.GetConfigurationAsync().Result;
            TokenValidationParameters validationParameters = new TokenValidationParameters
            {
                ValidateAudience = false,
                ValidateIssuer = false,
                IssuerSigningKeys = config.SigningKeys, //.net core calls it "IssuerSigningKeys" and "SigningKeys"
                ValidateLifetime = true
            };
            JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();
            SecurityToken jwt;
            var result = tokendHandler.ValidateToken(token, validationParameters, out jwt);
            return jwt as JwtSecurityToken;
        }
Sijoy Rajan
  • 39
  • 1
  • 5