Beispiel #1
0
    /// <inheritdoc />
    public string Protect(TData data, string?purpose)
    {
        var userData = _serializer.Serialize(data);

        var protector = _protector;

        if (!string.IsNullOrEmpty(purpose))
        {
            protector = protector.CreateProtector(purpose);
        }

        var protectedData = protector.Protect(userData);

        return(Base64UrlTextEncoder.Encode(protectedData));
    }
        /// <summary>
        /// This is not a command from a SQRL client but helpful for bate of SQRL
        /// </summary>
        /// <param name="request">The HTTP request</param>
        /// <param name="response">The HTTP response to write to</param>
        /// <param name="options">The options from the middleware</param>
        public void QrCodePage()
        {
            var nut = GenerateNut(Options.EncryptionKey);

            StoreNut(nut);
            var url                  = $"sqrl://{Request.Host}{Options.CallbackPath}?nut=" + nut;
            var checkUrl             = $"{Request.Scheme}://{Request.Host}{Options.CallbackPath}?check=" + nut;
            var diagUrl              = $"{Request.Scheme}://{Request.Host}{Options.CallbackPath}?diag";
            var cancelUrl            = Base64UrlTextEncoder.Encode(Encoding.ASCII.GetBytes($"{Request.Scheme}://{Request.Host}{Options.CancelledPath}"));
            var responseMessageBytes = Encoding.ASCII.GetBytes(QrCodePageHtml(url, checkUrl, cancelUrl, diagUrl));

            Response.StatusCode    = StatusCodes.Status200OK;
            Response.ContentType   = "text/html";
            Response.ContentLength = responseMessageBytes.LongLength;
            Response.Body.WriteAsync(responseMessageBytes, 0, responseMessageBytes.Length);
        }
        public void ShorterState_GenerateCorrelationId_Test(bool expected, int len)
        {
            var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("WeixinAuthTest"));
            var properties  = new AuthenticationProperties();

            var cryptoRandom = RandomNumberGenerator.Create();
            var bytes        = new byte[len];

            cryptoRandom.GetBytes(bytes);
            var correlationId = Base64UrlTextEncoder.Encode(bytes);

            properties.Items[".xrsf"] = correlationId;
            var state = stateFormat.Protect(properties);

            Assert.Equal(expected, state.Length <= 128);
        }
        public void GenerateClientSecret()
        {
            int bytes = 32;

            byte[] data;
            using (var rngCsp = RandomNumberGenerator.Create())
            {
                data = new byte[bytes];
                rngCsp.GetNonZeroBytes(data);
            }

            var audienceSecret = Base64UrlTextEncoder.Encode(data);
            var audienceId     = Guid.NewGuid().ToString("N");

            OutputHelper.WriteLine($"audienceId: {audienceId}");
            OutputHelper.WriteLine($"audienceSecret: {audienceSecret}");
        }
Beispiel #5
0
        public void SaveTempData_CustomProviderOptions_SetsCookie_WithAppropriateCookieOptions(
            string requestPathBase, string optionsPath, string optionsDomain, string expectedCookiePath, string expectedDomain)
        {
            // Arrange
            var values = new Dictionary <string, object>();

            values.Add("int", 10);
            var tempDataProviderStore = new TempDataSerializer();
            var expectedDataToProtect = tempDataProviderStore.Serialize(values);
            var expectedDataInCookie  = Base64UrlTextEncoder.Encode(expectedDataToProtect);
            var dataProtector         = new PassThroughDataProtector();
            var tempDataProvider      = GetProvider(
                dataProtector,
                new CookieTempDataProviderOptions()
            {
                Path = optionsPath, Domain = optionsDomain
            });
            var responseCookies = new MockResponseCookieCollection();
            var httpContext     = new Mock <HttpContext>();

            httpContext
            .SetupGet(hc => hc.Request.IsHttps)
            .Returns(false);
            httpContext
            .SetupGet(hc => hc.Request.PathBase)
            .Returns(requestPathBase);
            httpContext
            .Setup(hc => hc.Response.Cookies)
            .Returns(responseCookies);

            // Act
            tempDataProvider.SaveTempData(httpContext.Object, values);

            // Assert
            Assert.Equal(1, responseCookies.Count);
            var cookieInfo = responseCookies[CookieTempDataProvider.CookieName];

            Assert.NotNull(cookieInfo);
            Assert.Equal(expectedDataInCookie, cookieInfo.Value);
            Assert.Equal(expectedDataToProtect, dataProtector.PlainTextToProtect);
            Assert.Equal(expectedCookiePath, cookieInfo.Options.Path);
            Assert.Equal(expectedDomain, cookieInfo.Options.Domain);
            Assert.False(cookieInfo.Options.Secure);
            Assert.True(cookieInfo.Options.HttpOnly);
            Assert.Null(cookieInfo.Options.Expires);
        }
