Beispiel #1
0
        /// <summary>
        /// Verify a JWT token signed in RS256 (RSA + SHA-256)
        /// </summary>
        /// <param name="tokenJwtEncoded"></param>
        /// <returns></returns>
        private static bool VerifyTokenJwtSignatureInternal(string tokenJwtEncoded, string modulusEncoded, string exponentEncoded)
        {
            var urlTextEncoder = new Base64UrlTextEncoder();

            string[] tokenParts = tokenJwtEncoded.Split('.');

            var rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(
                new RSAParameters
            {
                Modulus  = urlTextEncoder.Decode(modulusEncoded),
                Exponent = urlTextEncoder.Decode(exponentEncoded)
            });

            byte[] hash;
            using (var sha256 = SHA256.Create())
            {
                hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(tokenParts[0] + '.' + tokenParts[1]));
            }

            var rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);

            rsaDeformatter.SetHashAlgorithm("SHA256");

            var signatureVerified = rsaDeformatter.VerifySignature(hash, urlTextEncoder.Decode(tokenParts[2]));

            return(signatureVerified);
        }
Beispiel #2
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);
            }
        }
    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);
    }
Beispiel #4
0
        public async Task <IActionResult> Callback(string code, string state)
        {
            // BIG NO-NO BELOW, COMMENTED OUT CODE BECAUSE THE SESSION WAS CHANGING BETWEEN AUTHORIZATION!
            var authorization = new Authorization
            {
                AuthorizationCode = code,
                ExpectedState     = state, //HttpContext.Session.GetString(SSOStateKey),
                ReturnedState     = state
            };

            var accessToken = await _ESIClient.SSO.VerifyAuthorizationAsync(authorization);

            var character = await _ESIClient.SSO.GetCharacterDetailsAsync(accessToken.AccessToken);

            await SignInAsync(accessToken, character);

            if (Guid.TryParse(state, out Guid stateGuid))
            {
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                var returnUrl = Encoding.ASCII.GetString(Base64UrlTextEncoder.Decode(state));
                return(Redirect(returnUrl));
            }
        }
        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);
        }
Beispiel #6
0
        public AuthenticationTicket Unprotect(string protectedText)
        {
            try
            {
                if (protectedText == null)
                {
                    return(default(AuthenticationTicket));
                }

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


                var userData = rsa.Decrypt(protectedData);
                if (userData == null)
                {
                    return(default(AuthenticationTicket));
                }
                var v1 = _serializer.Deserialize(userData);
                var v2 = v1.Properties.ExpiresUtc;
                return(v1);
            }
            catch
            {
                // TODO trace exception, but do not leak other information
                return(default(AuthenticationTicket));
            }
        }
Beispiel #7
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> 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."
                }));
            }
        }
Beispiel #9
0
        public string Base64UrlDecodeAndDecompressToUnicode(string content)
        {
            var bytes   = Base64UrlTextEncoder.Decode(content);
            var decoded = DecompressToUnicode(bytes);

            return(decoded);
        }
Beispiel #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"));
        }
Beispiel #11
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 static void ConfigureAuthentication(this IServiceCollection services, ServiceProvider provider)
        {
            var principalOptions = provider.GetService <IOptions <PrincipalConfiguration> >();
            var hostingOptions   = provider.GetService <IOptions <HostingConfiguration> >();


            // disable claim mapping
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

            var key         = Base64UrlTextEncoder.Decode(principalOptions.Value.AudienceSecret);
            var securityKey = new SymmetricSecurityKey(key);

            var validationParameters = new TokenValidationParameters
            {
                NameClaimType            = TokenConstants.Claims.Name,
                RoleClaimType            = TokenConstants.Claims.Role,
                ValidIssuer              = hostingOptions.Value.ClientDomain,
                ValidAudience            = principalOptions.Value.AudienceId,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = securityKey,
            };


            services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = validationParameters;
                options.SaveToken            = true;
                options.RequireHttpsMetadata = true;
            });
        }
Beispiel #13
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));
            }
        }
Beispiel #14
0
        public async Task <IActionResult> Callback(string code, string state)
        {
            var authorization = new Authorization
            {
                AuthorizationCode = code,
                ExpectedState     = HttpContext.Session.GetString(SSOStateKey),
                ReturnedState     = state
            };

            var accessToken = await esiClient.SSO.VerifyAuthorizationAsync(authorization);

            var character = await esiClient.SSO.GetCharacterDetailsAsync(accessToken.AccessToken);

            await SignInAsync(accessToken, character);

            if (Guid.TryParse(state, out Guid stateGuid))
            {
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                var returnUrl = Encoding.ASCII.GetString(Base64UrlTextEncoder.Decode(state));
                return(Redirect(returnUrl));
            }
        }
        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"]));
        }
