public RsaSecurityKey GetRsaSecurityKey(JwtSecurityToken jwtToken, string jwksUrl)
        {
            var tokenSigningKeysJson = _httpClient.GetStringAsync(jwksUrl).Result;
            var jsonWebKeySet        = new JsonWebKeySet(tokenSigningKeysJson);
            var keyToCheck           = jsonWebKeySet.Keys.First(x => x.Kid == jwtToken.Header.Kid);

            if (keyToCheck == null)
            {
                throw new AuthenticationException($@"Could not find the token signing key with id {jwtToken.Header.Kid} from JWKs");
            }

            var rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(
                new RSAParameters
            {
                Modulus  = ArrayHelper.TrimStart(Base64UrlEncoder.DecodeBytes(keyToCheck.N)),
                Exponent = Base64UrlEncoder.DecodeBytes(keyToCheck.E)
            });
            var signingKey = new RsaSecurityKey(rsa)
            {
                KeyId = keyToCheck.Kid
            };

            return(signingKey);
        }
Exemple #2
0
        private RSAParameters GetRSAParameters()
        {
            /*
             *  Secret Manager is used for this project. But I did not need to call
             *  AddUserSecrets<Startup>() above.
             *
             *  In ASP.NET Core 2.0 or later, the user secrets configuration source is automatically
             *  added in development mode when the project calls CreateDefaultBuilder to initialize
             *  a new instance of the host with preconfigured defaults. CreateDefaultBuilder calls
             *  AddUserSecrets when the EnvironmentName is Development.
             *
             *  In production the secrets will not be deployed so the app settings would have to be
             *  set at deploy time.
             */
            var keyParameters = Configuration.GetSection("KeyParameters").Get <KeyParameters>();

            return(new RSAParameters
            {
                D = Base64UrlEncoder.DecodeBytes(keyParameters.D),
                DP = Base64UrlEncoder.DecodeBytes(keyParameters.DP),
                DQ = Base64UrlEncoder.DecodeBytes(keyParameters.DQ),
                Exponent = Base64UrlEncoder.DecodeBytes(keyParameters.Exponent),
                InverseQ = Base64UrlEncoder.DecodeBytes(keyParameters.InverseQ),
                Modulus = Base64UrlEncoder.DecodeBytes(keyParameters.Modulus),
                P = Base64UrlEncoder.DecodeBytes(keyParameters.P),
                Q = Base64UrlEncoder.DecodeBytes(keyParameters.Q)
            });
        }
