Exemple #1
0
        public async Task <string> CreateJwtAsync(JwtSecurityToken token)
        {
            var ecdsaCache = await _keyVaultECDsaKeyStore.FetchCacheAsync();

            string algorithm = ecdsaCache.SecurityKeyInfos.First().SigningAlgorithm;
            var    header    = Base64UrlEncoder.Encode(_serializer.Serialize(
                                                           new Dictionary <string, string>()
            {
                { JwtHeaderParameterNames.Alg, algorithm },
                { JwtHeaderParameterNames.Kid, ecdsaCache.CurrentKeyProperties.Version },
                { JwtHeaderParameterNames.Typ, "JWT" }
            }));
            var rawDataBytes = Encoding.UTF8.GetBytes(header + "." + token.EncodedPayload);

            byte[] hash;
            using (var hasher = CryptoHelper.GetHashAlgorithmForSigningAlgorithm(algorithm))
            {
                hash = hasher.ComputeHash(rawDataBytes);
            }
            var signResult = await ecdsaCache.CryptographyClient.SignAsync(
                new SignatureAlgorithm(algorithm), hash);

            var rawSignature = Base64UrlTextEncoder.Encode(signResult.Signature);

            return($"{header}.{token.EncodedPayload}.{rawSignature}");
        }
Exemple #2
0
        public AuthenticationTicket Unprotect(string protectedText)
        {
            try
            {
                if (protectedText == null)
                {
                    return(default(AuthenticationTicket));
                }

                Base64UrlTextEncoder encoder = new Base64UrlTextEncoder();
                var protectedData            = encoder.Decode(protectedText);
                if (protectedData == null)
                {
                    return(default(AuthenticationTicket));
                }


                var userData = rsa.Decrypt(protectedData);
                if (userData == null)
                {
                    return(default(AuthenticationTicket));
                }

                return(_serializer.Deserialize(userData));
            }
            catch
            {
                // TODO trace exception, but do not leak other information
                return(default(AuthenticationTicket));
            }
        }
Exemple #3
0
        protected async Task GenerateCorrelationId(AuthenticationProperties properties)
        {
            // I think here we need to use a different correlationkey per folder site
            // becuase that is used for the cookie name
            // unless using related sites mode we want fodler sites to use different cookies

            var correlationKey = Constants.CorrelationPrefix + Options.AuthenticationScheme;

            correlationKey = await tenantOptions.ResolveCorrelationKey(correlationKey);

            log.LogDebug("GenerateCorrelationId called, correlationKey was " + correlationKey);

            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);
        }
        protected virtual string BuildChallengeUrl(AuthenticationProperties properties, string redirectUri)
        {
            var scopeParameter = properties.GetParameter <ICollection <string> >(OAuthChallengeProperties.ScopeKey);
            var scope          = scopeParameter != null?FormatScope(scopeParameter) : FormatScope();

            var parameters = new Dictionary <string, string>
            {
                { "client_id", Options.ClientId },
                { "scope", scope },
                { "response_type", "code" },
                { "redirect_uri", redirectUri },
            };

            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);

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

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

            parameters["state"] = Options.StateDataFormat.Protect(properties);

            return(QueryHelpers.AddQueryString(Options.AuthorizationEndpoint, parameters));
        }
Exemple #5
0
        public AuthenticationTicket Unprotect(string protectedText, string purpose)
        {
            var authTicket = default(AuthenticationTicket);
            var algorithm  = JwtOptions.Algorithm;

            try
            {
                authTicket = _ticketSerializer.Deserialize(
                    _dataProtector.Unprotect(
                        Base64UrlTextEncoder.Decode(protectedText)));

                var embeddedJwt = authTicket
                                  .Properties?
                                  .GetTokenValue(_jwtOptions.TokenName);
                new JwtSecurityTokenHandler()
                .ValidateToken(embeddedJwt, _jwtOptions.ValidationParameters, out var token);

                if (!(token is JwtSecurityToken jwt))
                {
                    throw new SecurityTokenValidationException("JWT token was found to be invalid");
                }

                if (!jwt.Header.Alg.Equals(algorithm, StringComparison.Ordinal))
                {
                    throw new ArgumentException($"Algorithm must be '{algorithm}'");
                }
            }
            catch (Exception)
            {
                return(null);
            }

            return(authTicket);
        }
        public async Task <IActionResult> GenerateFilesToBalance([FromBody] int[] productsId)
        {
            try
            {
                string guid   = Guid.NewGuid().ToString();
                var    folder = Path.Combine(_hostingEnvironment.ContentRootPath, "temp", guid);
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                var itensFileContent = await(_service as IProductService).GenerateFileContentItensToBalance(productsId);
                var infoFileContent  = await(_service as IProductService).GenerateFileContentInfoToBalance(productsId);
                await(_service as IProductService).UpdateProductsExportedToBalance(productsId);

                return(Ok(new
                {
                    itensFilecontent = Base64UrlTextEncoder.Encode(Encoding.UTF8.GetBytes(itensFileContent)),
                    infoFileContent = Base64UrlTextEncoder.Encode(Encoding.UTF8.GetBytes(infoFileContent)),
                }));
            }
            catch (NotSupportedException e)
            {
                _logger.LogError(e, "Error");
                return(SendBadRequest(e.Message.Split('|')));
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error");
                return(SendBadRequest(e));
            }
        }