Beispiel #16
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="str"></param>
        /// <param name="cursor"></param>
        /// <returns></returns>
        public static bool TryParse(string str, out NavigationCursor cursor)
        {
            if (null == str)
            {
                throw new ArgumentNullException(nameof(str));
            }

            if (0 < str.Length)
            {
                var stream = new MemoryStream(Base64UrlTextEncoder.Decode(str));

                if (TryRead(stream, out var dir, out var id, out var count))
                {
                    var direction = Enum.ToObject(typeof(NavigationCursorDirection), dir);

                    cursor = new NavigationCursor((NavigationCursorDirection)direction, id, count);

                    return(true);
                }
            }

            cursor = null;

            return(false);
        }
Beispiel #17
0
        public async Task <IActionResult> Callback(string code, string state)
        {
            var authorization = new Authorization {
                AuthorizationCode = code,
                ExpectedState     = HttpContext.Session.GetString(SSOStateKey),
                ReturnedState     = state
            };

            var accessToken = await esiClient.SSO.VerifyAuthorizationAsync(authorization);

            var character = await esiClient.SSO.GetCharacterDetailsAsync(accessToken.AccessToken);

            var dbUser = DataAccess.User.SelectUser(character.CharacterId);

            //The user does not exist in the db
            if (dbUser == null)
            {
                dbUser = new Models.Database.User {
                    CharacterId            = character.CharacterId,
                    CharacterName          = character.CharacterName,
                    AccessToken            = accessToken.AccessToken,
                    RefreshToken           = accessToken.RefreshToken,
                    RefreshTokenExpiresUTC = accessToken.ExpiresUtc,
                    APIToken = Guid.NewGuid().ToString()
                };

                DataAccess.User.InsertUser(dbUser);
            }
            else
            {
                dbUser.AccessToken            = accessToken.AccessToken;
                dbUser.RefreshToken           = accessToken.RefreshToken;
                dbUser.RefreshTokenExpiresUTC = accessToken.ExpiresUtc;
                if (dbUser.APIToken == null)
                {
                    dbUser.APIToken = Guid.NewGuid().ToString();
                }

                dbUser.CharacterName = character.CharacterName;
                DataAccess.User.UpdateUser(dbUser);
            }

            Response.Cookies.Append("APIToken", dbUser.APIToken,
                                    new CookieOptions {
                Expires = DateTimeOffset.Now.AddDays(7)
            });

            await SignInAsync(accessToken, character);

            if (Guid.TryParse(state, out Guid stateGuid))
            {
                return(Redirect("http://localhost"));
            }
            else
            {
                var returnUrl = Encoding.ASCII.GetString(Base64UrlTextEncoder.Decode(state));
                return(Redirect(returnUrl));
            }
        }
Beispiel #18
0
 public AuthService(IConfiguration configuration, IRoleRepository roleRepository)
 {
     this.roleRepository = roleRepository;
     byte[] base64DecodedSecretBytes =
         Base64UrlTextEncoder.Decode(configuration.GetValue <string>("Secret"));
     this.key = new SymmetricSecurityKey(base64DecodedSecretBytes);
     this.bearerTokenHandler = new JwtSecurityTokenHandler();
 }
 public static string FromBase64UrlEncoded(this string s)
 {
     if (s == null)
     {
         return(null);
     }
     return(Encoding.UTF8.GetString(Base64UrlTextEncoder.Decode(s)));
 }
        public async Task <IActionResult> Index()
        {
            foreach (var scheme in await _schemes.GetRequestHandlerSchemesAsync())
            {
                var handler1 = await _handlers.GetHandlerAsync(HttpContext, scheme.Name) as IAuthenticationRequestHandler;

                if (handler1 != null && await handler1.HandleRequestAsync())
                {
                    return(View());
                }
            }
            var target = ResolveTarget(_options.CurrentValue.ForwardAuthenticate);

            var defaultAuthenticate = await _schemes.GetDefaultAuthenticateSchemeAsync();

            if (defaultAuthenticate != null)
            {
                var result = await HttpContext.AuthenticateAsync(defaultAuthenticate.Name);

                if (result?.Principal != null)
                {
                    HttpContext.User = result.Principal;
                }
            }

            string cookieValue = HttpContext.Request.Cookies[".Aspnetcore.Identity.Application"];

            var provider = _options.CurrentValue.DataProtectionProvider;
            //Get a data protector to use with either approach
            IDataProtector dataProtector = provider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "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);
            //CookieAuthenticationHandler a;
            //a.AuthenticateAsync()
            //var result = (await handler.AuthenticateAsync()) ?? AuthenticateResult.NoResult();
            //if (!result.Succeeded)
            //{
            //    return View();
            //}
            //var options = _options.CurrentValue;
            //var cookie = options.CookieManager.GetRequestCookie(HttpContext, options.Cookie.Name!);
            var b = await ReadCookieTicket();

            //var a = options.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding());
            return(View());
        }
        private bool ValidateSignature()
        {
            _logger.LogTrace("Validating signature of message");
            var message  = Request.Form["client"] + Request.Form["server"];
            var ids      = Base64UrlTextEncoder.Decode(Request.Form["ids"]);
            var idk      = Base64UrlTextEncoder.Decode(GetClientParams()["idk"]);
            var verified = Ed25519.Verify(ids, Encoding.ASCII.GetBytes(message), idk);

            _logger.LogTrace("Message signature is: {0}", verified);
            return(verified);
        }