Exemple #3
0
        public static string Desencripta(string Cadena)
        {
            if (!String.IsNullOrEmpty(Cadena))
            {
                string textoLimpio = String.Empty;
                try
                {
                    byte[]          inputBytes  = Base64UrlEncoder.DecodeBytes(Cadena);
                    byte[]          resultBytes = new byte[inputBytes.Length];
                    RijndaelManaged cripto      = new RijndaelManaged();

                    using (MemoryStream ms = new MemoryStream(inputBytes))
                    {
                        using (CryptoStream objCryptoStream = new CryptoStream(ms, cripto.CreateDecryptor(Clave, IV), CryptoStreamMode.Read))
                        {
                            using (StreamReader sr = new StreamReader(objCryptoStream, true))
                            {
                                textoLimpio = sr.ReadToEnd();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    var x = ex;
                }
                return(textoLimpio);
            }
            return("");
        }
Exemple #4
0
        static IssuerSigningKeyResolver()
        {
            foreach (var pair in plainCertificates)
            {
                keyStore.Add(
                    pair.Key,
                    new X509SecurityKey(
                        new X509Certificate2(
                            Convert.FromBase64String(pair.Value))));
            }

            foreach (var pair in jwks)
            {
                var rsa = RSA.Create();
                rsa.ImportParameters(new RSAParameters
                {
                    Exponent = Base64UrlEncoder.DecodeBytes(pair.Value.E),
                    Modulus  = Base64UrlEncoder.DecodeBytes(pair.Value.N),
                });

                keyStore.Add(
                    pair.Key,
                    new RsaSecurityKey(rsa));
            }
        }
Exemple #5
0
        public static IdToken Parse(string idToken)
        {
            IdToken idTokenBody = null;

            if (!string.IsNullOrWhiteSpace(idToken))
            {
                string[] idTokenSegments = idToken.Split(new[] { '.' });

                // If Id token format is invalid, we silently ignore the id token
                if (idTokenSegments.Length == 3)
                {
                    try
                    {
                        byte[] idTokenBytes = Base64UrlEncoder.DecodeBytes(idTokenSegments[1]);
                        using (var stream = new MemoryStream(idTokenBytes))
                        {
                            var serializer = new DataContractJsonSerializer(typeof(IdToken));
                            idTokenBody = (IdToken)serializer.ReadObject(stream);
                        }
                    }
                    catch (SerializationException)
                    {
                        // We silently ignore the id token if exception occurs.
                    }
                    catch (ArgumentException)
                    {
                        // Again, we silently ignore the id token if exception occurs.
                    }
                }
            }

            return(idTokenBody);
        }
        public static IServiceCollection AddTokenAuthentication(this IServiceCollection services, IConfiguration config)
        {
            var secret    = config.GetSection("JwtConfig").GetSection("secret").Value;
            var keySecret = Base64UrlEncoder.DecodeBytes(secret);

            var key = Encoding.ASCII.GetBytes(keySecret.ToString());

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    RequireExpirationTime    = false,
                    ValidateLifetime         = true,
                    ValidateAudience         = false,
                };
            });

            return(services);
        }
        private string GetClaims(string token)
        {
            //urlDecode the token as it was url encoded in the response.
            var jwt = HttpContext.Server.UrlDecode(token);

            string[] parts   = jwt.Split('.');
            string   header  = parts[0];
            string   payload = parts[1];

            string  headerJson = Encoding.UTF8.GetString(Base64UrlEncoder.DecodeBytes(header));
            JObject headerData = JObject.Parse(headerJson);

            string  payloadJson = Encoding.UTF8.GetString(Base64UrlEncoder.DecodeBytes(payload));
            JObject payloadData = JObject.Parse(payloadJson);

            var organisationIds  = payloadData.GetValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").Children();
            var userEmailAddress = payloadData.GetValue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress");

            var data = new StringBuilder();

            foreach (var organisationId in organisationIds)
            {
                data.Append("OrganisationId: " + organisationId + ", ");
            }

            data.Append("User Email: " + userEmailAddress);

            return(data.ToString());
        }
        public async Task <SecurityKeyWithAlgorithm> GetSigningSecurityKey()
        {
            var secret = await _outbackDbContext.Secrets.SingleOrDefaultAsync(m => m.ActiveSigningKey == true);

            switch (secret.PublicKeyCryptographyType)
            {
            case PublicKeyCryptographyType.EC_NistP256:
                var storedParameters = JsonSerializer.Deserialize <CryptographyParameters>(secret.CryptographyData);
                var ecParameters     = new ECParameters
                {
                    Curve = ECCurve.NamedCurves.nistP256,
                    D     = Base64UrlEncoder.DecodeBytes(storedParameters.EncodedD),
                    Q     = new ECPoint
                    {
                        X = Base64UrlEncoder.DecodeBytes(storedParameters.EncodedX),
                        Y = Base64UrlEncoder.DecodeBytes(storedParameters.EncodedY)
                    }
                };

                var ecdsa = ECDsa.Create();
                ecdsa.ImportParameters(ecParameters);

                var ecdSaKey = new ECDsaSecurityKey(ecdsa)
                {
                    KeyId = storedParameters.KeyId
                };

                return(new SecurityKeyWithAlgorithm(JsonWebKeyConverter.ConvertFromECDsaSecurityKey(ecdSaKey), SecurityAlgorithms.EcdsaSha256));

            default:
                throw new Exception($"{secret.PublicKeyCryptographyType} is not supported");
            }
        }
        public void ConfigureServices(IServiceCollection services)
        {
            // uncomment, if you want to add an MVC-based UI
            //services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);

            var builder = services.AddIdentityServer()
                          .AddInMemoryIdentityResources(Config.GetIdentityResources())
                          .AddInMemoryApiResources(Config.GetApis())
                          .AddInMemoryClients(Config.GetClients())
                          .AddTestUsers(Config.GetUsers())
                          .AddSigningCredential(new RsaSecurityKey(
                                                    new RSAParameters
            {
                D        = Base64UrlEncoder.DecodeBytes("C6EGZYf9U6RI5Z0BBoSlwy_gKumVqRx-dBMuAfPM6KVbwIUuSJKT3ExeL5P0Ky1b4p-j2S3u7Afnvrrj4HgVLnC1ks6rEOc2ne5DYQq8szST9FMutyulcsNUKLOM5cVromALPz3PAqE2OCLChTiQZ5XZ0AiH-KcG-3hKMa-g1MVnGW-SSmm27XQwRtUtFQFfxDuL0E0fyA9O9ZFBV5201ledBaLdDcPBF8cHC53Gm5G6FRX3QVpoewm3yGk28Wze_YvNl8U3hvbxei2Koc_b9wMbFxvHseLQrxvFg_2byE2em8FrxJstxgN7qhMsYcAyw1qGJY-cYX-Ab_1bBCpdcQ"),
                DP       = Base64UrlEncoder.DecodeBytes("ErP3OpudePAY3uGFSoF16Sde69PnOra62jDEZGnPx_v3nPNpA5sr-tNc8bQP074yQl5kzSFRjRlstyW0TpBVMP0ocbD8RsN4EKsgJ1jvaSIEoP87OxduGkim49wFA0Qxf_NyrcYUnz6XSidY3lC_pF4JDJXg5bP_x0MUkQCTtQE"),
                DQ       = Base64UrlEncoder.DecodeBytes("YbBsthPt15Pshb8rN8omyfy9D7-m4AGcKzqPERWuX8bORNyhQ5M8JtdXcu8UmTez0j188cNMJgkiN07nYLIzNT3Wg822nhtJaoKVwZWnS2ipoFlgrBgmQiKcGU43lfB5e3qVVYUebYY0zRGBM1Fzetd6Yertl5Ae2g2CakQAcPs"),
                Exponent = Base64UrlEncoder.DecodeBytes("AQAB"),
                InverseQ = Base64UrlEncoder.DecodeBytes("lbljWyVY-DD_Zuii2ifAz0jrHTMvN-YS9l_zyYyA_Scnalw23fQf5WIcZibxJJll5H0kNTIk8SCxyPzNShKGKjgpyZHsJBKgL3iAgmnwk6k8zrb_lqa0sd1QWSB-Rqiw7AqVqvNUdnIqhm-v3R8tYrxzAqkUsGcFbQYj4M5_F_4"),
                Modulus  = Base64UrlEncoder.DecodeBytes("6-FrFkt_TByQ_L5d7or-9PVAowpswxUe3dJeYFTY0Lgq7zKI5OQ5RnSrI0T9yrfnRzE9oOdd4zmVj9txVLI-yySvinAu3yQDQou2Ga42ML_-K4Jrd5clMUPRGMbXdV5Rl9zzB0s2JoZJedua5dwoQw0GkS5Z8YAXBEzULrup06fnB5n6x5r2y1C_8Ebp5cyE4Bjs7W68rUlyIlx1lzYvakxSnhUxSsjx7u_mIdywyGfgiT3tw0FsWvki_KYurAPR1BSMXhCzzZTkMWKE8IaLkhauw5MdxojxyBVuNY-J_elq-HgJ_dZK6g7vMNvXz2_vT-SykIkzwiD9eSI9UWfsjw"),
                P        = Base64UrlEncoder.DecodeBytes("_avCCyuo7hHlqu9Ec6R47ub_Ul_zNiS-xvkkuYwW-4lNnI66A5zMm_BOQVMnaCkBua1OmOgx7e63-jHFvG5lyrhyYEmkA2CS3kMCrI-dx0fvNMLEXInPxd4np_7GUd1_XzPZEkPxBhqf09kqryHMj_uf7UtPcrJNvFY-GNrzlJk"),
                Q        = Base64UrlEncoder.DecodeBytes("7gvYRkpqM-SC883KImmy66eLiUrGE6G6_7Y8BS9oD4HhXcZ4rW6JJKuBzm7FlnsVhVGro9M-QQ_GSLaDoxOPQfHQq62ERt-y_lCzSsMeWHbqOMci_pbtvJknpMv4ifsQXKJ4Lnk_AlGr-5r5JR5rUHgPFzCk9dJt69ff3QhzG2c"),
            }
                                                    ));

            services.AddLocalApiAuthentication();
        }