Exemple #7
0
        public string Base64UrlDecodeAndDecompressToUnicode(string content)
        {
            var bytes   = Base64UrlTextEncoder.Decode(content);
            var decoded = DecompressToUnicode(bytes);

            return(decoded);
        }
Exemple #8
0
    /// <inheritdoc />
    public TData?Unprotect(string?protectedText, string?purpose)
    {
        try
        {
            if (protectedText == null)
            {
                return(default(TData));
            }

            var protectedData = Base64UrlTextEncoder.Decode(protectedText);
            if (protectedData == null)
            {
                return(default(TData));
            }

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

            var userData = protector.Unprotect(protectedData);
            if (userData == null)
            {
                return(default(TData));
            }

            return(_serializer.Deserialize(userData));
        }
        catch
        {
            // TODO trace exception, but do not leak other information
            return(default(TData));
        }
    }
        public async Task <IActionResult> ConfirmResetPassword([Required] string newPassword, [Required] string token)
        {
            var result = JsonSerializer.SerializeToUtf8Bytes(await _userRepo.ConfirmChangePasswordAsync(newPassword, token));

            return(RedirectPermanent($"http://{_configuration["Host"]}/result?response=" +
                                     Base64UrlTextEncoder.Encode(result)));
        }
Exemple #10
0
        public IActionResult DecryptCookie()
        {
            ViewData["Message"] = "This is the decrypt page";
            var user = HttpContext.User;        //User will be set to the ClaimsPrincipal

            //Get the encrypted cookie value
            string cookieValue = HttpContext.Request.Cookies["gicoOAU"];
            IDataProtectionProvider provider = HttpContext.RequestServices.GetService <IDataProtectionProvider>();

            //Get a data protector to use with either approach
            var dataProtector = provider.CreateProtector(
                "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                "Cookies",
                "v2");


            //Get the decrypted cookie as plain text
            UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

            byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookieValue);
            byte[] plainBytes     = dataProtector.Unprotect(protectedBytes);
            string plainText      = specialUtf8Encoding.GetString(plainBytes);


            //Get teh decrypted cookies as a Authentication Ticket
            TicketDataFormat     ticketDataFormat = new TicketDataFormat(dataProtector);
            AuthenticationTicket ticket           = ticketDataFormat.Unprotect(cookieValue);

            return(Content("111"));
        }
        public static async Task HandleAsync(string clientId, string clientSecret, string callbackUrl)
        {
            string nonce         = RandomValues.CreateNonce();
            string state         = RandomValues.CreateState();
            string codeVerifier  = RandomValues.CreateCodeVerifier();
            string codeChallenge = Base64UrlTextEncoder.Encode(SHA256.HashData(Encoding.UTF8.GetBytes(codeVerifier)));

            callbackUrl ??= Urls.DefaultCallback;

            using HttpClient client = HttpClientFactory.Create();

            JsonElement configuration = await client.GetAsJsonAsync(Urls.OpenIdConnectConfiguration);

            Task <string> waitForAuthorizationCodeTask = await AuthorizationCodeCallbackListener.StartAsync(callbackUrl, state);

            Browser.OpenLoginPage(configuration.AuthorizationEndpoint(), nonce, state, codeChallenge, clientId, callbackUrl);

            string authorizationCode = await waitForAuthorizationCodeTask;

            var tokenEndpointPostContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("grant_type", "authorization_code"),
                new KeyValuePair <string, string>("code", authorizationCode),
                new KeyValuePair <string, string>("redirect_uri", callbackUrl),
                new KeyValuePair <string, string>("code_verifier", codeVerifier),
                new KeyValuePair <string, string>("client_id", clientId),
                new KeyValuePair <string, string>("client_secret", clientSecret)
            });
            JsonElement tokens = await client.PostAndReadAsJsonAsync(configuration.TokenEndpoint(), tokenEndpointPostContent);

            Console.WriteLine(tokens.FormatForDisplay());
        }
