Esempio n. 1
0
        public static string Sign(WebSecureToken token, SecurityMode mode, string secretKey)
        {
            byte[] bSecretKey = Encoding.ASCII.GetBytes(secretKey);
            string encoded    = string.Empty;

            switch (mode)
            {
            case SecurityMode.Sign:
                var tokenHandler = new JwtSecurityTokenHandler();

                var jwtoken = tokenHandler.CreateJwtSecurityToken(issuer: token.Issuer, audience: null,
                                                                  subject: new ClaimsIdentity(new[] {
                    new Claim(WebSecureToken.GXISSUER, token.Issuer),
                    new Claim(WebSecureToken.GXPROGRAM, token.ProgramName),
                    new Claim(WebSecureToken.GXVALUE, token.Value),
                    new Claim(WebSecureToken.GXEXPIRATION, token.Expiration.Subtract(new DateTime(1970, 1, 1)).TotalSeconds.ToString())
                }),
                                                                  notBefore: DateTime.UtcNow,
                                                                  expires: token.Expiration,
                                                                  signingCredentials: new SigningCredentials(new SymmetricSecurityKey(bSecretKey), SecurityAlgorithms.HmacSha256));

                return(tokenHandler.WriteToken(jwtoken));
            }
            return(encoded);
        }
Esempio n. 2
0
        public static bool Verify(string pgmName, string issuer, string value, string jwtToken, out WebSecureToken token, IGxContext context)
        {
            token = new WebSecureToken();
            bool jwtVerifyOk     = SecureTokenHelper.Verify(jwtToken, token, GetSecretKey(context));
            bool contentVerifyOk = jwtVerifyOk && !string.IsNullOrEmpty(pgmName) && token.ProgramName == pgmName && issuer == token.Issuer &&
                                   StripInvalidChars(token.Value) == StripInvalidChars(value) && token.Expiration >= DateTime.Now;

            if (!contentVerifyOk && _log.IsErrorEnabled)
            {
                StringBuilder errMessage = new StringBuilder("WebSecurity Token Verification error");
                if (!jwtVerifyOk)
                {
                    errMessage.Append($" - JWT Signature Verification failed");
                }
                if (token.ProgramName != pgmName)
                {
                    errMessage.Append($" - ProgramName mismatch '{token.ProgramName}' <> '{pgmName}'");
                }
                if (StripInvalidChars(token.Value) != StripInvalidChars(value))
                {
                    errMessage.Append($" - Value mismatch '{StripInvalidChars(token.Value)}' <> '{StripInvalidChars(value)}'");
                }
                else if (issuer != token.Issuer)
                {
                    errMessage.Append($" - Issuer mismatch '{token.Issuer}' <> '{issuer}'");
                }

                if (token.Expiration < DateTime.Now)
                {
                    errMessage.Append(" - Token expired ");
                }
                GXLogging.Error(_log, errMessage.ToString());
            }
            return(contentVerifyOk);
        }
Esempio n. 3
0
        internal static WebSecureToken getWebSecureToken(string signedToken, string secretKey)
        {
            byte[] bSecretKey = Encoding.ASCII.GetBytes(secretKey);
            if (string.IsNullOrEmpty(signedToken))
            {
                return(null);
            }

            using (var hmac = new System.Security.Cryptography.HMACSHA256(bSecretKey))
            {
                var handler = new JwtSecurityTokenHandler();
                var validationParameters = new TokenValidationParameters
                {
                    ClockSkew        = TimeSpan.FromMinutes(1),
                    ValidateAudience = false,
                    ValidateIssuer   = false,
                    IssuerSigningKey = new SymmetricSecurityKey(hmac.Key),
                };
                SecurityToken  securityToken;
                WebSecureToken outToken = new WebSecureToken();
                var            claims   = handler.ValidateToken(signedToken, validationParameters, out securityToken);
                outToken.Value = claims.Identities.First().Claims.First(c => c.Type == WebSecureToken.GXVALUE).Value;
                return(outToken);
            }
        }