Exemple #10
0
                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="ValueTask"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public ValueTask HandleAsync([NotNull] TContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    if (!context.Properties.TryGetValue(typeof(IDataProtector).FullName, out var property) ||
                        !(property is IDataProtector protector))
                    {
                        throw new InvalidOperationException(new StringBuilder()
                                                            .Append("No suitable data protector was found for the specified token type.")
                                                            .Append("This may indicate that the OpenIddict Data Protection services were not correctly registered.")
                                                            .ToString());
                    }

                    try
                    {
                        using var buffer = new MemoryStream(protector.Unprotect(Base64UrlEncoder.DecodeBytes(context.Token)));
                        using var reader = new BinaryReader(buffer);

                        var(principal, properties) = Read(reader, version: 5);
                        if (principal == null)
                        {
                            return(default);
Exemple #11
0
        public async Task <bool> ValidateAsync(string hash, string payload)
        {
            byte[] signature = null;
            try
            {
                signature = Base64UrlEncoder.DecodeBytes(hash);
            }
            catch (Exception)
            {
                return(false);
            }

            if (_keys == null)
            {
                await GetKeys();
            }

            return(_keys.Any(x =>
            {
                using var hasher = SHA256.Create();
                var hashValue = hasher.ComputeHash(Encoding.UTF8.GetBytes(payload));

                var deformatter = new RSAPKCS1SignatureDeformatter(x);
                deformatter.SetHashAlgorithm("SHA256");
                return deformatter.VerifySignature(hashValue, signature);
            }));
        }
        public async Task InvokeCryptographyEndpointAsync_EcdsaSecurityKeysAreCorrectlyExposed(
            string oid, string curve, string d, string x, string y)
        {
            // Arrange
            var parameters = new ECParameters {
                Curve = ECCurve.CreateFromOid(new Oid(oid, curve)),
                D     = Convert.FromBase64String(d),
                Q     = new ECPoint {
                    X = Convert.FromBase64String(x),
                    Y = Convert.FromBase64String(y)
                }
            };

            var algorithm = ECDsa.Create(parameters);

            var server = CreateAuthorizationServer(options => {
                options.SigningCredentials.Clear();
                options.SigningCredentials.AddKey(new ECDsaSecurityKey(algorithm));
            });

            var client = new OpenIdConnectClient(server.CreateClient());

            // Act
            var response = await client.GetAsync(CryptographyEndpoint);

            var key = response[OpenIdConnectConstants.Parameters.Keys].First;

            // Assert
            Assert.Null(key[JsonWebKeyParameterNames.D]);

            Assert.Equal(parameters.Q.X, Base64UrlEncoder.DecodeBytes((string)key[JsonWebKeyParameterNames.X]));
            Assert.Equal(parameters.Q.Y, Base64UrlEncoder.DecodeBytes((string)key[JsonWebKeyParameterNames.Y]));
        }
Exemple #13
0
        public async Task InvokeCryptographyEndpointAsync_RsaSecurityKeysAreCorrectlyExposed()
        {
            // Arrange
            var parameters = new RSAParameters {
                D        = Convert.FromBase64String("Uj6NrYBnyddhlJefYEP2nleCntAKlWyIttJC4cJnNxNN+OT2fQXhpTXRwW4R5YIS3HDqK/Fg2yoYm+OTVntAAgRFKveRx/WKwFo6UpnJc5u3lElhFa7IfosO9qXjErpX9ruAVqipekDLwQ++KmVVdgH4PK/o//nEx5zklGCdlEJURZYJPs9/7g1cx3UwvPp8jM7LgZL5OZRNyI3Jz4efrwiI2/vd8P28lAbpv/Ao4NwUDq/WKEnZ8JYSjLEKnZCfbX1ZEwf0Ic48jEKHmi1WEwpru1fMPoYfakrsY/VEfatPiDs8a5HABP/KaXcM4AZsr7HbzqAaNycV2xgdZimGcQ=="),
                DP       = Convert.FromBase64String("hi1e+0eQ/iYrfT4zpZVbx3dyfA7Ch/aujMt6nGMF+1LGaut86vDHM2JI0Gc2BKc+uPEu2bNAorhSmuSyGpfGYl0MYFQoVF/jyiGpzYPmhYpL5yLuN9jWAqNwjfstuRDLU9zTEfZnr3OSN85rZcgT7NUxlY8im1Y2TWYxGiEXw9E="),
                DQ       = Convert.FromBase64String("laVNkWIbnSuGo7nAxyUSdL2sXU3GZWwItwzTG0IK/0woFjArtCxGgNXW+V+GhxT7iHGAVJJSBvJ65TXrUYuBmoWj2CsoUs2mzK8ax4zg3CXrU61esCsGUoS2owR4FXlhYPmoVnglGu89bH72eXKixZsuF7vKW19nG703BXYEaEU="),
                Exponent = Convert.FromBase64String("AQAB"),
                InverseQ = Convert.FromBase64String("dhzLDS4F5WYHX+vH4+uL3Ei/K5lxw2A/dBHGtbS2X54gm7vARl+FrptOFFwIjjmsLuTjttAq9K1EP/XZIq8bjW6dXJ/IytnobIPSFkclEeQlMi4/2VDMG5915J0DwnKO9M+B8F3JViUyMv0pvb+ub+HHDVFkIr7zooCmY25i77Q="),
                Modulus  = Convert.FromBase64String("kXv7Pxf6mSf7mu6mPAOAoKAXl5kU7Q3h9zevC5i4Mm5bMk17XCh7ZvVxDzGA+1JmyxOX6sw3gMUl31FtIFlDhis8VnXKAPn8i1zrmebq+7QKzpE2GpoIpXjXbkPaHG/DbC67M1bux7/dE7lSUSifHRRLsbMUC2D4UahJ6miH2iPFNFyoa6CLtwosD8tIJKwmZ9r9zfqc9BrVGu24lZySjTSRttpLaTkgkBjxHmYhinKNEtj9wUfi1S1wPJUvf+roc6o+7jeBBV3EXJCsb6XCCXI7/e3umWp19odeRShXLQNQbNuuVC7yre4iidUDrWJ1jiaB06svUG+fVEi4FCMvEQ=="),
                P        = Convert.FromBase64String("xQGczmp4qD7Sez/ZqgW+O4cciTHvSqJqJUSdDd2l1Pd/szQ8avvzorrbSWOIULyv6eJb32+HuyLgy6rTSJ6THFobAnUv4ZTR7EGK26AJmP/BhD+3G+n21+4fzfbAxpHihkCYmO8aEl8fm/r4qPVXmCzFoXDZLMNIxFsdEXiFRS0="),
                Q        = Convert.FromBase64String("vQy5C++AzF+TRh6qwbKzOqt87ZHEHidIAh6ivRNewjzIgCWXpseVl7DimY1YdViOnw1VI7xY+EyiyTanq5caTqqB3KcDm2t40bJfrZuUcn/5puRIh1bKNDwIMLsuNCrjHmDlNbocqpYMOh0Pgw7ARNbqrnPjWsYGJPuMNFpax/U=")
            };

            var rsa = RSA.Create();

            rsa.ImportParameters(parameters);

            var server = CreateAuthorizationServer(options => {
                options.SigningCredentials.Clear();
                options.SigningCredentials.AddKey(new RsaSecurityKey(rsa));
            });

            var client = new OpenIdConnectClient(server.HttpClient);

            // Act
            var response = await client.GetAsync(CryptographyEndpoint);

            var key = response[OpenIdConnectConstants.Parameters.Keys].First;

            // Assert
            Assert.Equal(parameters.Exponent, Base64UrlEncoder.DecodeBytes((string)key[JsonWebKeyParameterNames.E]));
            Assert.Equal(parameters.Modulus, Base64UrlEncoder.DecodeBytes((string)key[JsonWebKeyParameterNames.N]));
        }
        public async Task <IActionResult> GetLicense(string token)
        {
            var json = await new StreamReader(Request.Body).ReadToEndAsync();

            if (string.IsNullOrEmpty(json) || string.IsNullOrEmpty(token))
            {
                return(new BadRequestObjectResult("Missing parameters"));
            }

            if (!_streamingTokenHelper.ValidateToken(token))
            {
                return(new UnauthorizedResult());
            }

            // Spec about the request body: https://www.w3.org/TR/encrypted-media/#x9.1.3-license-request-format
            var body         = JsonConvert.DeserializeAnonymousType(json, new { kids = new List <string>() });
            var kidByteArray = Base64UrlEncoder.DecodeBytes(body.kids[0]);
            var kidHex       = BitConverter.ToString(kidByteArray).Replace("-", "");
            var kidGuid      = Guid.Parse(kidHex);
            var kid          = kidGuid.ToString();
            var keyBytes     = await _keyRepository.GetKeyWithDASHGroupAsync(kid);

            var jsonWebKey = new JsonWebKey
            {
                Kty = "oct",
                K   = Base64UrlEncoder.Encode(keyBytes),
                Kid = body.kids[0]
            };

            var jwks = new JsonWebKeySet();

            jwks.Keys.Add(jsonWebKey);

            return(new OkObjectResult(jwks));
        }
Exemple #15
0
        public Task <Result <PaymentLink> > Get(string code)
        {
            const string invalidCodeError = "Invalid link code";

            return(ValidateCode()
                   .Bind(GetLink));


            Result ValidateCode()
            {
                if (code.Length != CodeLength)
                {
                    return(Result.Failure(invalidCodeError));
                }

                var binaryData = Base64UrlEncoder.DecodeBytes(code);
                var isParsed   = Guid.TryParse(BitConverter.ToString(binaryData).Replace("-", string.Empty), out _);

                return(isParsed ? Result.Success() : Result.Failure(invalidCodeError));
            }

            async Task <Result <PaymentLink> > GetLink()
            {
                var link = await _context.PaymentLinks.SingleOrDefaultAsync(p => p.Code == code);

                return(link == default
                    ? Result.Failure <PaymentLink>(invalidCodeError)
                    : Result.Success(link));
            }
        }
Exemple #16
0
        public static BuyerToken ValidateBuyerCookie(string cookie, string secret)
        {
            var sessionValues  = Base64UrlEncoder.DecodeBytes(cookie.Split('.')[0]);
            var hashFromCookie = cookie.Split('.')[1];

            if (GenerateCookieHash(sessionValues, secret) != hashFromCookie)
            {
                throw new Exception("this is not a valid buyer cookie");
            }

            var sessionValueStrings = Encoding.UTF8.GetString(sessionValues).Split('/');

            var buyerToken = new BuyerToken
            {
                Username       = sessionValueStrings[0],
                UserID         = sessionValueStrings[1],
                clientID       = sessionValueStrings[2],
                PunchoutName   = sessionValueStrings[3],
                CurrentOrderID = sessionValueStrings[4],
                BuyerID        = sessionValueStrings[5],
                dateSigned     = Convert.ToDouble(sessionValueStrings[6])
            };

            if (TimeInHours() - buyerToken.dateSigned > 8)             //or whatever time makes sense
            {
                throw new Exception("buyer cookie has expiried");
            }

            return(buyerToken);
        }
Exemple #17
0
        public UserApiModel UserApiFromString(string value)
        {
            // Ensure that the API Key Size is at least 16 bytes
            if (string.IsNullOrEmpty(value))
            {
                return(null);
            }

            var data       = Base64UrlEncoder.DecodeBytes(value);
            var apiKeySize = data.Length - 16;

            if (apiKeySize < 16)
            {
                return(null);
            }

            var idValue = new byte[16];

            Array.Copy(data, 0, idValue, 0, 16);

            var apiValue = new byte[apiKeySize];

            Array.Copy(data, 16, apiValue, 0, apiKeySize);

            return(new UserApiModel
            {
                Id = new Guid(idValue),
                ApiKey = apiValue
            });
        }
        protected virtual void TransformRequest(HttpRequest request)
        {
            using (var reader = new StreamReader(request.Body))
            {
                var body = reader.ReadToEnd();
                _logger.LogInformation(body);

                var validationParams = new TokenValidationParameters
                {
                    ValidateIssuer        = false,
                    ValidateAudience      = false,
                    RequireSignedTokens   = false,
                    RequireExpirationTime = false,
                    TokenDecryptionKey    = _jwtSettings.GetSecurityKey(),
                };


                _jwtHandler.ValidateToken(body, validationParams, out var securityToken);

                var jwtToken = (JwtSecurityToken)securityToken;

                var bytes = Base64UrlEncoder.DecodeBytes(jwtToken.InnerToken.RawPayload);

                var stream = new MemoryStream(bytes, 0, bytes.Length);

                request.Body          = stream;
                request.ContentType   = "application/json";
                request.ContentLength = bytes.Length;
            }
        }
Exemple #19
0
        private TokenValidationParameters GetTokenValidationParameters(string publicKey, IEnumerable <string> audiences, string issuer)
        {
            var rsaParameters = new RSAParameters
            {
                Modulus  = Base64UrlEncoder.DecodeBytes(publicKey),
                Exponent = Base64UrlEncoder.DecodeBytes("AQAB")
            };
            var rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(rsaParameters);

            var validationParameters = new TokenValidationParameters()
            {
                RequireExpirationTime = false,
                RequireSignedTokens   = true,

                // Validate audiences only for situations where a known set of
                //  clients is authorized to use this API.
                ValidateAudience = false,
                ValidAudiences   = audiences,

                ValidateIssuer = true,
                ValidIssuer    = issuer,

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = new RsaSecurityKey(rsa),

                // Check that the token is not expired, with some leeway
                ValidateLifetime = true,
                ClockSkew        = TimeSpan.FromSeconds(5)
            };

            return(validationParameters);
        }
Exemple #20
0
        /// <summary>
        /// Fetches the public key information from the ESEC jwks endpoint, and generates an RsaSecurityKey from it
        /// </summary>
        private static RsaSecurityKey GetPublicKey()
        {
            var esecConfig = (NameValueCollection)ConfigurationManager.GetSection("ESECConfig");
            // These two lines should be removed as soon as the ESEC site's certificates start working
            var handler = new HttpClientHandler();

            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => { return(true); };

            using (HttpClient client = new HttpClient(handler))
            {
                client.BaseAddress = new Uri(esecConfig["ESECBaseAddress"]);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                Task <HttpResponseMessage> responseTask = client.GetAsync("jwks?AuthorizationProvider=OIDC Auth Provider");
                responseTask.Wait();

                string resultJSON = responseTask.Result.Content.ReadAsStringAsync().Result;

                // This dictionary and list structure matches the structure of the JSON response from the ESEC JWKS endpoint
                var resultDictionary = (new JavaScriptSerializer()).Deserialize <Dictionary <string, List <Dictionary <string, string> > > >(resultJSON);

                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.ImportParameters(new RSAParameters()
                {
                    Modulus  = Base64UrlEncoder.DecodeBytes(resultDictionary["keys"][0]["n"]),
                    Exponent = Base64UrlEncoder.DecodeBytes(resultDictionary["keys"][0]["e"])
                });
                return(new RsaSecurityKey(rsa));
            }
        }
Exemple #21
0
        /// <summary>
        ///     Decodes and decrypts the given cipher text.
        ///     This function also checks the included timestamp; if it exceeds the internal validity period, an <see cref="CryptographicException" /> is thrown.
        /// </summary>
        /// <param name="cipher"></param>
        /// <returns></returns>
        public string Decrypt(string cipher)
        {
            // Decode
            Span <byte> encryptedData = Base64UrlEncoder.DecodeBytes(cipher).AsSpan();

            // Extract parameter sizes
            int nonceSize  = BinaryPrimitives.ReadInt32LittleEndian(encryptedData.Slice(0, 4));
            int tagSize    = BinaryPrimitives.ReadInt32LittleEndian(encryptedData.Slice(4 + nonceSize, 4));
            int cipherSize = encryptedData.Length - 4 - nonceSize - 4 - tagSize;

            // Extract parameters
            var nonce       = encryptedData.Slice(4, nonceSize);
            var tag         = encryptedData.Slice(4 + nonceSize + 4, tagSize);
            var cipherBytes = encryptedData.Slice(4 + nonceSize + 4 + tagSize, cipherSize);

            // Decrypt
            using var aesGcm = new AesGcm(_key);
            Span <byte> plainBytes = cipherSize < 1024 ? stackalloc byte[cipherSize] : new byte[cipherSize];

            aesGcm.Decrypt(nonce, cipherBytes, tag, plainBytes);

            // Extract time stamp and verify
            DateTime timestamp = DateTime.FromBinary(BitConverter.ToInt64(plainBytes.Slice(0, 8)));

            if (DateTime.UtcNow - timestamp > _timestampValidityDuration)
            {
                throw new CryptographicException("Timestamp validation failed.");
            }

            // Convert plain bytes back into string
            return(Encoding.UTF8.GetString(plainBytes.Slice(8)));
        }
                /// <summary>
                /// Processes the event.
                /// </summary>
                /// <param name="context">The context associated with the event to process.</param>
                /// <returns>
                /// A <see cref="Task"/> that can be used to monitor the asynchronous operation.
                /// </returns>
                public Task HandleAsync([NotNull] TContext context)
                {
                    if (context == null)
                    {
                        throw new ArgumentNullException(nameof(context));
                    }

                    if (!context.Properties.TryGetValue(typeof(IDataProtector).FullName, out var property) ||
                        !(property is IDataProtector protector))
                    {
                        throw new InvalidOperationException(new StringBuilder()
                                                            .Append("No suitable data protector was found for the specified token type.")
                                                            .Append("This may indicate that the OpenIddict Data Protection services were not correctly registered.")
                                                            .ToString());
                    }

                    try
                    {
                        using var buffer = new MemoryStream(protector.Unprotect(Base64UrlEncoder.DecodeBytes(context.Token)));
                        using var reader = new BinaryReader(buffer);

                        var(principal, properties) = Read(reader, version: 5);
                        if (principal == null)
                        {
                            return(Task.CompletedTask);
                        }

                        context.Principal = principal;

                        // Tokens serialized using the ASP.NET Core Data Protection stack are compound
                        // of both claims and special authentication properties. To ensure existing tokens
                        // can be reused, well-known properties are manually mapped to their claims equivalents.

                        context.Principal
                        .SetAudiences(GetArrayProperty(properties, Properties.Audiences))
                        .SetCreationDate(GetDateProperty(properties, Properties.Issued))
                        .SetExpirationDate(GetDateProperty(properties, Properties.Expires))
                        .SetPresenters(GetArrayProperty(properties, Properties.Presenters))
                        .SetScopes(GetArrayProperty(properties, Properties.Scopes))

                        .SetClaim(Claims.Private.AccessTokenLifetime, GetProperty(properties, Properties.AccessTokenLifetime))
                        .SetClaim(Claims.Private.AuthorizationCodeLifetime, GetProperty(properties, Properties.AuthorizationCodeLifetime))
                        .SetClaim(Claims.Private.CodeChallenge, GetProperty(properties, Properties.CodeChallenge))
                        .SetClaim(Claims.Private.CodeChallengeMethod, GetProperty(properties, Properties.CodeChallengeMethod))
                        .SetClaim(Claims.Private.IdentityTokenLifetime, GetProperty(properties, Properties.IdentityTokenLifetime))
                        .SetClaim(Claims.Private.OriginalRedirectUri, GetProperty(properties, Properties.OriginalRedirectUri))
                        .SetClaim(Claims.Private.RefreshTokenLifetime, GetProperty(properties, Properties.RefreshTokenLifetime));

                        context.HandleDeserialization();

                        return(Task.CompletedTask);
                    }

                    catch (Exception exception)
                    {
                        context.Logger.LogTrace(exception, "An exception occured while deserializing a token.");

                        return(Task.CompletedTask);
                    }
Exemple #23
0
        public JsonWebKey FixupKey(JsonWebKey key)
        {
#if NET452
            byte[] existing = Base64UrlEncoder.DecodeBytes(key.N);
            TrimKey(key, existing);
#endif
            return(key);
        }
Exemple #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddCors();

            services.AddControllers();

            services.AddCors(options =>
            {
                options.AddPolicy(name: MySpecificOrigin, builder =>
                {
                    builder
                    //.WithOrigins("https://epic-northcutt-0cee3d.netlify.app", "https://www.hetfeld.name", "http://localhost")
                    //.WithOrigins("https://epic-northcutt-0cee3d.netlify.app", "http://localhost:3000")
                    .AllowAnyOrigin()
                    //.SetIsOriginAllowed(origin => true)
                    //.WithHeaders("Content-Type", "application/json")
                    //.WithMethods("PUT", "DELETE", "GET", "POST", "OPTIONS")
                    //.AllowCredentials()
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    ;
                });
            });


            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "ticketsystem_backend", Version = "v1"
                });
            });

            services.AddDbContext <TicketSystemDbContext>(options =>
                                                          options.UseSqlServer(Configuration.GetConnectionString("TicketContext")));
            services.AddTransient <DbSeedData>();

            services.AddAuthentication(opt =>
            {
                opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                opt.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,

                    //ValidIssuer = "https://epic-northcutt-0cee3d.netlify.app",
                    ValidIssuer   = "*",
                    ValidAudience = "*",
                    //ValidAudience = "https://epic-northcutt-0cee3d.netlify.app",
                    IssuerSigningKey = new SymmetricSecurityKey(Base64UrlEncoder.DecodeBytes("MBcCT4UEs67vh3shK683Lxhn33t2LTtH"))
                };
            });
        }
 private byte[] ParseKey(string key, string keyType)
 {
     return(keyType switch
     {
         "base64" => Convert.FromBase64String(key),
         "utf8" => Encoding.UTF8.GetBytes(key),
         "base64url" => Base64UrlEncoder.DecodeBytes(key),
         _ => throw new NotSupportedException("Invalid key type")
     });
        /// <summary>
        /// Decodes the string into the header, payload and signature
        /// </summary>
        /// <param name="jwtEncodedString">Base64Url encoded string.</param>
        internal void Decode(string jwtEncodedString)
        {
            IdentityModelEventSource.Logger.WriteInformation(LogMessages.IDX10716, jwtEncodedString);
            string[] tokenParts = jwtEncodedString.Split(new char[] { '.' }, 4);
            if (tokenParts.Length != 3)
            {
                throw LogHelper.LogException <ArgumentException>(LogMessages.IDX10709, "jwtEncodedString", jwtEncodedString);
            }

            try
            {
                IdentityModelEventSource.Logger.WriteVerbose(LogMessages.IDX10717, tokenParts[0]);
                Header = JwtHeader.Base64UrlDeserialize(tokenParts[0]);

                // if present, "typ" should be set to "JWT" or "http://openid.net/specs/jwt/1.0"
                string type = Header.Typ;
                if (type != null)
                {
                    if (!(StringComparer.Ordinal.Equals(type, JwtConstants.HeaderType) || StringComparer.Ordinal.Equals(type, JwtConstants.HeaderTypeAlt)))
                    {
                        throw LogHelper.LogException <SecurityTokenException>(LogMessages.IDX10702, JwtConstants.HeaderType, JwtConstants.HeaderTypeAlt, type);
                    }
                }
            }
            catch (Exception ex)
            {
                throw LogHelper.LogException <ArgumentException>(ex, LogMessages.IDX10703, "header", tokenParts[0], jwtEncodedString);
            }

            try
            {
                IdentityModelEventSource.Logger.WriteVerbose(LogMessages.IDX10718, tokenParts[1]);
                Payload = JwtPayload.Base64UrlDeserialize(tokenParts[1]);
            }
            catch (Exception ex)
            {
                throw LogHelper.LogException <ArgumentException>(ex, LogMessages.IDX10703, "payload", tokenParts[1], jwtEncodedString);
            }

            if (!string.IsNullOrEmpty(tokenParts[2]))
            {
                try
                {
                    Base64UrlEncoder.DecodeBytes(tokenParts[2]);
                }
                catch (Exception ex)
                {
                    throw LogHelper.LogException <ArgumentException>(ex, LogMessages.IDX10703, "signature", tokenParts[2], jwtEncodedString);
                }
            }

            RawData      = jwtEncodedString;
            RawHeader    = tokenParts[0];
            RawPayload   = tokenParts[1];
            RawSignature = tokenParts[2];
        }
Exemple #27
0
        public string CreateFakeHmacToken(List <Claim> claims,
                                          string issuer,
                                          string audience,
                                          JsonWebKey publicRsaKey)
        {
            var key           = Base64UrlEncoder.DecodeBytes(publicRsaKey.N);
            var fakeHmacToken = CreateHmacToken(claims, issuer, audience, key, publicRsaKey.KeyId);

            return(fakeHmacToken);
        }
Exemple #28
0
 /// <summary>
 /// Constructs a new <see cref="RsaJsonWebKey"/> instance
 /// </summary>
 /// <param name="id">The key id (kid)</param>
 /// <param name="expiresAt">When the key expires</param>
 /// <param name="n">The RSA modulus</param>
 /// <param name="e">The RSA exponent</param>
 public RsaJsonWebKey(
     string id,
     DateTime?expiresAt,
     string n,
     string e
     ) : base(id, expiresAt)
 {
     m_parameters.Modulus  = Base64UrlEncoder.DecodeBytes(n);
     m_parameters.Exponent = Base64UrlEncoder.DecodeBytes(e);
 }
Exemple #29
0
        public JsonWebKey FixupKey(JsonWebKey key)
        {
            if (Platform.IsFullFramework)
            {
                byte[] existing = Base64UrlEncoder.DecodeBytes(key.N);
                TrimKey(key, existing);
            }

            return(key);
        }
Exemple #30
0
        public string Decrypt(string intput)
        {
            var encryptedBytes = Base64UrlEncoder.DecodeBytes(intput);

            var plainBytes = _privateRsaProvider.Decrypt(encryptedBytes, RSAEncryptionPadding.Pkcs1);

            var plainText = Encoding.UTF8.GetString(plainBytes);

            return(plainText);
        }