Exemple #12
0
        public async Task <ActionResult> OAuthAuthorizationCodeGrantClient(string code, string state)
        {
            try
            {
                OAuth2AndOIDCClient.HttpClient = new HttpClient();
                string response = "";

                if (state == this.State) // CSRF(XSRF)対策のstateの検証は重要
                {
                    response = await OAuth2AndOIDCClient.GetAccessTokenByCodeAsync(
                        new Uri("http://localhost:63359/MultiPurposeAuthSite/OAuthBearerToken"),
                        OAuth2AndOIDCParams.ClientID, OAuth2AndOIDCParams.ClientSecret,
                        HttpUtility.HtmlEncode("http://localhost:63877/SPA_Sample/Home/OAuthAuthorizationCodeGrantClient"), code);

                    // 汎用認証サイトはOIDCをサポートしたのでid_tokenを取得し、検証可能。
                    Base64UrlTextEncoder        base64UrlEncoder = new Base64UrlTextEncoder();
                    Dictionary <string, string> dic = JsonConvert.DeserializeObject <Dictionary <string, string> >(response);

                    // id_tokenの検証コード
                    if (dic.ContainsKey("id_token"))
                    {
                        string id_token = dic["id_token"];

                        string        sub    = "";
                        List <string> roles  = null;
                        List <string> scopes = null;
                        JObject       jobj   = null;

                        if (JwtToken.Verify(id_token, out sub, out roles, out scopes, out jobj) &&
                            jobj["nonce"].ToString() == this.Nonce)
                        {
                            // ログインに成功

                            // /userinfoエンドポイントにアクセスする場合
                            response = await OAuth2AndOIDCClient.CallUserInfoEndpointAsync(
                                new Uri("http://localhost:63359/MultiPurposeAuthSite/userinfo"), dic["access_token"]);

                            FormsAuthentication.RedirectFromLoginPage(sub, false);
                            MyUserInfo ui = new MyUserInfo(sub, Request.UserHostAddress);
                            UserInfoHandle.SetUserInformation(ui);

                            return(new EmptyResult());
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                }

                // ログインに失敗
                return(RedirectToAction("Login"));
            }
            finally
            {
                this.ClearExLoginsParams();
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="properties">properties only .Items[CorrelationProperty] used.</param>
        protected override void GenerateCorrelationId(AuthenticationProperties properties)
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            var bytes = new byte[32];

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

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure   = Request.IsHttps,
                Expires  = Clock.UtcNow.Add(Options.RemoteAuthenticationTimeout),
            };

            properties.Items[CorrelationProperty] = correlationId; //need to build challenge url

            var cookieName = ConcateCookieName(correlationId);

            Response.Cookies.Append(cookieName, Options.StateDataFormat.Protect(properties), cookieOptions);
        }
 public static string RawBase64Serialize <T>(this T raw)
 {
     using (MemoryStream binary = new MemoryStream()) {
         new BinaryFormatter().Serialize(binary, raw);
         return(Base64UrlTextEncoder.Encode(binary.ToArray()));
     }
 }
Exemple #15
0
        private static void GenerateCorrelationId(HttpContext context, OpenIdConnectOptions options, AuthenticationProperties properties)
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            var bytes = new byte[32];

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

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure   = context.Request.IsHttps,
                Expires  = DateTimeOffset.UtcNow + options.ProtocolValidator.NonceLifetime
            };

            properties.Items[CorrelationProperty] = correlationId;

            var cookieName = CookieStatePrefix + OpenIdConnectDefaults.AuthenticationScheme + "." + correlationId;

            context.Response.Cookies.Append(cookieName, NonceProperty, cookieOptions);
        }
