Пример #1
0
        public static string DecryptString(string text, X509Certificate2 cert, bool base64UrlEncoding)
        {
            var bytes          = base64UrlEncoding ? Base64UrlEncoder.FromBase64String(text) : Convert.FromBase64String(text);
            var decryptedBytes = DecryptBytes(bytes, cert);

            return(Encoding.UTF8.GetString(decryptedBytes));
        }
Пример #2
0
        public void Authorize(HttpRequestHeader header)
        {
            if (!header.Headers.TryGetValue(cookieHeader, out IList <string> cookieHeaderValue))
            {
                if (!header.Headers.TryGetValue(authorizeHeader, out cookieHeaderValue))
                {
                    return;
                }
            }

            var cookies = CookieParser.CookiesFromString(cookieHeaderValue[0]);

            if (cookies.TryGetValue(cookieName, out string authCookieDataEncoded))
            {
                var authCookieDataEncrypted = Base64UrlEncoder.FromBase64String(authCookieDataEncoded);
                var authCookieDataBytes     = SymmetricEncryptor.Decrypt(encryptionAlgorithm, encryptionKey, authCookieDataEncrypted);
                var authCookieData          = Encoding.UTF8.GetString(authCookieDataBytes);
                if (authCookieData == "I can access this")
                {
                    var claims = new Claim[] {
                        new Claim(ClaimTypes.Authentication, Boolean.TrueString),
                        new Claim(ClaimTypes.NameIdentifier, "1234", ClaimValueTypes.String),
                        new Claim(ClaimTypes.Name, "Tester", ClaimValueTypes.String),
                        new Claim(ClaimTypes.Role, "Admin", ClaimValueTypes.String)
                    };

                    var identity  = new ClaimsIdentity(claims, "Cookies");
                    var principal = new ClaimsPrincipal(identity);
                    System.Threading.Thread.CurrentPrincipal = principal;
                }
            }
        }
Пример #3
0
        public static bool Validate(string text, string signature, AsymmetricAlgorithm asymmetricAlgorithm, XmlSignatureAlgorithmType signatureAlgorithm, bool base64UrlEncoding)
        {
            if (signature == null)
            {
                return(false);
            }

            var textBytes      = Encoding.UTF8.GetBytes(text);
            var signatureBytes = base64UrlEncoding ? Base64UrlEncoder.FromBase64String(signature) : Convert.FromBase64String(signature);
            var valid          = Validate(textBytes, signatureBytes, asymmetricAlgorithm, signatureAlgorithm);

            return(valid);
        }
Пример #4
0
        public async ValueTask <IdentityModel> LoginCallback(IdentityHttpRequest request)
        {
            OpenIDJwtBinding callbackBinding;

            if (OpenIDJwtBinding.IsCodeBinding(request))
            {
                var callbackCodeBinding = OpenIDBinding.GetBindingForRequest(request, BindingDirection.Response);

                var callbackCodeDocument = new OpenIDLoginResponse(callbackCodeBinding);
                if (!String.IsNullOrWhiteSpace(callbackCodeDocument.Error))
                {
                    throw new IdentityProviderException($"{callbackCodeDocument.Error}: {callbackCodeDocument.ErrorDescription}");
                }

                //Get Token--------------------
                var requestTokenDocument = new OpenIDTokenRequest(callbackCodeDocument.AccessCode, this.secret, OpenIDGrantType.authorization_code, redirectUrl);
                var requestTokenBinding  = OpenIDBinding.GetBindingForDocument(requestTokenDocument, BindingType.Form);

                var requestTokenBody = requestTokenBinding.GetContent();
                var requestToken     = WebRequest.Create(tokenUrl);
                requestToken.Method      = "POST";
                requestToken.ContentType = "application/x-www-form-urlencoded";
                var requestTokenBodyBytes = Encoding.UTF8.GetBytes(requestTokenBody);
                requestToken.ContentLength = requestTokenBodyBytes.Length;
                using (var stream = await requestToken.GetRequestStreamAsync())
                {
#if NETSTANDARD2_0 || NET461_OR_GREATER
                    await stream.WriteAsync(requestTokenBodyBytes, 0, requestTokenBodyBytes.Length);
#else
                    await stream.WriteAsync(requestTokenBodyBytes.AsMemory());
#endif
                    await stream.FlushAsync();
                }

                WebResponse responseToken;
                try
                {
                    responseToken = await requestToken.GetResponseAsync();
                }
                catch (WebException ex)
                {
                    if (ex.Response == null)
                    {
                        throw ex;
                    }
                    var responseTokenStream = ex.Response.GetResponseStream();
                    var error = await new StreamReader(responseTokenStream).ReadToEndAsync();
                    ex.Response.Close();
                    ex.Response.Dispose();
                    throw new IdentityProviderException(error);
                }

                //access_code is a JWT
                callbackBinding = OpenIDJwtBinding.GetBindingForResponse(responseToken, BindingDirection.Response);
            }
            else
            {
                callbackBinding = OpenIDJwtBinding.GetBindingForRequest(request, BindingDirection.Response);
            }

            var callbackDocument = new OpenIDLoginResponse(callbackBinding);
            if (!String.IsNullOrWhiteSpace(callbackDocument.Error))
            {
                throw new IdentityProviderException($"{callbackDocument.Error}: {callbackDocument.ErrorDescription}");
            }

            NonceManager.Validate(serviceProvider, callbackDocument.Nonce);

            if (callbackDocument.Audience != serviceProvider)
            {
                throw new IdentityProviderException("OpenID Audience is not valid", $"Received: {serviceProvider}, Expected: {callbackDocument.Audience}");
            }

            var keys = await GetSignaturePublicKeys(this.identityProviderCertUrl);

            var key = keys.FirstOrDefault(x => x.X509Thumbprint == callbackDocument.X509Thumbprint);
            if (key == null)
            {
                key = keys.FirstOrDefault(x => x.KeyID == callbackDocument.KeyID);
            }
            if (key == null)
            {
                throw new IdentityProviderException("Identity Provider OpenID certificate not found from Json Key Url");
            }
            if (key.KeyType != "RSA")
            {
                throw new IdentityProviderException("Identity Provider OpenID only supporting RSA at the moment");
            }

            RSA rsa;
            if (key.X509Certificates == null || key.X509Certificates.Length == 0)
            {
                var rsaParams = new RSAParameters()
                {
                    Modulus  = Base64UrlEncoder.FromBase64String(key.Modulus),
                    Exponent = Base64UrlEncoder.FromBase64String(key.Exponent)
                };
                rsa = RSA.Create();
                rsa.ImportParameters(rsaParams);
            }
            else
            {
                var certString = key.X509Certificates.First();
                var certBytes  = Convert.FromBase64String(certString);
                var cert       = new X509Certificate2(certBytes);
                rsa = cert.GetRSAPublicKey();
            }

            callbackBinding.ValidateSignature(rsa, requiredSignature);
            callbackBinding.ValidateFields();

            var identity = new IdentityModel()
            {
                UserID          = callbackDocument.UserID,
                UserName        = callbackDocument.UserName ?? callbackDocument.Emails?.FirstOrDefault(),
                Name            = callbackDocument.Name,
                Roles           = callbackDocument.Roles,
                ServiceProvider = callbackDocument.Issuer,
                OtherClaims     = callbackDocument.OtherClaims,
                State           = callbackDocument.State,
                AccessToken     = callbackBinding.AccessToken,
            };

            return(identity);
        }