private IEnumerable <SecurityKey> GetSigningKeys() { var httpClient = new HttpClient(); var identityServerAddress = _configurationManager.Get <string>("IdentityServerAddress"); var identityServerPath = _configurationManager.Get("IdentityServerPath", string.Empty); var discoveryEndpoint = $"{identityServerAddress}{identityServerPath}/.well-known/openid-configuration"; logger.Debug($"{nameof(NanoHttp)}.{nameof(GetSigningKeys)}", new LogItem("Event", "Retrieving identity server settings"), new LogItem("Url", discoveryEndpoint)); var openIdConfigResult = httpClient.GetStringAsync(discoveryEndpoint).Result; var openIdConfig = JsonConvert.DeserializeObject <OpenIdConfig>(openIdConfigResult); logger.Debug($"{nameof(NanoHttp)}.{nameof(GetSigningKeys)}", new LogItem("Event", "Retrieving signing keys"), new LogItem("Url", openIdConfig.JwksUri)); var jwksResult = httpClient.GetStringAsync(openIdConfig.JwksUri).Result; try { var keySet = new JsonWebKeySet(jwksResult); return(keySet.GetSigningKeys()); } catch (ArgumentException) { return(null); } }
public void Constructors( string json, JsonWebKeySet compareTo, JsonSerializerSettings settings, ExpectedException ee) { var context = new CompareContext(); try { #pragma warning disable CS0618 // Type or member is obsolete var jsonWebKeys = new JsonWebKeySet(json, settings); #pragma warning restore CS0618 // Type or member is obsolete var keys = jsonWebKeys.GetSigningKeys(); ee.ProcessNoException(context); if (compareTo != null) { IdentityComparer.AreEqual(jsonWebKeys, compareTo, context); } } catch (Exception ex) { ee.ProcessException(ex, context.Diffs); } TestUtilities.AssertFailIfErrors(context); }
/// <summary> /// Retrieves a populated <see cref="OpenIdConnectConfiguration"/> given an address and an <see cref="IDocumentRetriever"/>. /// </summary> /// <param name="address">address of the jwks uri.</param> /// <param name="retriever">the <see cref="IDocumentRetriever"/> to use to read the jwks</param> /// <param name="cancel"><see cref="CancellationToken"/>.</param> /// <returns>A populated <see cref="OpenIdConnectConfiguration"/> instance.</returns> public static async Task <OpenIdConnectConfiguration> GetAsync(string address, IDocumentRetriever retriever, CancellationToken cancel) { if (string.IsNullOrWhiteSpace(address)) { throw LogHelper.LogArgumentNullException(nameof(address)); } if (retriever == null) { throw LogHelper.LogArgumentNullException(nameof(retriever)); } var doc = await retriever.GetDocumentAsync(address, cancel).ConfigureAwait(false); LogHelper.LogVerbose("IDX21811: Deserializing the string: '{0}' obtained from metadata endpoint into openIdConnectConfiguration object.", doc); var jwks = new JsonWebKeySet(doc); var openIdConnectConfiguration = new OpenIdConnectConfiguration() { JsonWebKeySet = jwks, JwksUri = address, }; foreach (var securityKey in jwks.GetSigningKeys()) { openIdConnectConfiguration.SigningKeys.Add(securityKey); } return(openIdConnectConfiguration); }
/* * Utilizando o 'Microsoft.Owin.Security.Jwt' * faz a validação do Bearer Token. */ public void Configuration(IAppBuilder app) { using (var http = new HttpClient()) { var keysResponse = http.GetAsync("http://localhost:8080/auth/realms/transurc/protocol/openid-connect/certs").Result; var rawKeys = keysResponse.Content.ReadAsStringAsync().Result; JsonWebKeySet jsonWebKeySet = JsonConvert.DeserializeObject <JsonWebKeySet>(rawKeys); app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ExternalBearer, AuthenticationMode = AuthenticationMode.Active, Realm = "transurc", TokenValidationParameters = new TokenValidationParameters() { AuthenticationType = "Bearer", ValidateIssuer = true, ValidateIssuerSigningKey = true, ValidAudiences = new string[] { "keycloak-sample-webapp-backend", "keycloak-sample-webapp-frontend" }, ValidIssuer = "http://localhost:8080/auth/realms/transurc", ValidateLifetime = true, ValidateAudience = true, IssuerSigningKeys = jsonWebKeySet.GetSigningKeys(), } }); } }
public string ValidateToken() { // get jwks url var jwksUrl = GetJwksUrl(); // get json web keys from its urls var jsonWebKeys = new WebClient().DownloadString(jwksUrl); // creates a json web keys set var jwks = new JsonWebKeySet(jsonWebKeys); var signedKeys = jwks.GetSigningKeys(); // validate token SecurityToken validatedToken; var validationParameters = new TokenValidationParameters { ValidAudience = _decodedToken.Audiences.First(), IssuerSigningKeys = signedKeys, ValidIssuer = _decodedToken.Issuer }; _tokenHandler.ValidateToken(_token, validationParameters, out validatedToken); Console.WriteLine(validatedToken); return("ok"); }
private void Constructors( string testId, string json, JsonWebKeySet compareTo, ExpectedException ee) { var context = new CompareContext($"{this}.{testId}"); context.PropertiesToIgnoreWhenComparing.Add(typeof(JsonWebKeySet), new List <string>() { "SkipUnresolvedJsonWebKeys" }); try { var jsonWebKeys = new JsonWebKeySet(json); var keys = jsonWebKeys.GetSigningKeys(); ee.ProcessNoException(context); if (compareTo != null) { IdentityComparer.AreEqual(jsonWebKeys, compareTo, context); } } catch (Exception ex) { ee.ProcessException(ex, context.Diffs); } TestUtilities.AssertFailIfErrors(context); }
private static TokenValidationResult ValidateSignedToken(string serviceJwt, JsonWebKeySet jwksTrustedSigningKeys, bool includeDetails) { // Now validate the JWT using the signing keys we just discovered TokenValidationParameters tokenValidationParams = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, IssuerSigningKeys = jwksTrustedSigningKeys.GetSigningKeys() }; var jwtHandler = new JsonWebTokenHandler(); var validatedToken = jwtHandler.ValidateToken(serviceJwt, tokenValidationParams); if (!validatedToken.IsValid) { throw new ArgumentException("JWT is not valid (signature verification failed)"); } Logger.WriteLine($"JWT signature validation : True"); if (includeDetails) { X509SecurityKey signingKey = (X509SecurityKey)validatedToken.SecurityToken.SigningKey; if (signingKey.PublicKey is RSA publicKey) { var modulus = publicKey.ExportParameters(false).Modulus; var exponent = publicKey.ExportParameters(false).Exponent; Logger.WriteLine(37, 80, " RSA signing key modulus : ", BitConverter.ToString(modulus).Replace("-", "")); Logger.WriteLine(37, 80, " RSA signing key exponent : ", BitConverter.ToString(exponent).Replace("-", "")); } else { Logger.WriteLine($"Unexpected signing key type. Signing Key Type: {signingKey.PublicKey.GetType()}"); } } return(validatedToken); }
public async Task Jwks_with_ecdsa_should_have_parsable_key(string crv, string alg) { var key = CryptoHelper.CreateECDsaSecurityKey(crv); IdentityServerPipeline pipeline = new IdentityServerPipeline(); pipeline.OnPostConfigureServices += services => { services.AddIdentityServerBuilder() .AddSigningCredential(key, alg); }; pipeline.Initialize("/ROOT"); var result = await pipeline.BackChannelClient.GetAsync("https://server/root/.well-known/openid-configuration/jwks"); var json = await result.Content.ReadAsStringAsync(); var jwks = new JsonWebKeySet(json); var parsedKeys = jwks.GetSigningKeys(); var matchingKey = parsedKeys.FirstOrDefault(x => x.KeyId == key.KeyId); matchingKey.Should().NotBeNull(); matchingKey.Should().BeOfType <ECDsaSecurityKey>(); }
/// <summary> /// GetIssuerSigningKeys /// </summary> /// <returns></returns> /// <exception cref="HB.Component.Authorization.AuthorizationException"></exception> public IEnumerable <SecurityKey> GetIssuerSigningKeys() { if (_jsonWebKeySet == null) { throw new AuthorizationException(Resources.JsonWebKeySetIsNullErrorMessage); } return(_jsonWebKeySet.GetSigningKeys()); }
/// <summary> /// </summary> /// <param name="builder"></param> /// <param name="configuration"></param> /// <returns></returns> public static AuthenticationBuilder AddJwtBearerConfiguration(this AuthenticationBuilder builder, IConfiguration configuration) { var serviceProvider = builder.Services.BuildServiceProvider(); if (_logger is null) { _logger = serviceProvider.GetRequiredService <ILogger <AuthenticationBuilder> >(); } TokenValidationParameters tokenValidationParameters = new TokenValidationParameters(); configuration.GetSection("Authentication").GetSection("JwtBearer") .GetSection("TokenValidationParameters").Bind(tokenValidationParameters); JsonWebKeySet tokenSigningKeys = new JsonWebKeySet(); configuration.GetSection("Authentication").GetSection("JwtBearer") .GetSection("TokenValidationParameters").Bind(tokenSigningKeys); IList <SecurityKey> _tokenIssuerSigningSecruityKeys = tokenSigningKeys.GetSigningKeys(); #if DEBUG var _developerSigningKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes( "the secret that needs to be at least 16 characeters long for HmacSha256" ) ); _tokenIssuerSigningSecruityKeys.Add(_developerSigningKey); #endif tokenValidationParameters.IssuerSigningKeys = _tokenIssuerSigningSecruityKeys; builder.AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.TokenValidationParameters = tokenValidationParameters; options.Events = new JwtBearerEvents { OnMessageReceived = _onMessageReceived, OnChallenge = _onChallenge, OnTokenValidated = _onTokenValidated, OnAuthenticationFailed = _onAuthenticationFailed }; options.SaveToken = true; }); return(builder); }
/// <summary> /// Gets the instance of <see cref="OpenIdConnectConfiguration"/> with the given certificate. /// </summary> /// <param name="cert">The certificate with the signing public keys.</param> /// <returns>The instance of <see cref="OpenIdConnectConfiguration"/>.</returns> private static OpenIdConnectConfiguration GetTestO365OpenIdConnectConfiguration(X509Certificate2 cert) { OpenIdConnectConfiguration config = new OpenIdConnectConfiguration(GetTestOpenIDConfiguration().ToString()); JObject jwk = CertificateHelper.ToJsonWebKey(cert); JsonWebKeySet jwks = new JsonWebKeySet(jwk.ToString()); foreach (SecurityKey key in jwks.GetSigningKeys()) { config.SigningKeys.Add(key); } return(config); }
/// <summary> /// Return all signing keys from jwks.json file content /// </summary> /// <param name="jsonString">full json string from jwks.json</param> /// <returns></returns> public static IList <SecurityKey> GetSigningKeysFromJson(string jsonString) { IList <SecurityKey> keys = new List <SecurityKey>(); JsonWebKeySet keyset = JsonConvert.DeserializeObject <JsonWebKeySet>(jsonString); foreach (SecurityKey key in keyset.GetSigningKeys()) { keys.Add(key); } return(keys); }
public void ValidateTokenWithKey() { string keys = "{\"keys\":[{\"kty\":\"RSA\",\"use\":\"sig\",\"kid\":\"WHROgiuc_n3Zb3i_5q7d7c5cb4s\",\"x5t\":\"WHROgiuc_n3Zb3i_5q7d7c5cb4s\",\"e\":\"AQAB\",\"n\":\"nkSx7FnImfW47T4XBKyP9ndwkqyL3JU3J4Zeg3F-pO7OVMaIx7LIEQMD12Lldy1kX3tHd31J5M4FhbKj9eJg4iiVKciAOBZ39JvGGFlzkqrdabifcFE9sO1nTeY7rYt5vzFuFpDNs02I9Bk1Uv6avWzkWKdjUWHx3sQmPuVWmE4pKvG254dF_5XY-6k3uqtwDPYPB7UTMgQE1GJennGbK97YSsmEcoOBWA8aDgUgWhRmwfbSkvLYfm5dubxhORl5foOVzqSaOaF7WtzAa8X9V2mYwNLFYJC4r6oPZS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OIqHHM_ZtU78M7Lw3yjdKdqRjGDWtVU52CyQ_br95HphHukk4vd-7bAocNpFqP07d0bZ5j-Efca-0bzQtVzmzal_cVWwvQHZHxHbIjAUW_2yHQlB2ROdOfDYoICNKcIdGP1Kf5ysFONsCaygHJo-xHCLsMYPmPA"; JsonWebKeySet keyset = new JsonWebKeySet(keys); JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); handler.ValidateToken(token, new TokenValidationParameters { IssuerSigningKeys = keyset.GetSigningKeys(), ValidateAudience = false }, out SecurityToken blah); }
private static TokenValidationResult ValidateSignedToken(string policyJwt, JsonWebKeySet jwksTrustedSigningKeys) { // Now validate the JWT using the signing keys we just discovered TokenValidationParameters tokenValidationParams = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, IssuerSigningKeys = jwksTrustedSigningKeys.GetSigningKeys() }; var jwtHandler = new JsonWebTokenHandler(); var validatedToken = jwtHandler.ValidateToken(policyJwt, tokenValidationParams); if (!validatedToken.IsValid) { throw new ArgumentException("Policy JWT is not valid (signature verification failed)"); } return(validatedToken); }
public void RetrieveMetadataSigningKeys() { using (MockContext ctx = MockContext.Start(this.GetType())) { var attestationClient = GetAttestationClient(); var response = attestationClient.SigningCertificates.Get(tenantBaseUrl); var json = JsonConvert.DeserializeObject(response.ToString()) as JObject; Assert.NotNull(json); var jwks = new JsonWebKeySet(response.ToString()); var signingKeys = jwks.GetSigningKeys(); foreach (var key in signingKeys) { Assert.True(key is X509SecurityKey); var x509Key = key as X509SecurityKey; } } }
public static async Task <IList <SecurityKey> > GetApplePublicKeys() { var requestUrl = $"https://appleid.apple.com/auth/keys"; using (HttpClient client = new HttpClient()) using (HttpResponseMessage res = await client.GetAsync(requestUrl)) using (HttpContent content = res.Content) { string data = await content.ReadAsStringAsync(); if (data != null) { JsonWebKeySet jsonWebKeySet = new JsonWebKeySet(data); IList <SecurityKey> keys = jsonWebKeySet.GetSigningKeys(); return(keys); } return(null); } }
public void Constructors(string json, JsonWebKeySet compareTo, ExpectedException ee) { var context = new CompareContext(); try { var jsonWebKeys = new JsonWebKeySet(json); var keys = jsonWebKeys.GetSigningKeys(); ee.ProcessNoException(context); if (compareTo != null) { IdentityComparer.AreEqual(jsonWebKeys, compareTo, context); } } catch (Exception ex) { ee.ProcessException(ex, context.Diffs); } TestUtilities.AssertFailIfErrors(context); }
private static SecurityKey GetSecurityKey(string jwksJson, string token) { string[] tokenParts = token.Split('.'); JwtHeader header = JwtHeader.Base64UrlDeserialize(tokenParts[0]); JsonWebKeySet jwks = new JsonWebKeySet(jwksJson); IList <SecurityKey> keyList = jwks.GetSigningKeys(); SecurityKey signedKey = null; for (int index = 0; index < keyList.Count; index++) { SecurityKey key = keyList[index]; if (StringComparer.Ordinal.Equals(key.KeyId, header.Kid)) { signedKey = key; break; } } return(signedKey); }
public AuthorizationService(IOptions <AuthorizationServerOptions> options, ITransaction transaction, IDistributedLockManager lockManager, SignInTokenBiz signInTokenBiz, IIdentityService identityService /*, ILogger<AuthorizationService> logger*/) { _options = options.Value; _transaction = transaction; _lockManager = lockManager; _identityService = identityService; _signInTokenBiz = signInTokenBiz; #region Initialize Jwt Signing Credentials X509Certificate2?cert = CertificateUtil.GetBySubject(_options.SigningCertificateSubject); if (cert == null) { throw new AuthorizationException(ErrorCode.JwtSigningCertNotFound, $"Subject:{_options.SigningCertificateSubject}"); } _jsonWebKeySet = CredentialHelper.CreateJsonWebKeySet(cert); _issuerSigningKeys = _jsonWebKeySet.GetSigningKeys(); #endregion #region Initialize Jwt Content Encrypt/Decrypt Credentials X509Certificate2?encryptionCert = CertificateUtil.GetBySubject(_options.EncryptingCertificateSubject); if (encryptionCert == null) { throw new FrameworkException(ErrorCode.JwtEncryptionCertNotFound, $"Subject:{_options.EncryptingCertificateSubject}"); } _encryptingCredentials = CredentialHelper.GetEncryptingCredentials(encryptionCert); _decryptionSecurityKey = CredentialHelper.GetSecurityKey(encryptionCert); #endregion }