Exemple #16
0
        public static AuthenticationTicket GetCookieAuthenticationTicket(this HttpContext context, CookieAuthenticationOptions options)
        {
            try
            {
                //Get the encrypted cookie value
                string cookieValue = context.Request.Cookies[".AspNetCore.CookieAuth"];

                //Get a data protector to use with either approach
                var dataProtector = options.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "CookieAuth", "v2");

                //Get the decrypted cookie as plain text
                UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
                byte[]       protectedBytes      = Base64UrlTextEncoder.Decode(cookieValue);
                byte[]       plainBytes          = dataProtector.Unprotect(protectedBytes);
                string       plainText           = specialUtf8Encoding.GetString(plainBytes);

                //Get the decrypted cookie as a Authentication Ticket
                TicketDataFormat     ticketDataFormat = new TicketDataFormat(dataProtector);
                AuthenticationTicket ticket           = ticketDataFormat.Unprotect(cookieValue);

                return(ticket);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemple #17
0
        public void TimeBasedTokenGenerator_Defaults_GenerateTokenWithDefaults()
        {
            var gen   = new Csg.ApiKeyGenerator.TimeBasedTokenGenerator();
            var token = Base64UrlTextEncoder.Encode(gen.ComputeToken(ClientID, ClientSecret, TokenDateTime));

            Assert.AreEqual(TokenString, token);
        }
        private void TryRemoveUser(Dictionary <string, string> clientParams)
        {
            _logger.LogTrace("Starting to try and remove user");
            if (!Request.Form.ContainsKey("urs"))
            {
                _logger.LogError("Missing URS in request to remove user");
                SendResponse(Tif.IpMatch | Tif.IdMatch | Tif.CommandFailed | Tif.ClientFailed);
                return;
            }

            var idk = clientParams["idk"];

            var message  = Encoding.ASCII.GetBytes(Request.Form["client"] + Request.Form["server"]);
            var usersVuk = Base64UrlTextEncoder.Decode(Options.GetUserVukInternal(idk, Request.HttpContext));
            var urs      = Base64UrlTextEncoder.Decode(Request.Form["urs"]);
            var valid    = Ed25519.Verify(urs, message, usersVuk);

            if (!valid)
            {
                _logger.LogError("Invalid URS to unlock user.");
                _logger.LogDebug("Message to validate: {0}", Request.Form["client"] + Request.Form["server"]);
                _logger.LogDebug("VUK stored on server: {0}", Options.GetUserVukInternal(idk, Request.HttpContext));
                _logger.LogDebug("URS sent by client: {0}", Request.Form["urs"]);
                SendResponse(Tif.IpMatch | Tif.CommandFailed | Tif.ClientFailed);
                return;
            }

            Options.RemoveUserInternal(idk, Request.HttpContext);
            _logger.LogInformation("Remove user {0}", idk);
            _logger.LogTrace("Remove user and responding to client as valid identified user");
            SendResponse(Tif.IdMatch | Tif.IpMatch, !AuthorizeNut(Request.Query["nut"]));
        }
Exemple #19
0
        public void SaveTempData(HttpContext context, IDictionary <string, object> values)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var cookieOptions = new CookieOptions()
            {
                Domain   = string.IsNullOrEmpty(_options.Value.Domain) ? null : _options.Value.Domain,
                HttpOnly = true,
                Secure   = context.Request.IsHttps,
            };

            SetCookiePath(context, cookieOptions);

            var hasValues = (values != null && values.Count > 0);

            if (hasValues)
            {
                var bytes = _tempDataSerializer.Serialize(values);
                bytes = _dataProtector.Protect(bytes);
                var encodedValue = Base64UrlTextEncoder.Encode(bytes);
                _chunkingCookieManager.AppendResponseCookie(context, CookieName, encodedValue, cookieOptions);
            }
            else
            {
                _chunkingCookieManager.DeleteCookie(context, CookieName, cookieOptions);
            }
        }
Exemple #20
0
        private string CreateSecret()
        {
            var key = new byte[KeyLength];

            RandomNumberGenerator.Create().GetBytes(key);
            return(Base64UrlTextEncoder.Encode(key));
        }
