private static TlsFederationMetadata Validate(JwsBody body) { foreach (var signature in body.Signatures) { var key = JsonWebKey.Create(File.ReadAllText("Skolverket.jwk")); var handler = new JsonWebTokenHandler(); var jwsCompact = signature.Protected + "." + body.Payload + "." + signature.Signature; var validation = new TokenValidationParameters() { IssuerSigningKey = key, ValidateAudience = false, ValidateLifetime = false, ValidateIssuer = false }; var tokenValidation = handler.ValidateToken(jwsCompact, validation); if (tokenValidation.IsValid) { var base64 = body.Payload.PadRight(body.Payload.Length + (4 - body.Payload.Length % 4) % 4, '='); var content = Encoding.UTF8.GetString(Convert.FromBase64String(base64)); return(JsonConvert.DeserializeObject <TlsFederationMetadata>(content)); } else { return(null); } } return(null); }
public static void AddDotnetWebApiBenchAuthentication(this IServiceCollection services) { var builder = services.AddIdentityServer() .AddInMemoryApiScopes(Config.Config.Scopes) .AddInMemoryApiResources(Config.Config.Apis) .AddInMemoryClients(Config.Config.Clients); SecurityKey signingKey = null; var assembly = Assembly.GetExecutingAssembly(); using Stream stream = assembly.GetManifestResourceStream($"{nameof(DotnetWebApiBench)}.{nameof(DotnetWebApiBench.Auth)}.tempkey.jwk"); using StreamReader reader = new StreamReader(stream); string json = reader.ReadToEnd(); JsonWebKey jsonWebKey = JsonWebKey.Create(json); SigningCredentials credential = new SigningCredentials(jsonWebKey, jsonWebKey.Alg); builder.AddSigningCredential(credential); signingKey = jsonWebKey; services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = signingKey, ValidateIssuer = false, ValidateAudience = true, ValidAudiences = Config.Config.Apis.Select(x => x.Name), }; x.Events = new JwtBearerEvents() { OnTokenValidated = context => { return(Task.CompletedTask); } }; }); }
public void BouncyCastleCryptoProviderTest1() { var cryptoProviders = CryptoProviderLoader.LoadCryptoProviders(); var didCryptoProvider = new DidCryptoProvider(cryptoProviders); //Copied from did-3.json... const string Jwk = @"{ ""kty"": ""OKP"", ""crv"": ""X25519"", ""x"": ""OeXe54Y0Dnk0WNWsQ6PqKUBB2x6bos0DZ_WkdFNdt3M"" }"; var jwkObj = JsonWebKey.Create(Jwk); var algorithm = CryptographyAlgorithmConstants.EdDsa.Algorithm; Assert.True(didCryptoProvider.IsSupportedAlgorithm(algorithm, jwkObj), "Unsupported algorithm was tried."); var keyWrapper = didCryptoProvider.Create(algorithm, jwkObj); Assert.NotNull(keyWrapper); Assert.True(keyWrapper is AsymmetricKeyWrapper); Assert.True(keyWrapper is BouncyCastleEdDsaWrapper); }
/// <summary> /// Método para obtenção da chave de assinatura do token provida pela autoridade de identificação. /// </summary> /// <param name="settings">Objeto referenciado</param> /// <param name="token">Token de autenticação</param> /// <returns>Chave de segurança provida pela autoridade de identificação.</returns> private static async Task <SecurityKey> GetSigningKeyAsync(this IdentityConfigurations settings, JwtSecurityToken token) { var client = new HttpClient(); try { var discovery = await client.GetDiscoveryDocumentAsync(settings.Authority); var kid = token.Header.Kid; var key = discovery.KeySet.Keys.Where(x => x.Kid == kid).FirstOrDefault(); var json = JsonConvert.SerializeObject(key); var result = JsonWebKey.Create(json); //var keys = client.GetRequest(".well-known/openid-configuration/jwks").ExecuteAsync<IdentityKeySet>().Result; return(result); } catch (Exception ex) { throw ex; } }
public void PostConfigure(string name, MonitorApiKeyConfiguration options) { MonitorApiKeyOptions sourceOptions = _apiKeyOptions.CurrentValue; IList <ValidationResult> errors = new List <ValidationResult>(); Validator.TryValidateObject( sourceOptions, new ValidationContext(sourceOptions, null, null), errors, validateAllProperties: true); string jwkJson = null; try { jwkJson = Base64UrlEncoder.Decode(sourceOptions.PublicKey); } catch (Exception) { errors.Add( new ValidationResult( string.Format( Strings.ErrorMessage_NotBase64, nameof(MonitorApiKeyOptions.PublicKey), sourceOptions.PublicKey), new string[] { nameof(MonitorApiKeyOptions.PublicKey) })); } JsonWebKey jwk = null; if (!string.IsNullOrEmpty(jwkJson)) { try { jwk = JsonWebKey.Create(jwkJson); } // JsonWebKey will throw only throw ArgumentException or a derived class. catch (ArgumentException ex) { errors.Add( new ValidationResult( string.Format( Strings.ErrorMessage_InvalidJwk, nameof(MonitorApiKeyOptions.PublicKey), sourceOptions.PublicKey, ex.Message), new string[] { nameof(MonitorApiKeyOptions.PublicKey) })); } } if (null != jwk) { if (!JwtAlgorithmChecker.IsValidJwk(jwk)) { errors.Add( new ValidationResult( string.Format( Strings.ErrorMessage_RejectedJwk, nameof(MonitorApiKeyOptions.PublicKey)), new string[] { nameof(MonitorApiKeyOptions.PublicKey) })); } // We will let the algorithm work with private key but we should produce a warning message else if (jwk.HasPrivateKey) { _logger.NotifyPrivateKey(nameof(MonitorApiKeyOptions.PublicKey)); } } options.ValidationErrors = errors; if (errors.Any()) { options.Subject = string.Empty; options.PublicKey = null; } else { options.Subject = sourceOptions.Subject; options.PublicKey = jwk; } }
public void GetValueAsyncWorksForScope(string requiredScope, string[] authorizedRoles, List <Claim> claims, TokenStatus tokenStatus) { Mock <HttpRequest> request = new Mock <HttpRequest>(); request .SetupGet(r => r.Headers) .Returns(new HeaderDictionary { { "Authorization", "Bearer abc123" } }); request .SetupGet(r => r.HttpContext) .Returns(Mock.Of <HttpContext>()); TokenSigningKeyOptions options = new TokenSigningKeyOptions { SigningKey = JsonWebKey.Create( @"{ ""alg"": ""RS256"", ""kty"": ""RSA"", ""use"": ""sig"", ""n"": ""fasdklfjahsdfkaljsnddfnlkasudvgiuq3450897uzxcvnlksdfn---aserkfjasbvdkluy3t45r"", ""e"": ""AQAB"", ""kid"": ""NKJLGHLJKHGBVKBLKJAFUYKJHBFADF"", ""x5t"": ""NKJLGHLJKHGBVKBLKJAFUYKJHBFADF"", ""x5c"": [ ""hkjlgrhkljzvkzjhlgvzvdklhvzsilseujrgfoisyehfltw34to--=sdfghzksujfdhgi7tsertukjhask.fhcgfalsiyuegrht.jklw34batgfklyuasgdvkjsdrbg="" ] }" ), Issuer = "http://iamanissuerofauthtokens.com", Audience = "some audience", }; FunctionTokenAttribute attribute = new FunctionTokenAttribute( AuthLevel.Authorized, requiredScope, authorizedRoles ); SecurityToken mockSecurityToken = Mock.Of <SecurityToken>(); Mock <ISecurityTokenValidator> mockSecurityTokenValidator = new Mock <ISecurityTokenValidator>(); mockSecurityTokenValidator .Setup(v => v.ValidateToken( It.IsAny <string>(), It.IsAny <TokenValidationParameters>(), out mockSecurityToken ) ) .Returns( new ClaimsPrincipal( new List <ClaimsIdentity> { new ClaimsIdentity( claims, "Bearer" ) }) ); SigningKeyValueProvider provider = new SigningKeyValueProvider( request.Object, options, attribute, mockSecurityTokenValidator.Object ); ((FunctionTokenResult)(provider .GetValueAsync() .GetAwaiter() .GetResult())) .Status .Should() .Be(tokenStatus); }
public async Task GenerateKey(OutputFormat?format) { using CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TestTimeouts.OperationTimeout); CancellationToken cancellationToken = cancellationTokenSource.Token; await using MonitorGenerateKeyRunner toolRunner = new(_outputHelper); toolRunner.Format = format; await toolRunner.StartAsync(cancellationToken); await toolRunner.WaitForExitAsync(cancellationToken); string tokenStr = await toolRunner.GetBearerToken(cancellationToken); Assert.NotNull(tokenStr); string formatStr = await toolRunner.GetFormat(cancellationToken); Assert.NotNull(formatStr); Assert.Equal(toolRunner.FormatUsed.ToString(), formatStr); string subject = await toolRunner.GetSubject(cancellationToken); Assert.NotNull(subject); string publicKey = await toolRunner.GetPublicKey(cancellationToken); Assert.NotNull(publicKey); string pubKeyJson = Base64UrlEncoder.Decode(publicKey); Assert.NotNull(pubKeyJson); JsonWebKey validatingKey = JsonWebKey.Create(pubKeyJson); Assert.NotNull(validatingKey); JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); Assert.True(tokenHandler.CanReadToken(tokenStr)); TokenValidationParameters tokenValidationParams = new TokenValidationParameters() { // Signing Settings RequireSignedTokens = true, ValidAlgorithms = JwtAlgorithmChecker.GetAllowedJwsAlgorithmList(), // Issuer Settings ValidateIssuer = true, // This setting differs from actual token validation in the product because we want to make sure we set our Issuer ValidIssuer = AuthConstants.ApiKeyJwtInternalIssuer, ValidateIssuerSigningKey = true, IssuerSigningKeys = new SecurityKey[] { validatingKey }, TryAllIssuerSigningKeys = true, // Audience Settings ValidateAudience = true, ValidAudiences = new string[] { AuthConstants.ApiKeyJwtAudience }, // Other Settings ValidateActor = false, ValidateLifetime = false, }; ClaimsPrincipal claimsPrinciple = tokenHandler.ValidateToken(tokenStr, tokenValidationParams, out SecurityToken validatedToken); ITestOutputHelper validationHelper = new PrefixedOutputHelper(_outputHelper, "[JWT Validation] "); foreach (Claim c in claimsPrinciple.Claims) { validationHelper.WriteLine($"Token Claim: {c.Issuer}:{c.Type}=[{c.ValueType}]{c.Value}"); } Assert.True(claimsPrinciple.HasClaim(ClaimTypes.NameIdentifier, subject)); }
public JwtTokenService(string privateKeyPath) { _privateSecret = JsonWebKey.Create(ReadFile(privateKeyPath)); }