Beispiel #22
0
        public static string DecodeToken(string encodedToken)
        {
            if (string.IsNullOrEmpty(encodedToken))
            {
                return(null);
            }
            // get byte[]
            var tokenBytes = Base64UrlTextEncoder.Decode(encodedToken);

            // to string
            return(System.Text.Encoding.UTF8.GetString(tokenBytes));
        }
Beispiel #23
0
        public static T RawBase64Deserialize <T>(this string raw)
        {
            byte[]       bytes  = Base64UrlTextEncoder.Decode(raw);
            MemoryStream binary = new MemoryStream(bytes);

            try {
                return((T)(new BinaryFormatter().Deserialize(binary)));
            } catch (InvalidCastException) {
                //log exception
                return(default(T));
            }
        }
        public async ValueTask <ActionResult> CallersChildren(string name, string path)
        {
            name = Encoding.UTF8.GetString(Base64UrlTextEncoder.Decode(name));

            var model = new CallersViewStackViewerViewModel(this.HttpContext)
            {
                TreeNodes = await this.controller.CallerTree(name, path)
            };

            this.ViewBag.Title = "Callers Viewer";
            return(this.View(model));
        }
Beispiel #25
0
        private static JwtPayload ParsePayload(string token)
        {
            var jwtSegments = token.Split(".");

            if (jwtSegments.Length != 3)
            {
                return(null);
            }
            var payload = jwtSegments[1];

            return(JsonConvert.DeserializeObject <JwtPayload>(
                       Encoding.UTF8.GetString(Base64UrlTextEncoder.Decode(payload))));
        }
Beispiel #26
0
    public string Decrypt(HttpContext context, string cookie)
    {
        IDataProtectionProvider dataProtectionProvider = _storedOption.DataProtectionProvider;
        IDataProtector          protector = dataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "v2");
        string purpose = GetTlsTokenBinding(context);

        if (!string.IsNullOrEmpty(purpose))
        {
            protector = protector.CreateProtector(purpose);
        }
        var protectedData = Base64UrlTextEncoder.Decode(cookie);

        byte[] userData = protector.Unprotect(protectedData);
        var    rawText  = Encoding.UTF8.GetString(userData);

        return(rawText);
    }
Beispiel #27
0
        public bool ValidateCircuitId(string circuitId)
        {
            try
            {
                var protectedBytes = Base64UrlTextEncoder.Decode(circuitId);
                _protector.Unprotect(protectedBytes);

                // Its enough that we prove that we can unprotect the payload to validate the circuit id,
                // as this demonstrates that it the id wasn't tampered with.
                return(true);
            }
            catch (Exception)
            {
                // The payload format is not correct (either not base64urlencoded or not data protected)
                return(false);
            }
        }
Beispiel #28
0
 private void HandleFiles(Form_submission s, Form form)
 {
     foreach (var qa in s.Answers.SelectMany(a => a.QuestionAnswers).Where(x => x.Files != null && x.Files.Count > 0).ToList())
     {
         foreach (var file in qa.Files)
         {
             var destFolder = Path.Combine(hostingEnvironment.WebRootPath, "files", GetUser()?.id.ToString());
             if (!Directory.Exists(destFolder))
             {
                 Directory.CreateDirectory(destFolder);
             }
             var destPath = Path.Combine(destFolder, file.filename);
             var data     = Base64UrlTextEncoder.Decode(file.data.Substring(28));
             System.IO.File.WriteAllBytes(destPath, data);
         }
     }
 }