Beispiel #6
0
    public void DataOfVariousLengthRoundTripCorrectly()
    {
        for (int length = 0; length != 256; ++length)
        {
            var data = new byte[length];
            for (int index = 0; index != length; ++index)
            {
                data[index] = (byte)(5 + length + (index * 23));
            }
            string text   = Base64UrlTextEncoder.Encode(data);
            byte[] result = Base64UrlTextEncoder.Decode(text);

            for (int index = 0; index != length; ++index)
            {
                Assert.Equal(data[index], result[index]);
            }
        }
    }
        public override string ToString()
        {
            var contractResolver = new DefaultContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy()
            };
            var serializerSettings = new JsonSerializerSettings
            {
                ContractResolver = contractResolver,
                Formatting       = Formatting.Indented
            };
            var jwtHeader = Base64UrlTextEncoder.Encode(
                Encoding.UTF8.GetBytes(
                    JsonConvert.SerializeObject(_jwtHeader, serializerSettings)
                    )
                );
            var jwtPayload = Base64UrlTextEncoder.Encode(
                Encoding.UTF8.GetBytes(
                    JsonConvert.SerializeObject(_jwtPayload, serializerSettings)
                    )
                );

            if (_signOption == JwtSignOption.NoSignature)
            {
                return($"{jwtHeader}.{jwtPayload}.");
            }
            string jwtSignature;
            var    rsa = (RSACng)_cert.PrivateKey;

            jwtSignature = Base64UrlTextEncoder.Encode(
                rsa.SignData(
                    Encoding.UTF8.GetBytes(
                        $"{jwtHeader}.{jwtPayload}"),
                    HashAlgorithmName.SHA256,
                    RSASignaturePadding.Pkcs1
                    )
                );
            if (_signOption == JwtSignOption.InvalidSignature)
            {
                // Laat de eerste 10 posities weg voor een ongeldige handtekening.
                jwtSignature = jwtSignature.Substring(10);
            }
            return($"{jwtHeader}.{jwtPayload}.{jwtSignature}");
        }