Exemple #21
0
        public string CompressAndBase64UrlEncodeUnicode(string content)
        {
            var bytes  = CompressUnicode(content);
            var base64 = Base64UrlTextEncoder.Encode(bytes);

            return(base64);
        }
        public static void LogTransaction(HttpRequest request, string response)
        {
            var info = new DiagnosticsInfo()
            {
                RequestUrl   = "[" + request.Method + "]" + request.Host + request.Path + request.QueryString,
                Body         = new List <string>(),
                ResponseBody = new List <string>()
            };

            if (request.HasFormContentType)
            {
                foreach (var form in request.Form)
                {
                    if (form.Key == "client" || form.Key == "server")
                    {
                        var clientParams = Encoding.ASCII.GetString(Base64UrlTextEncoder.Decode(form.Value))
                                           .Replace("\r\n", "\n")
                                           .Split('\n')
                                           .Where(x => x.Contains("="))
                                           .ToDictionary(x => x.Split('=')[0], x => x.Remove(0, x.Split('=')[0].Length + 1));

                        foreach (var param in clientParams)
                        {
                            info.Body.Add(form.Key + "." + param.Key + ": " + param.Value);
                        }
                        continue;
                    }
                    info.Body.Add(form.Key + ": " + form.Value);
                }
            }

            var responseValues = response
                                 .Replace("\r\n", "\n")
                                 .Split('\n')
                                 .Where(x => x.Contains("="))
                                 .ToDictionary(x => x.Split('=')[0], x => x.Remove(0, x.Split('=')[0].Length + 1));

            foreach (var responseValue in responseValues)
            {
                if (responseValue.Key == "tif")
                {
                    var intValue  = int.Parse(responseValue.Value, System.Globalization.NumberStyles.HexNumber);
                    var translate = Enum.TryParse <SqrlCommandWorker.Tif>(intValue.ToString(), out var tifText);
                    if (translate)
                    {
                        info.ResponseBody.Add(responseValue.Key + ": " + responseValue.Value + " ( " + tifText.ToString("F") + " ) ");
                    }
                    else
                    {
                        info.ResponseBody.Add(responseValue.Key + ": " + responseValue.Value + " ( !!!UNKNOWN!!! ) ");
                    }
                }
                else
                {
                    info.ResponseBody.Add(responseValue.Key + ": " + responseValue.Value);
                }
            }

            TransactionLog.Add(info);
        }
Exemple #23
0
        public TreeNode(CallTreeNode template)
        {
            if (template == null)
            {
                ThrowHelper.ThrowArgumentNullException(nameof(template));
            }

            this.Path                         = string.Empty;
            this.Base64EncodedId              = Base64UrlTextEncoder.Encode(Encoding.UTF8.GetBytes(template.Name));
            this.Name                         = template.Name;
            this.InclusiveMetric              = template.InclusiveMetric.ToString("N3");
            this.InclusiveCount               = template.InclusiveCount.ToString("N0");
            this.ExclusiveMetric              = template.ExclusiveMetric.ToString("N3");
            this.ExclusiveCount               = template.ExclusiveCount.ToString("N0");
            this.ExclusiveFoldedMetric        = template.ExclusiveFoldedMetric.ToString("N0");
            this.ExclusiveFoldedCount         = template.ExclusiveFoldedCount.ToString("N0");
            this.InclusiveMetricByTimeString  = template.InclusiveMetricByTimeString;
            this.FirstTimeRelativeMSec        = template.FirstTimeRelativeMSec.ToString("N3");
            this.LastTimeRelativeMSec         = template.LastTimeRelativeMSec.ToString("N3");
            this.InclusiveMetricPercent       = (template.InclusiveMetric * 100 / template.CallTree.PercentageBasis).ToString("N2");
            this.ExclusiveMetricPercent       = (template.ExclusiveMetric * 100 / template.CallTree.PercentageBasis).ToString("N2");
            this.ExclusiveFoldedMetricPercent = (template.ExclusiveFoldedMetric * 100 / template.CallTree.PercentageBasis).ToString("N2");
            this.HasChildren                  = template.HasChildren;
            this.BackingNode                  = template;
            this.backingNodeWithChildren      = template;
        }