Beispiel #29
0
        /// <summary>VerifyJwtBearerTokenFlowAssertion</summary>
        /// <param name="jwtAssertion">string</param>
        /// <param name="iss">client_id</param>
        /// <param name="aud">Token2 EndPointのuri</param>
        /// <param name="scopes">scopes</param>
        /// <param name="jobj">JObject</param>
        /// <param name="xmlPublicKey">RS256用のXML公開鍵</param>
        /// <returns>検証結果</returns>
        public static bool VerifyJwtBearerTokenFlowAssertion(string jwtAssertion,
                                                             out string iss, out string aud, out string scopes, out JObject jobj, string xmlPublicKey)
        {
            iss    = "";
            aud    = "";
            scopes = "";
            jobj   = null;

            JWT_RS256_XML jwtRS256 = new JWT_RS256_XML(xmlPublicKey);

            if (jwtRS256.Verify(jwtAssertion))
            {
                Base64UrlTextEncoder base64UrlEncoder = new Base64UrlTextEncoder();
                string jwtPayload = Encoding.UTF8.GetString(base64UrlEncoder.Decode(jwtAssertion.Split('.')[1]));
                jobj = ((JObject)JsonConvert.DeserializeObject(jwtPayload));

                iss = (string)jobj["iss"];
                aud = (string)jobj["aud"];
                //string iat = (string)jobj["iat"];
                scopes = (string)jobj["scope"];

                long unixTimeSeconds = 0;
#if NET45
                unixTimeSeconds = PubCmnFunction.ToUnixTime(DateTimeOffset.Now);
#else
                unixTimeSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();
#endif
                string exp = (string)jobj["exp"];
                if (long.Parse(exp) >= unixTimeSeconds)
                {
                    return(true);
                }
                else
                {
                    // JWTの内容検証に失敗
                }
            }
            else
            {
                // JWTの署名検証に失敗
            }

            // 認証に失敗
            return(false);
        }
        private void LogFbaCookie(HttpContext Context, Guid CorrelationId)
        {
            if (_cookieAuthenticationOptions == null)
            {
                return;
            }
            // See https://stackoverflow.com/questions/42842511/how-to-manually-decrypt-an-asp-net-core-authentication-cookie
            // Retrieve encrypted HTTP cookie.
            var cookieName      = $".AspNetCore.{CookieAuthenticationDefaults.AuthenticationScheme}";
            var encryptedCookie = _cookieAuthenticationOptions.CurrentValue.CookieManager.GetRequestCookie(Context, cookieName);

            if (!encryptedCookie.IsNullOrEmpty())
            {
                var encryptedCookieBytes = Base64UrlTextEncoder.Decode(encryptedCookie);
                // Decrypt cookie and remove control characters.
                var dataProtector = _cookieAuthenticationOptions.CurrentValue.DataProtectionProvider.CreateProtector
                                        ("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", CookieAuthenticationDefaults.AuthenticationScheme, "v2");
                string cookie;
                try
                {
                    var cookieBytes = dataProtector.Unprotect(encryptedCookieBytes);
                    cookie = Encoding.UTF8.GetString(cookieBytes).RemoveControlCharacters();
                }
                catch (CryptographicException exception)
                {
                    // Cookie is signed by expired key.  This may occur if data protection is not configured in web server startup.
                    // Without data protection configured to persist keys, the web server creates a new key every time it recycles the application pool.
                    // See https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-2.2
                    cookie = $"Failed to decrypt FBA cookie.  {exception.GetSummary(true, true)}";
                }
                _logger.Log(CorrelationId, $"FBA Cookie = {cookie}");

                // The above cookie string approximates the data passed from the user's web browser to this web server.
                // It's an approximation because it was created by a binary serializer that converted an AuthenticationTicket class to a byte array.
                // See https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.authentication.ticketserializer.serialize?view=aspnetcore-2.2.

                // To reconstruct the AuthenticationTicket, do the following:
                //   TicketDataFormat ticketDataFormat = new TicketDataFormat(dataProtector);
                //   AuthenticationTicket authenticationTicket = ticketDataFormat.Unprotect(encryptedCookie);
                // Note that attempting to serialize AuthenticationTicket to JSON (to write to a log file or database) using Newtonsoft Json.NET causes a
                //   "PlatformNotSupportedException: This instance contains state that cannot be serialized and deserialized on this platform" error.
                //   This error occurs even with PreserveReferencesHandling.All and IgnoreSerializableInterface.
                // See https://github.com/JamesNK/Newtonsoft.Json/issues/1713.
            }
        }