Beispiel #8
0
        public void SaveTempData_RemovesCookie_WhenNoDataToSave()
        {
            // Arrange
            var values = new Dictionary <string, object>();

            values.Add("int", 10);
            var tempDataProviderStore   = new TempDataSerializer();
            var serializedData          = tempDataProviderStore.Serialize(values);
            var base64AndUrlEncodedData = Base64UrlTextEncoder.Encode(serializedData);
            var dataProtector           = new PassThroughDataProtector();
            var tempDataProvider        = GetProvider(dataProtector);
            var requestCookies          = new RequestCookieCollection(new Dictionary <string, string>()
            {
                { CookieTempDataProvider.CookieName, base64AndUrlEncodedData }
            });
            var responseCookies = new MockResponseCookieCollection();
            var httpContext     = new Mock <HttpContext>();

            httpContext
            .SetupGet(hc => hc.Request.PathBase)
            .Returns("/");
            httpContext
            .Setup(hc => hc.Request.Cookies)
            .Returns(requestCookies);
            httpContext
            .Setup(hc => hc.Response.Cookies)
            .Returns(responseCookies);
            httpContext
            .Setup(hc => hc.Response.Headers)
            .Returns(new HeaderDictionary());

            // Act
            tempDataProvider.SaveTempData(httpContext.Object, new Dictionary <string, object>());

            // Assert
            Assert.Equal(1, responseCookies.Count);
            var cookie = responseCookies[CookieTempDataProvider.CookieName];

            Assert.NotNull(cookie);
            Assert.Equal(string.Empty, cookie.Value);
            Assert.NotNull(cookie.Options.Expires);
            Assert.True(cookie.Options.Expires.Value < DateTimeOffset.Now); // expired cookie
        }
    public void ValidateCircuitId_ReturnsFalseForPotentiallyTamperedPayloads()
    {
        // Arrange
        var factory        = TestCircuitIdFactory.CreateTestFactory();
        var secret         = factory.CreateCircuitId();
        var protectedBytes = Base64UrlTextEncoder.Decode(secret.Secret);

        for (int i = protectedBytes.Length - 10; i < protectedBytes.Length; i++)
        {
            protectedBytes[i] = 0;
        }
        var tampered = Base64UrlTextEncoder.Encode(protectedBytes);

        // Act
        var isValid = factory.TryParseCircuitId(tampered, out _);

        // Assert
        Assert.False(isValid, "Accepted a tampered payload");
    }
Beispiel #10
0
        protected void GenerateCorrelationId([NotNull] AuthenticationProperties properties)
        {
            var correlationKey = Constants.CorrelationPrefix + Options.AuthenticationScheme;

            var nonceBytes = new byte[32];

            CryptoRandom.GetBytes(nonceBytes);
            var correlationId = Base64UrlTextEncoder.Encode(nonceBytes);

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure   = Request.IsHttps
            };

            properties.Items[correlationKey] = correlationId;

            Response.Cookies.Append(correlationKey, correlationId, cookieOptions);
        }
Beispiel #11
0
        public static string Compress(string uncompressed)
        {
            byte[] compressedBytes;

            using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressed)))
            {
                using (var compressedStream = new MemoryStream())
                {
                    using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Optimal, true))
                    {
                        uncompressedStream.CopyTo(compressorStream);
                    }

                    compressedBytes = compressedStream.ToArray();
                }
            }

            return(Base64UrlTextEncoder.Encode(compressedBytes));
        }
Beispiel #12
0
        // Generates a circuit id that is produced from a strong cryptographic random number generator
        // we don't care about the underlying payload, other than its uniqueness and the fact that we
        // authenticate encrypt it using data protection.
        // For validation, the fact that we can unprotect the payload is guarantee enough.
        public CircuitId CreateCircuitId()
        {
            var buffer = new byte[SecretLength];

            RandomNumberGenerator.Fill(buffer);

            var id = new byte[IdLength];

            Array.Copy(
                sourceArray: buffer,
                sourceIndex: SecretLength - IdLength,
                destinationArray: id,
                destinationIndex: 0,
                length: IdLength);

            var secret = _protector.Protect(buffer);

            return(new CircuitId(Base64UrlTextEncoder.Encode(secret), Base64UrlTextEncoder.Encode(id)));
        }