Esempio n. 4
0
        public static bool Verify(string pgmName, string issuer, string value, string jwtToken, out WebSecureToken token, IGxContext context)
        {
            token = new WebSecureToken();
            bool ok  = SecureTokenHelper.Verify(jwtToken, token, GetSecretKey(context));
            bool ret = ok && !string.IsNullOrEmpty(pgmName) && token.ProgramName == pgmName && issuer == token.Issuer &&
                       StripInvalidChars(token.Value) == StripInvalidChars(value) && token.Expiration >= DateTime.Now;

            if (!ret)
            {
                if (!ok)
                {
                    GXLogging.Error(_log, "verify: Invalid token");
                }
                if (token.ProgramName != pgmName)
                {
                    GXLogging.Error(_log, "verify: pgmName mismatch " + "'" + token.ProgramName + "' <> '" + pgmName + "'");
                }
                if (issuer != token.Issuer)
                {
                    GXLogging.Error(_log, "verify: issuer mismatch " + "'" + token.Issuer + "' <> '" + issuer + "'");
                }
                if (StripInvalidChars(token.Value) != StripInvalidChars(value))
                {
                    GXLogging.Error(_log, "verify: value mismatch " + "'" + token.Value + "'" + " <> '" + value + "'");
                }
                if (token.Expiration < DateTime.Now)
                {
                    GXLogging.Error(_log, "verify: token expired ");
                }
            }
            return(ret);
        }
Esempio n. 5
0
        internal static bool VerifySecureSignedSDTToken(string cmpCtx, GxUserType value, string signedToken, IGxContext context)
        {
            WebSecureToken Token = SecureTokenHelper.getWebSecureToken(signedToken, GetSecretKey(context));

            if (Token == null)
            {
                return(false);
            }
            GxUserType PayloadObject = (GxUserType)value.Clone();

            PayloadObject.FromJSonString(Token.Value);
            return(GxUserType.IsEqual(value, PayloadObject));
        }
Esempio n. 6
0
 public override bool FromJSonString(string s)
 {
     try {
         WebSecureToken wt = JSONHelper.Deserialize <WebSecureToken>(s, Encoding.UTF8);
         this.Expiration  = wt.Expiration;
         this.Value       = wt.Value;
         this.ProgramName = wt.ProgramName;
         this.Issuer      = wt.Issuer;
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Esempio n. 7
0
        internal static bool Verify(string jwtToken, WebSecureToken outToken, string secretKey)
        {
            bool ok = false;

            byte[] bSecretKey = Encoding.ASCII.GetBytes(secretKey);
            if (!string.IsNullOrEmpty(jwtToken))
            {
                try
                {
                    using (var hmac = new System.Security.Cryptography.HMACSHA256(bSecretKey))
                    {
                        var handler = new JwtSecurityTokenHandler();
                        var validationParameters = new TokenValidationParameters
                        {
                            ClockSkew        = TimeSpan.FromMinutes(1),
                            ValidateAudience = false,
                            ValidateIssuer   = false,
                            IssuerSigningKey = new SymmetricSecurityKey(hmac.Key),
                        };
                        //Avoid handler.ValidateToken which does not work in medium trust environment
                        JwtSecurityToken jwtSecurityToken = (JwtSecurityToken)handler.GetType().InvokeMember("ValidateSignature",
                                                                                                             System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod, null, handler,
                                                                                                             new object[] { jwtToken, validationParameters });
                        Validators.ValidateIssuerSecurityKey(jwtSecurityToken.SigningKey, jwtSecurityToken, validationParameters);

                        outToken.Expiration  = new DateTime(1970, 1, 1).AddSeconds(Double.Parse(jwtSecurityToken.Claims.First(c => c.Type == WebSecureToken.GXEXPIRATION).Value));
                        outToken.ProgramName = jwtSecurityToken.Claims.First(c => c.Type == WebSecureToken.GXPROGRAM).Value;
                        outToken.Issuer      = jwtSecurityToken.Claims.First(c => c.Type == WebSecureToken.GXISSUER).Value;
                        outToken.Value       = jwtSecurityToken.Claims.First(c => c.Type == WebSecureToken.GXVALUE).Value;
                        ok = true;
                    }
                }
                catch (Exception e)
                {
                    GXLogging.Error(_log, string.Format("Web Token verify failed for Token '{0}'", jwtToken), e);
                }
            }
            return(ok);
        }