Exemple #24
0
        private async Task <string> SignAndCreateJwtAsync(JwtSecurityToken jwt)
        {
            var algorithm = "RS256";//jwt.SignatureAlgorithm;

            var plaintext = $"{jwt.EncodedHeader}.{jwt.EncodedPayload}";

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

            var cryptoClient = new CryptographyClient(
                new Uri("https://cleankey.vault.azure.net/keys/cleankey/82f7ce0323574ab4869565d3bc525793"),
                new DefaultAzureCredential());

            try
            {
                //jwt.SignatureAlgorithm
                var signResult = await cryptoClient.SignAsync(new SignatureAlgorithm(algorithm), hash);

                return($"{plaintext}.{Base64UrlTextEncoder.Encode(signResult.Signature)}");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
        public async Task Invoke(HttpContext ctx)
        {
            if (ctx.User.Identity.IsAuthenticated)
            {
                var cnfJson = ctx.User.FindFirst("cnf")?.Value;
                if (!String.IsNullOrWhiteSpace(cnfJson))
                {
                    var certResult = await ctx.AuthenticateAsync(_options.CertificateSchemeName);

                    if (!certResult.Succeeded)
                    {
                        await ctx.ChallengeAsync(_options.CertificateSchemeName);

                        return;
                    }

                    var certificate = await ctx.Connection.GetClientCertificateAsync();

                    var thumbprint = Base64UrlTextEncoder.Encode(certificate.GetCertHash(HashAlgorithmName.SHA256));

                    var cnf    = JObject.Parse(cnfJson);
                    var sha256 = cnf.Value <string>("x5t#S256");

                    if (String.IsNullOrWhiteSpace(sha256) ||
                        !thumbprint.Equals(sha256, StringComparison.Ordinal))
                    {
                        await ctx.ChallengeAsync(_options.JwtBearerSchemeName);

                        return;
                    }
                }
            }

            await _next(ctx);
        }
        public async Task <IActionResult> SendResetPasswordLink([FromBody] ResetPasswordLinkModel model)
        {
            try
            {
                var resetPasswordToken = await _authenticateService.CreateResetPasswordTokenAsync(model.Email);

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

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

                var response = new Response {
                    Status = 200, Message = "Account password reset link was sent to you email address."
                };
                return(Ok(response));
            }
            catch (InvalidUserException e)
            {
                return(Ok(new Response {
                    Status = 403, Message = e.Message
                }));
            }
            catch
            {
                return(Ok(new Response {
                    Status = 500, Message = "Internal Server Error."
                }));
            }
        }
    public AuthenticationTicket?Unprotect(string?protectedText, string?purpose)
    {
        AuthenticationTicket?authTicket;

        try
        {
            var unprotectedBytes = dataProtector.Unprotect
                                   (
                Base64UrlTextEncoder.Decode(protectedText ?? "")
                                   );
            authTicket = ticketSerializer.Deserialize(unprotectedBytes);
            var embeddedJwt = authTicket?.Properties?.GetTokenValue("Jwt");
            new JwtSecurityTokenHandler().ValidateToken(embeddedJwt, validationParameters, out var token);
            if (!(token is JwtSecurityToken jwt))
            {
                throw new SecurityTokenValidationException("JWT token was found to be invalid");
            }
            if (!jwt.Header.Alg.Equals(Algorithm, StringComparison.Ordinal))
            {
                throw new ArgumentException($"Algorithm must be '{Algorithm}'");
            }
        }
        catch (Exception)
        {
            authTicket = null;
        }
        return(authTicket);
    }
        public async Task <IActionResult> ConfirmEmail([FromBody] ConfirmEmailModel model)
        {
            try
            {
                var dataJsonBytes = Base64UrlTextEncoder.Decode(model.Token);
                var dataJson      = Encoding.UTF8.GetString(dataJsonBytes);
                var data          = JsonConvert.DeserializeObject <Token>(dataJson);

                await _authenticateService.ConfirmEmail(data.Email, data.Hash);

                var response = new Response {
                    Status = 200
                };
                return(Ok(response));
            }
            catch (Exception e) when(e is InvalidUserException || e is InvalidTokenException)
            {
                return(Ok(new Response {
                    Status = 403, Message = e.Message
                }));
            }
            catch
            {
                return(Ok(new Response {
                    Status = 500, Message = "Internal Server Error."
                }));
            }
        }
        private static void GenerateCorrelationId(HttpContext httpContext, OpenIdConnectOptions options, AuthenticationProperties properties)
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            var bytes = new byte[32];

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

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure   = httpContext.Request.IsHttps,
                Expires  = properties.ExpiresUtc
            };

            properties.Items[CorrelationProperty] = correlationId;

            var cookieName = CorrelationPrefix + options.AuthenticationScheme + "." + correlationId;

            httpContext.Response.Cookies.Append(cookieName, CorrelationMarker, cookieOptions);
        }
Exemple #30
0
        public IActionResult Login(string returnUrl = null)
        {
            // Scopes are required for API calls but not for authentication, dummy scope is inserted to workaround an issue in the library
            var scopes = new List <string>()
            {
                "esi-location.read_location.v1",
                "esi-industry.read_character_mining.v1"
            };

            string state;

            if (!String.IsNullOrEmpty(returnUrl))
            {
                state = Base64UrlTextEncoder.Encode(Encoding.ASCII.GetBytes(returnUrl));
            }
            else
            {
                state = Guid.NewGuid().ToString();
            }

            HttpContext.Session.SetString(SSOStateKey, state);

            var authorization = esiClient.SSO.AuthorizeToEVEUri(scopes, state);

            return(Redirect(authorization.SignInURI));
        }