Beispiel #13
0
        public async Task <IActionResult> Login(string returnUrl = null)
        {
            // If Windows Auth is enabled, check for a user and either sign up or sign in directly
            if (_config.GetValue <Enums.AuthenticationMode>("Customization:AuthenticationMode") == Enums.AuthenticationMode.Windows &&
                User.Identity.IsAuthenticated)
            {
                var identity = ((ClaimsIdentity)HttpContext.User.Identity);

                var username = identity.Name.Split('\\').Last();
                var domain   = identity.Name.Split('\\').First();
                var email    = string.Format("{0}@{1}.local", username, domain);

                var user = await _userManager.FindByEmailAsync(email);

                if (user == null)
                {
                    var rnd   = RandomNumberGenerator.Create();
                    var bytes = new byte[64];
                    rnd.GetBytes(bytes);

                    user = await CreateUser(username, "", "", email, Base64UrlTextEncoder.Encode(bytes));
                }

                await _signInManager.SignInAsync(user, isPersistent : false);

                if (!String.IsNullOrWhiteSpace(returnUrl))
                {
                    return(Redirect(returnUrl));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            else
            {
                // Clear the existing external cookie to ensure a clean login process
                await AuthenticationHttpContextExtensions.SignOutAsync(HttpContext);

                ViewData["ReturnUrl"] = returnUrl;
                return(View());
            }
        }
Beispiel #14
0
        private string GenerateToken(LevisUser user)
        {
            var parts = new List <byte[]>
            {
                BitConverter.GetBytes(DateTime.UtcNow.ToBinary()),
                (_providerUserKey).ToByteArray(),
                _privateTokenKey.ToByteArray(),
                Encoding.UTF8.GetBytes(user.UserName)
            };

            var tokenBytes = new byte[parts.Sum(s => s.Length)];
            var offset     = 0;

            foreach (var part in parts)
            {
                Buffer.BlockCopy(part, 0, tokenBytes, offset, part.Length);
                offset += part.Length;
            }
            return(Base64UrlTextEncoder.Encode(tokenBytes.ToArray()));
        }
    /// <summary>
    /// Produces a cookie containing a nonce used to correlate the current remote authentication request.
    /// </summary>
    /// <param name="properties"></param>
    protected virtual void GenerateCorrelationId(AuthenticationProperties properties)
    {
        if (properties == null)
        {
            throw new ArgumentNullException(nameof(properties));
        }

        var bytes = new byte[32];

        RandomNumberGenerator.Fill(bytes);
        var correlationId = Base64UrlTextEncoder.Encode(bytes);

        var cookieOptions = Options.CorrelationCookie.Build(Context, Clock.UtcNow);

        properties.Items[CorrelationProperty] = correlationId;

        var cookieName = Options.CorrelationCookie.Name + correlationId;

        Response.Cookies.Append(cookieName, CorrelationMarker, cookieOptions);
    }
        public void ShorterStateTest_WhereKeepRedirect(bool expected, int correlationIdGeneratorSize, int redirectUrlLen)
        {
            var stateFormat = new PropertiesDataFormat(new EphemeralDataProtectionProvider(NullLoggerFactory.Instance).CreateProtector("WeixinAuthTest"));
            var properties  = new AuthenticationProperties();

            var cryptoRandom = RandomNumberGenerator.Create();
            var bytes        = new byte[correlationIdGeneratorSize];

            cryptoRandom.GetBytes(bytes);
            var correlationId = Base64UrlTextEncoder.Encode(bytes);

            properties.Items[".xrsf"] = correlationId;

            var redirectUrl = new string('a', redirectUrlLen);

            properties.Items[".redirect"] = redirectUrl;

            var state = stateFormat.Protect(properties);

            Assert.Equal(expected, state.Length <= 128);
        }
    public async Task <IActionResult> Authorize(string returnUrl)
    {
        var state    = Base64UrlTextEncoder.Encode(Encoding.UTF8.GetBytes(returnUrl));
        var response = await _oAuthFlows.RunFlow(_oAuthClientConfiguration, state);

        switch (response)
        {
        case OAuthRedirect oAuthRedirect:
            TempData[Common.State]        = oAuthRedirect.State;
            TempData[Common.CodeVerifier] = oAuthRedirect.CodeVerifier;
            return(Redirect(oAuthRedirect.Uri));

        case AccessTokenResponse accessTokenResponse:
            return(await SignInUser(accessTokenResponse, state));

        case ErrorResponse errorResponse:
            return(ProcessOAuthClientErrorResponse(errorResponse));
        }

        return(BadRequest());
    }
        protected override async Task <string> CreateJwtAsync(JwtSecurityToken jwt)
        {
            var plaintext = $"{jwt.EncodedHeader}.{jwt.EncodedPayload}";

            byte[] hash;
            using (var hasher = CryptoHelper.GetHashAlgorithmForSigningAlgorithm(jwt.SignatureAlgorithm))
            {
                hash = hasher.ComputeHash(Encoding.UTF8.GetBytes(plaintext));
            }

            var cryptoClient = new CryptographyClient(
                new Uri(""), // e.g. https://scottbrady91-test.vault.azure.net/keys/IdentityServerSigningKeyEcc
                new ClientSecretCredential(
                    tenantId: "",
                    clientId: "",
                    clientSecret: ""));

            var signResult = await cryptoClient.SignAsync(new SignatureAlgorithm(jwt.SignatureAlgorithm), hash);

            return($"{plaintext}.{Base64UrlTextEncoder.Encode(signResult.Signature)}");
        }
        public async Task <string> StoreAsync(AuthenticationTicket ticket)
        {
            var bytes = new byte[32];

            CryptoRandom.GetBytes(bytes);
            var sessionId = Base64UrlTextEncoder.Encode(bytes);

            var session = new Session
            {
                SessionId        = sessionId,
                IdentityId       = ticket.Principal.GetClaimGuidValue(ClaimTypes.NameIdentifier),
                CorrelationId    = ticket.Principal.GetClaimGuidValue(ClaimTypes.SerialNumber),
                LastAccess       = DateTimeOffset.Now,
                Expires          = ticket.Properties.ExpiresUtc ?? DateTimeOffset.Now.AddDays(1),
                SerializedTicket = _ticketSerializer.Serialize(ticket)
            };

            await _sessionStorage.CreateAsync(session);

            return(session.SessionId);
        }
Beispiel #20
0
        private Response HandleBasicRoute(RouteDetails numInfo)
        {
            _logger.LogInformation($"HandleBasicRoute");

            var ret  = new Response();
            var dial = ConstructDial(numInfo);

            if (numInfo.callRecordEnabled)
            {
                TwilioSay  saying = null;
                TwilioPlay play   = null;
                bool       callRecordKeyPressRequired = (numInfo.callRecordConfirmationRequired ?? false) && (!string.IsNullOrEmpty(numInfo.callRecordNotificationText) || !string.IsNullOrEmpty(numInfo.callRecordNotificationFileId));

                if (!string.IsNullOrEmpty(numInfo.callRecordNotificationText))
                {
                    var lang = numInfo.terminationNumber.StartsWith("61")
                        ? "en-AU"
                        : "en-US";

                    saying = new TwilioSay {
                        Loop = 1, Text = numInfo.callRecordNotificationText, Voice = "alice", Language = lang
                    };
                }
                else if (!string.IsNullOrEmpty(numInfo.callRecordNotificationFileId))
                {
                    var fileLink      = $"{numInfo.callRecordNotificationFileId}-{numInfo.callRecordNotificationFileName}";
                    var mediaFileType = numInfo.callRecordNotificationFileType == 6
                        ? "CallRecordStudyFiles"
                        : "CallRecordNotificationFiles";
                    play = new TwilioPlay {
                        Loop = 1, Text = $"{_mediaFileUrl}/api/mediafile?mediaFile={Base64UrlTextEncoder.Encode(Encoding.UTF8.GetBytes(fileLink))}&amp;mediaType={mediaFileType}&amp;tenantId=1234"
                    };
                }
                ret.Saying = saying;
                ret.Play   = play;
            }
            ret.Dialing = dial;

            return(ret);
        }
Beispiel #21
0
        public void SaveTempData_SetsSecureAttributeOnCookie_OnlyIfRequestIsSecure(bool isSecure)
        {
            // Arrange
            var values = new Dictionary <string, object>();

            values.Add("int", 10);
            var tempDataProviderStore = new TempDataSerializer();
            var expectedDataToProtect = tempDataProviderStore.Serialize(values);
            var expectedDataInCookie  = Base64UrlTextEncoder.Encode(expectedDataToProtect);
            var dataProtector         = new PassThroughDataProtector();
            var tempDataProvider      = GetProvider(dataProtector);
            var responseCookies       = new MockResponseCookieCollection();
            var httpContext           = new Mock <HttpContext>();

            httpContext
            .SetupGet(hc => hc.Request.PathBase)
            .Returns("/");
            httpContext
            .SetupGet(hc => hc.Request.IsHttps)
            .Returns(isSecure);
            httpContext
            .Setup(hc => hc.Response.Cookies)
            .Returns(responseCookies);

            // Act
            tempDataProvider.SaveTempData(httpContext.Object, values);

            // Assert
            Assert.Equal(1, responseCookies.Count);
            var cookieInfo = responseCookies[CookieTempDataProvider.CookieName];

            Assert.NotNull(cookieInfo);
            Assert.Equal(expectedDataInCookie, cookieInfo.Value);
            Assert.Equal(expectedDataToProtect, dataProtector.PlainTextToProtect);
            Assert.Equal("/", cookieInfo.Options.Path);
            Assert.Equal(isSecure, cookieInfo.Options.Secure);
            Assert.True(cookieInfo.Options.HttpOnly);
            Assert.Null(cookieInfo.Options.Expires);
            Assert.Null(cookieInfo.Options.Domain);
        }
Beispiel #22
0
        public async Task <ExternalApplicationsResult> Create([FromBody] ExternalApplicationToCreate externalApplicationToCreate)
        {
            var bytes = new byte[60];

            CryptoRandom.GetBytes(bytes);
            var applicationKey = Base64UrlTextEncoder.Encode(bytes);

            var newExternalApplication = new ExternalApplication
            {
                Active                = externalApplicationToCreate.Active,
                ActiveUntil           = externalApplicationToCreate.ActiveUntil,
                ApplicationKey        = applicationKey,
                ExternalApplicationId = Guid.NewGuid(),
                Name = externalApplicationToCreate.Name
            };

            await _externalApplicationStorage.CreateAsync(newExternalApplication);

            return(new ExternalApplicationsResult {
                ExternalApplications = new[] { newExternalApplication }
            });
        }
Beispiel #23
0
        public CodeFlowData GetCodeFlowData(string redirectUri)
        {
            // Generates state and PKCE values.
            var state         = RandomBase64Url(32);
            var codeVerifier  = RandomBase64Url(32);
            var codeChallenge = Base64UrlTextEncoder.Encode(Sha256(codeVerifier));

            var uri = QueryHelpers.AddQueryString(
                new Uri(_httpClient.BaseAddress, "connect/auth").ToString(),
                new Dictionary <string, string>
            {
                { "response_type", "code" },
                { "redirect_uri", redirectUri },
                { "client_id", _clientId },
                { "scope", _scope },
                { "state", state },
                { "code_challenge", codeChallenge },
                { "code_challenge_method", "S256" }
            });

            return(new CodeFlowData(uri, state, codeVerifier, redirectUri));
        }
Beispiel #24
0
        public bool TryParseCircuitId(string?text, out CircuitId circuitId)
        {
            if (text is null)
            {
                circuitId = default;
                return(false);
            }

            try
            {
                var protectedBytes   = Base64UrlTextEncoder.Decode(text);
                var unprotectedBytes = _protector.Unprotect(protectedBytes);

                if (unprotectedBytes.Length != SecretLength)
                {
                    // Wrong length
                    circuitId = default;
                    return(false);
                }

                var id = new byte[IdLength];
                Array.Copy(
                    sourceArray: unprotectedBytes,
                    sourceIndex: SecretLength - IdLength,
                    destinationArray: id,
                    destinationIndex: 0,
                    length: IdLength);

                circuitId = new CircuitId(text, Base64UrlTextEncoder.Encode(id));
                return(true);
            }
            catch (Exception)
            {
                // The payload format is not correct (either not base64urlencoded or not data protected)
                circuitId = default;
                return(false);
            }
        }
        protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
        {
            var queryStrings = new Dictionary <string, string?>
            {
                { "client_id", Options.ClientId },
                { "response_type", "code" },
                { "redirect_uri", redirectUri }
            };

            AddQueryString(queryStrings !, properties, MicrosoftChallengeProperties.ScopeKey, FormatScope, Options.Scope);
            AddQueryString(queryStrings !, properties, MicrosoftChallengeProperties.ResponseModeKey);
            AddQueryString(queryStrings !, properties, MicrosoftChallengeProperties.DomainHintKey);
            AddQueryString(queryStrings !, properties, MicrosoftChallengeProperties.LoginHintKey);
            AddQueryString(queryStrings !, properties, MicrosoftChallengeProperties.PromptKey);

            if (Options.UsePkce)
            {
                var bytes = new byte[32];
                CryptoRandom.GetBytes(bytes);
                var codeVerifier = Base64UrlTextEncoder.Encode(bytes);

                // Store this for use during the code redemption.
                properties.Items.Add(OAuthConstants.CodeVerifierKey, codeVerifier);

                using var sha256 = SHA256.Create();
                var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));
                var codeChallenge  = WebEncoders.Base64UrlEncode(challengeBytes);

                queryStrings[OAuthConstants.CodeChallengeKey]       = codeChallenge;
                queryStrings[OAuthConstants.CodeChallengeMethodKey] = OAuthConstants.CodeChallengeMethodS256;
            }

            var state = Options.StateDataFormat.Protect(properties);

            queryStrings.Add("state", state);

            return(QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, queryStrings));
        }
        /// <inheritdoc />
        protected override string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
        {
            var queryStrings = new Dictionary <string, string>
            {
                { "client_id", Options.ClientId },
                { "response_type", "code" },
                { "redirect_uri", redirectUri }
            };

            AddQueryString(queryStrings, properties, MicrosoftChallengeProperties.ScopeKey, FormatScope, Options.Scope);
#pragma warning disable CS0618 // Type or member is obsolete
            AddQueryString(queryStrings, properties, MicrosoftChallengeProperties.ResponseModeKey);
#pragma warning restore CS0618 // Type or member is obsolete
            AddQueryString(queryStrings, properties, MicrosoftChallengeProperties.DomainHintKey);
            AddQueryString(queryStrings, properties, MicrosoftChallengeProperties.LoginHintKey);
            AddQueryString(queryStrings, properties, MicrosoftChallengeProperties.PromptKey);

            if (Options.UsePkce)
            {
                var bytes = new byte[32];
                RandomNumberGenerator.Fill(bytes);
                var codeVerifier = Base64UrlTextEncoder.Encode(bytes);

                // Store this for use during the code redemption.
                properties.Items.Add(OAuthConstants.CodeVerifierKey, codeVerifier);

                var challengeBytes = SHA256.HashData(Encoding.UTF8.GetBytes(codeVerifier));
                var codeChallenge  = WebEncoders.Base64UrlEncode(challengeBytes);

                queryStrings[OAuthConstants.CodeChallengeKey]       = codeChallenge;
                queryStrings[OAuthConstants.CodeChallengeMethodKey] = OAuthConstants.CodeChallengeMethodS256;
            }

            var state = Options.StateDataFormat.Protect(properties);
            queryStrings.Add("state", state);

            return(QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, queryStrings));
        }
Beispiel #27
0
        public async Task <Message> CreateMessage(string key, string content, DateTime expiresAt)
        {
            string id;

            do
            {
                Encryption.GenerateRandomBytes(48, out var idBytes);
                id = Base64UrlTextEncoder.Encode(idBytes);
            }while (await _context.Messages.AnyAsync(m => m.Id == id));

            var message = new Message
            {
                Id = id,
                EncryptedContent = Encryption.Encrypt(content, key),
                ExpiresAt        = expiresAt,
                CreatedAt        = DateTime.UtcNow
            };

            _context.Messages.Add(message);
            await _context.SaveChangesAsync();

            return(message);
        }
        public async Task <IActionResult> SignUp([FromBody] SignUpModel model)
        {
            try
            {
                var emailConfirmationToken = await _authenticateService.SignUpAsync(model.Fullname, model.Email, model.Password);

                var token = new Token {
                    Email = model.Email, Hash = emailConfirmationToken
                };
                var tokenJson       = JsonConvert.SerializeObject(token);
                var tokenJsonBytes  = Encoding.UTF8.GetBytes(tokenJson);
                var tokenJsonBase64 = Base64UrlTextEncoder.Encode(tokenJsonBytes);

                var emailConfirmationLink = $"{model.RedirectUrl}?token={tokenJsonBase64}";
                _backgroundJobClient.Enqueue <SendEmailJob>(x =>
                                                            x.SendConfirmationLinkEmail(model.Email, model.Fullname, emailConfirmationLink)
                                                            );

                var response = new Response {
                    Status = 200, Message = "A confirmation email was sent to your email address."
                };
                return(Ok(response));
            }
            catch (UserSignUpException e)
            {
                return(Ok(new Response {
                    Status = 403, Message = e.Error.Description
                }));
            }
            catch
            {
                return(Ok(new Response {
                    Status = 500, Message = "Internal Server Error."
                }));
            }
        }
Beispiel #29
0
        public virtual async Task <IActionResult> ListTasks([FromQuery] string namePrefix, [FromQuery] long?pageSize, [FromQuery] string pageToken, [FromQuery] string view)
        {
            var decodedPageToken =
                pageToken != null?Encoding.UTF8.GetString(Base64UrlTextEncoder.Decode(pageToken)) : null;

            if (pageSize < 1 || pageSize > 2047)
            {
                logger.LogError($"pageSize invalid {pageSize}");
                return(BadRequest("If provided, pageSize must be greater than 0 and less than 2048. Defaults to 256."));
            }

            (var nextPageToken, var tasks) = await repository.GetItemsAsync(
                t => string.IsNullOrWhiteSpace(namePrefix) || t.Name.StartsWith(namePrefix),
                pageSize.HasValue?(int)pageSize : 256,
                decodedPageToken);

            var encodedNextPageToken = nextPageToken != null?Base64UrlTextEncoder.Encode(Encoding.UTF8.GetBytes(nextPageToken)) : null;

            var response = new TesListTasksResponse {
                Tasks = tasks.Select(t => t.Value).ToList(), NextPageToken = encodedNextPageToken
            };

            return(TesJsonResult(response, view));
        }
Beispiel #30
0
        private static string EncryptAES(string text, string key, string iv)
        {
            //Convert SourceString to byte []
            var sourceBytes = Encoding.UTF8.GetBytes(text);

            var aes = Aes.Create();

            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            //Convert key/iv string to byte [] and assign to Aes's Key/IV property
            MD5CryptoServiceProvider    md5    = new MD5CryptoServiceProvider();
            SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider();

            byte[] keyData = sha256.ComputeHash(Encoding.UTF8.GetBytes(key));
            byte[] IVData  = md5.ComputeHash(Encoding.UTF8.GetBytes(iv));
            aes.Key = keyData;
            aes.IV  = IVData;

            var transform = aes.CreateEncryptor();

            //I Encrypt sourceString to Base64Url(Base64String for Url),you can Encrypt to Base64String (System.Convert.ToBase64String)
            return(Base64UrlTextEncoder.Encode(transform.TransformFinalBlock(sourceBytes, 0, sourceBytes.Length)));
        }