Ejemplo n.º 1
0
        private string RefreshToken(UserLogin userAccount, User userDetails)
        {
            var        refreshId = DateTime.Now.Ticks; // To verify freshness of issued Token.
            JwtPayload payload   = new JwtPayload();

            payload.Add("isAdmin", userAccount.IsAdmin);
            payload.Add("userLoginId", userAccount.Id);
            payload.Add("displayName", userDetails.FirstName + " " + userDetails.LastName);
            payload.Add("refreshId", refreshId);

            var token = JwtTokenHelper.GenerateJwtToken(userAccount.Login,
                                                        userDetails.Role.Name, payload);

            userAccount.AccessFailedCount = 0;
            userAccount.LockoutEnabled    = false;
            userAccount.LockoutEnd        = DateTime.Parse("1/1/1900");
            userAccount.RefreshId         = refreshId;
            userAccount.LastModifiedBy    = "SECURITY";
            userAccount.LastModified      = DateTime.Now;
            db.Entry(userAccount).State   = EntityState.Modified;
            try
            {
                db.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(token);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Generates a JWT.
        /// NOTE:  THIS METHOD DOES NOT AUTHENTICATE USER CREDENTIALS.
        /// Any user authentication must be done prior to calling this method.
        ///
        /// The expiration time is expressed as a unix/posix integer in UTC.
        /// </summary>
        /// <param name="userId">The user's ID</param>
        /// <param name="tzOffset">The user's timezone offset from UTC in minutes</param>
        /// <param name="expMinutes">
        ///     An optional specification of how long the token is valid (in seconds).
        ///     Must be positive to be considered.
        /// </param>
        /// <param name="assesmentId">Optionally brands the new token with an assessment ID in the payload</param>
        /// <returns></returns>
        public static string GenerateToken(int userId, string tzOffset, int expSeconds, int?assessmentId, int?aggregationId, string scope)
        {
            // Build securityKey.  For uniqueness, append the user identity (userId)
            var securityKey = new Microsoft
                              .IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(GetSecret() + userId));

            // Build credentials
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
                                  (securityKey, SecurityAlgorithms.HmacSha256Signature);

            //  Finally create a Token
            var header = new JwtHeader(credentials);

            // Determine the expiration (server time) of the token
            int    jwtExpiryMinutes = 60;
            string expMinutesConfig = ConfigurationManager.AppSettings["JWT Expiry Minutes"];

            if (expMinutesConfig != null)
            {
                int.TryParse(expMinutesConfig, out jwtExpiryMinutes);
            }

            int secondsUntilExpiry = (jwtExpiryMinutes * 60);

            // If a non-zero expSeconds was provided, override the expiration
            if (expSeconds > 0)
            {
                secondsUntilExpiry = expSeconds;
            }

            var payload = new JwtPayload
            {
                { "aud", "CSET_AUD" },
                { "iss", "CSET_ISS" },
                { "exp", Utilities.UnixTime() + secondsUntilExpiry },
                { Constants.Token_UserId, userId },
                { Constants.Token_TimezoneOffsetKey, tzOffset },
                { "scope", scope }
            };



            // Include the current AssessmentId if one was provided
            if (assessmentId != null)
            {
                payload.Add(Constants.Token_AssessmentId, assessmentId);
            }

            // Include the current AggregationId if one was provided
            if (aggregationId != null)
            {
                payload.Add(Constants.Token_AggregationId, aggregationId);
            }

            // Build the token
            var secToken = new JwtSecurityToken(header, payload);
            var handler  = new JwtSecurityTokenHandler();

            return(handler.WriteToken(secToken));
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            JwtPayload payload = new JwtPayload();

            Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
            payload.Add("aud", "https://iam.api.cloud.yandex.net/iam/v1/tokens");
            payload.Add("iss", "%iss%");
            payload.Add("iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
            payload.Add("exp", DateTimeOffset.UtcNow.ToUnixTimeSeconds() + 3600);

            var       reader = File.OpenText("C:\\Users\\User\\source\\repos\\ConsoleApp1\\ConsoleApp1\\private.key");
            PemReader pRd    = new PemReader(reader);
            RsaPrivateCrtKeyParameters pKey = (RsaPrivateCrtKeyParameters)pRd.ReadObject();

            pRd.Reader.Close();

            var rsa = RSA.Create();

            rsa.ImportParameters(DotNetUtilities.ToRSAParameters(pKey));

            IDictionary <string, object> dict = new Dictionary <string, object>();

            dict.Add("kid", "%kid%");
            dict.Add("typ", "JWT");

            string token = Jose.JWT.Encode(payload.SerializeToJson(), rsa, JwsAlgorithm.PS256, dict);

            Console.WriteLine(token);
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            var serviceAccountId = "%serviceAccountId%";
            var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();

            JwtPayload payload = new JwtPayload();

            Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
            payload.Add("aud", "https://iam.api.cloud.yandex.net/iam/v1/tokens");
            payload.Add("iss", serviceAccountId);
            payload.Add("iat", now);
            payload.Add("exp", now + 3600);

            var       reader = File.OpenText("./private.key");
            PemReader pRd    = new PemReader(reader);
            RsaPrivateCrtKeyParameters pKey = (RsaPrivateCrtKeyParameters)pRd.ReadObject();

            pRd.Reader.Close();

            var RSAOpenSsl = new RSAOpenSsl(ToRSAParameters(pKey));

            IDictionary <string, object> dict = new Dictionary <string, object>();

            dict.Add("kid", "ajerfj2gvc0rf20si9ot");
            dict.Add("typ", "JWT");

            string token = Jose.JWT.Encode(payload.SerializeToJson(), RSAOpenSsl, JwsAlgorithm.PS256, dict);

            Console.WriteLine(token);
        }
Ejemplo n.º 5
0
        public TokenModel GenerateToken(string email)
        {
            var dateTimeNow     = ((DateTimeOffset)DateTime.Now).ToUnixTimeSeconds();
            var expiresDateTime = DateTime.Now.AddDays(100);
            var payload         = new JwtPayload
            {
                { "sub", email },
                { "email", email },
                { "iat", dateTimeNow },
                { "nbf", dateTimeNow },
                { "exp", ((DateTimeOffset)expiresDateTime).ToUnixTimeSeconds() }
            };

            if (_securitySettings.Audience != null)
            {
                payload.Add("aud", _securitySettings.Audience);
            }

            if (_securitySettings.Issuer != null)
            {
                payload.Add("iss", _securitySettings.Issuer);
            }

            var securityService = GetSecurityService(_securitySettings.SecurityType);

            var token = securityService.GenerateToken(payload);

            return(new TokenModel {
                Token = token, ExpiredAt = expiresDateTime
            });
        }
Ejemplo n.º 6
0
        // We need to handle json objects ourself as this isn't directly supported by JwtSecurityHandler yet
        private static JwtPayload AddJsonToPayload(JwtPayload payload, IEnumerable <Claim> jsonClaims)
        {
            var jsonTokens = jsonClaims.Select(x => new { x.Type, JsonValue = JRaw.Parse(x.Value) }).ToArray();

            var jsonObjects      = jsonTokens.Where(x => x.JsonValue.Type == JTokenType.Object).ToArray();
            var jsonObjectGroups = jsonObjects.GroupBy(x => x.Type).ToArray();

            foreach (var group in jsonObjectGroups)
            {
                if (payload.ContainsKey(group.Key))
                {
                    throw new IncompatibleClaimTypesException(string.Format("Can't add two claims where one is a JSON object and the other is not a JSON object ({0})", group.Key));
                }

                if (group.Skip(1).Any())
                {
                    // add as array
                    payload.Add(group.Key, group.Select(x => x.JsonValue).ToArray());
                }
                else
                {
                    // add just one
                    payload.Add(group.Key, group.First().JsonValue);
                }
            }

            var jsonArrays      = jsonTokens.Where(x => x.JsonValue.Type == JTokenType.Array).ToArray();
            var jsonArrayGroups = jsonArrays.GroupBy(x => x.Type).ToArray();

            foreach (var group in jsonArrayGroups)
            {
                if (payload.ContainsKey(group.Key))
                {
                    throw new IncompatibleClaimTypesException(string.Format("Can't add two claims where one is a JSON array and the other is not a JSON array ({0})", group.Key));
                }

                var newArr = new List <JToken>();
                foreach (var arrays in group)
                {
                    var arr = (JArray)arrays.JsonValue;
                    newArr.AddRange(arr);
                }

                // add just one array for the group/key/claim type
                payload.Add(group.Key, newArr.ToArray());
            }

            var unsupportedJsonTokens     = jsonTokens.Except(jsonObjects).Except(jsonArrays);
            var unsupportedJsonClaimTypes = unsupportedJsonTokens.Select(x => x.Type).Distinct();

            if (unsupportedJsonClaimTypes.Any())
            {
                var unsupportedClaimTypes = unsupportedJsonClaimTypes.Aggregate((x, y) => x + ", " + y);
                throw new UnsupportedJsonClaimTypeException($"Unsupported JSON type for claim types: {unsupportedClaimTypes}");
            }

            return(payload);
        }
        private string GenerateJwtToken(User user, string role)
        {
            var expires = !string.IsNullOrWhiteSpace(role) ? DateTime.UtcNow.AddMinutes(90) : DateTime.UtcNow.AddMinutes(40320);

            var payload = new JwtPayload {
                { "sub", user.Id.ToString() },
                { "jti", Guid.NewGuid().ToString() },
                { "id", user.Id.ToString() },
                { "exp", (int)expires.Subtract(new DateTime(1970, 1, 1)).TotalSeconds }
            };

            payload.Add(ClaimTypes.Role, role);

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.JwtKey()));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(new JwtHeader(creds), payload);

            var stringToken = new JwtSecurityTokenHandler().WriteToken(token);

#if !DEBUG
            _jwtRepository.Add(stringToken, user.Id);
#endif

            return(stringToken);
        }
Ejemplo n.º 8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        public static string GenerateToken(object obj, string secretKey)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.Default.GetBytes(secretKey));

            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var header = new JwtHeader(signingCredentials);

            //DateTime centuryBegin = new DateTime(1970, 1, 1);
            //var exp = new TimeSpan(DateTime.Now.AddSeconds(30).Ticks - centuryBegin.Ticks).TotalSeconds;

            var payload = new JwtPayload("", "", new List <Claim>(), null, new DateTime(DateTime.Now.Ticks + TimeSpan.FromMinutes(500).Ticks));


            var properties = obj.GetType().GetProperties();

            foreach (var prop in properties)
            {
                payload.Add(prop.Name, prop.GetValue(obj));
            }

            var secToken = new JwtSecurityToken(header, payload);

            var handler     = new JwtSecurityTokenHandler();
            var tokenString = handler.WriteToken(secToken);

            return(tokenString);
        }
Ejemplo n.º 9
0
        public static Token CreateToken(UserOutputDto userOutput)
        {
            var header  = new JwtHeader(new SigningCredentials(SecretKey, SecurityAlgorithms.HmacSha256));
            var payload = new JwtPayload(
                Jwt.Issuer,
                Jwt.Audience,
                userOutput.Roles.Select(role => new Claim(ClaimTypes.Role, role)),
                DateTime.UtcNow,
                DateTime.UtcNow + Jwt.TokenLifetime
                );
            var dict = DictionaryHelper.ToDictionary(userOutput);

            foreach (var(key, value) in dict)
            {
                payload.Add(key, value);
            }

            var token = new JwtSecurityToken(header, payload);

            var refreshToken = Guid.NewGuid().ToString().Replace("-", "") + "." + userOutput.Id;
            var accessToken  = new Token
            {
                AccessToken  = Handler.WriteToken(token),
                Type         = "bearer",
                RefreshToken = refreshToken,
                Expires      = token.ValidTo
            };

            return(accessToken);
        }
Ejemplo n.º 10
0
        private JwtPayload CreateJwtPayload(string subject,
                                            params KinJwtPayload[] kinJwtPayloads)
        {
            DateTime currentTime = DateTime.UtcNow;

            List <Claim> claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, subject)
            };

            JwtPayload payload = new JwtPayload(
                _kinApplicationId,
                null,
                claims,
                null,
                currentTime.AddHours(6),
                currentTime);

            foreach (KinJwtPayload kinJwtPayload in kinJwtPayloads)
            {
                payload.Add(kinJwtPayload.Name, kinJwtPayload.Data);
            }

            return(payload);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Generates a token
        /// </summary>
        /// <returns>A signed JSON Web Token that can be validated on requests</returns>
        public virtual JsonWebToken Create(TIdentity identity)
        {
            var dict = _payloadFactory.Create(identity);

            var now = DateTimeOffset.Now;

            var payload = new JwtPayload(
                _options.Issuer,
                _options.Audience,
                new List <Claim>(),
                now.UtcDateTime,
                now.Add(_options.Expiration).UtcDateTime);

            foreach (var item in dict)
            {
                payload.Add(item.Key, item.Value);
            }

            var token = new JwtSecurityToken(new JwtHeader(_options.SigningCredentials), payload);

            var handler = new JwtSecurityTokenHandler();

            handler.InboundClaimTypeMap.Clear();

            return(new JsonWebToken(token, handler));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// create payload of jwt
        /// contains: iss, aud, iat, nbf, exp, viewclaims, username
        /// </summary>
        /// <param name="username">username of user</param>
        /// <param name="exptime">experation time of token</param>
        /// <param name="type">user type, either admin or general</param>
        /// <returns></returns>
        public JwtPayload CreatePayload(string username, int exptime = 20)//, string type, int exptime = 1)
        {
            // get current time
            DateTime currenttime = DateTime.UtcNow;

            // convert time to unixtime
            long currentunixTime = ((DateTimeOffset)currenttime).ToUnixTimeSeconds();

            // get 1 hour from current time
            long minsunixtime = ((DateTimeOffset)currenttime.AddMinutes(exptime)).ToUnixTimeSeconds();

            // Get view claims
            List <Claim> ViewClaim = GetViewClaims(username);

            // create payload of jwt
            JwtPayload payload = new JwtPayload()
            {
                { "iss", "https://www.Whatfits.social/" },
                // { "aud", type },
                { "iat", currentunixTime.ToString() },
                { "nbf", currentunixTime.ToString() },
                { "exp", minsunixtime.ToString() }
            };

            // add username to jwt
            payload.Add("UserName", username);

            // add view claims to payload
            payload.AddClaims(ViewClaim);

            // return payload
            return(payload);
        }
Ejemplo n.º 13
0
        private JwtPayload CreateJwtPayload(string subject,
                                            Dictionary <string, object> kinJwtPayloads)
        {
            DateTime currentTime = DateTime.UtcNow;

            List <Claim> claims = new List <Claim>
            {
                new Claim(System.IdentityModel.Tokens.Jwt.JwtRegisteredClaimNames.Sub, subject)
            };

            JwtPayload payload = new JwtPayload(
                _kinApplicationId,
                null,
                claims,
                null,
                currentTime.AddHours(6),
                currentTime);

            foreach (KeyValuePair <string, object> kinJwtPayload in kinJwtPayloads)
            {
                payload.Add(kinJwtPayload.Key, kinJwtPayload.Value);
            }

            return(payload);
        }
Ejemplo n.º 14
0
        public PrivateApiResponse<T> ForcePasswordChangeDiffHeaderWithContent<T>(IEnumerable<KeyValuePair<string, object>> parameters, object content, HttpMethod httpMethod, string contentType = "application/json")
        {
            string contentString = ConvertToJsonString(content);
            var HrbcAuth = Connection.GetCookieValue("HRBCAUTH");
            var tokenHeader = HrbcAuth.Split('.')[0];
            var tokenSecret = HrbcAuth.Split('.')[2];
            var tokenhandler = new JwtSecurityTokenHandler();
            var tokenObj = tokenhandler.ReadJwtToken(HrbcAuth);
            var newPayLoad = tokenObj.Payload.ToDictionary(p => p.Key, p => p.Value);
            var curPayLoad = JsonConvert.DeserializeObject<Dictionary<string, object>>(newPayLoad["payload"].ToString());
            foreach (var item in parameters)
            {
                curPayLoad[item.Key] = item.Value;
            }
            newPayLoad["payload"] = curPayLoad;
            JwtPayload jwtPayload = new JwtPayload();
            foreach (var item in newPayLoad)
            {
                jwtPayload.Add(item.Key, item.Value);
            }
            Connection.AddCookie("HRBCAUTH", $"{tokenHeader}.{jwtPayload.Base64UrlEncode()}.{tokenSecret}");

            using (LogHelper.LoggerForCurrentTest.EnterReproStep($"Force password change with {ForceEndpoint}"))
            {
                return ProcessResponseWithContent<T>(Connection.SendAsync(ForceEndpoint, contentString, httpMethod, contentType).Result);
            }
        }
Ejemplo n.º 15
0
        public PrivateApiResponse <T> SendRequestWithIdentityHeaderConvertJwt <T>(object content, Dictionary <string, object> headerValue, HttpMethod httpMethod, string contentType = "application/json")
        {
            string contentString = ConvertToJsonString(content);

            using (LogHelper.LoggerForCurrentTest.EnterReproStep($"Send request that contains Jwt X-IDENTITY header with {InternalTestEndpoint}"))
            {
                var HrbcAuth     = InternalConnection.GetCookieValue("HRBCAUTH");
                var tokenHeader  = HrbcAuth.Split('.')[0];
                var tokenSecret  = HrbcAuth.Split('.')[2];
                var tokenhandler = new JwtSecurityTokenHandler();
                var tokenObj     = tokenhandler.ReadJwtToken(HrbcAuth);
                var newPayLoad   = tokenObj.Payload.ToDictionary(p => p.Key, p => p.Value);
                var curPayLoad   = new Dictionary <string, object>();

                foreach (var item in headerValue)
                {
                    curPayLoad[item.Key.ToString()] = item.Value;
                }

                newPayLoad["payload"] = curPayLoad;
                JwtPayload jwtPayload = new JwtPayload();

                foreach (var item in newPayLoad)
                {
                    jwtPayload.Add(item.Key, item.Value);
                }

                InternalConnection.DeleteAllCookies();
                InternalConnection.Headers.Clear();
                InternalConnection.Headers.Add("X-IDENTITY", $"{tokenHeader}.{jwtPayload.Base64UrlEncode()}.{tokenSecret}");
                return(ProcessResponseWithContent <T>(InternalConnection.SendAsync(InternalTestEndpoint, contentString, httpMethod, contentType).Result));
            }
        }
Ejemplo n.º 16
0
        public void Descriptor_FullCapacity()
        {
            var payload = new JwtPayload();

            for (int i = 0; i < 256; i++)
            {
                payload.Add(i.ToString(), i);
            }

            var descriptor = new JweDescriptor(SymmetricJwk.GenerateKey(EncryptionAlgorithm.A128CbcHS256), KeyManagementAlgorithm.Dir, EncryptionAlgorithm.A128CbcHS256, CompressionAlgorithm.Def)
            {
                Payload = new JwsDescriptor(SymmetricJwk.GenerateKey(SignatureAlgorithm.HS256), SignatureAlgorithm.HS256)
                {
                    Payload = payload
                }
            };

            for (int i = 0; i < 256; i++)
            {
                descriptor.Payload.TryGetClaim(i.ToString(), out var member);
                Assert.Equal(JwtValueKind.Int32, member.Type);
                Assert.Equal(i.ToString(), member.Name.ToString());
                Assert.Equal(i, (int)member.Value);
            }

            PooledByteBufferWriter writer = new PooledByteBufferWriter();
            var context = new EncodingContext(writer, null, 0, false);

            descriptor.Encode(context);
        }
Ejemplo n.º 17
0
        private void BtnGenerateToken_Click(object sender, RoutedEventArgs e)
        {
            string step = null;

            try
            {
                UpdateKeyParameter();
                JwtPayload payload = new JwtPayload();
                foreach (var v in JwtPayloadPairs)
                {
                    step = $"Claim: {v.Name}, Value: {v.Value}";
                    object value;
                    switch (v.ValueType)
                    {
                    case ClaimValueType.Numeric:
                        value = long.Parse(v.Value.ToString());
                        break;

                    case ClaimValueType.Decimal:
                        value = decimal.Parse(v.Value.ToString());
                        break;

                    default:
                        value = v.Value;
                        break;
                    }
                    payload.Add(v.Name, value);
                }
                string algorithm = GetAlgotithm(cbAlgorithms.SelectedItem);
                string token;
                if (algorithm.StartsWith("HS"))
                {
                    string base64Key = GetBase64Key(symmetricKey, keyform);
                    JsonWebTokenUtility.CreateHmacShaToken(base64Key, algorithm, payload, out token);
                }
                else if (algorithm.StartsWith("RS"))
                {
                    var importedCertificate = ImportCertificate(certificatePath, certificatePassword);
                    JsonWebTokenUtility.CreateRsaToken(importedCertificate, algorithm, payload, out token);
                }
                else if (algorithm.StartsWith("ES"))
                {
                    var importedCertificate = ImportCertificate(certificatePath, certificatePassword);
                    JsonWebTokenUtility.CreateEcdsaToken(importedCertificate, algorithm, payload, out token);
                }
                else
                {
                    token = "The given algorithm is not supported.";
                }
                txtJwtToken.Text = token;
            }
            catch (CryptographicException ce)
            {
                ShowMessageBox("Error when doing cryptography", ce.Message, ce.ToString());
            }
            catch (Exception ex)
            {
                ShowMessageBox("Error", "An error has occurred during generating " + step + "\nError Message: " + ex.Message, ex.ToString());
            }
        }
Ejemplo n.º 18
0
        public static object GenerateToken(dynamic input)
        {
            var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var header      = new JwtHeader(credentials);
            var payload     = new JwtPayload();

            foreach (IDictionary <string, object> row in input)
            {
                foreach (var pair in row)
                {
                    var num = pair.Key;
                    var val = pair.Value;
                    if (num == "ID" || num == "EMAIL")
                    {
                        payload.Add(num, val);
                    }
                }
            }
            var secToken = new JwtSecurityToken(header, payload);
            var handler  = new JwtSecurityTokenHandler();

            var tokenString = handler.WriteToken(secToken);

            //Get_Id("eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJJRCI6MzAwMy4wLCJFTUFJTCI6ImdhYnJpZWxtYXRlaTJAZ21haWwuY29tIn0.0YGk0PrCbkuhjdSHrG8YQ9oEpiNOh4YNxWqO36xMO28");
            return(tokenString);
        }
Ejemplo n.º 19
0
        public string BuildJwtToken(LoginViewModel loginViewModel)
        {
            var plainTextSecurityKey = Environment.GetEnvironmentVariable("JWT_KEY");
            var signingKey           = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(plainTextSecurityKey));
            var credentials          = new SigningCredentials(
                signingKey,
                SecurityAlgorithms.HmacSha256);

            var    notBefore         = DateTime.UtcNow.AddSeconds(-1);
            double expirationMinutes = double.Parse(Environment.GetEnvironmentVariable("JWT_EXP_MINUTES") ?? "180");
            var    expires           = DateTime.UtcNow.AddMinutes(expirationMinutes);
            var    payload           = new JwtPayload(Environment.GetEnvironmentVariable("JWT_ISSUER"), Environment.GetEnvironmentVariable("JWT_AUDIENCE"), new List <Claim>(), notBefore, expires)
            {
                { "userId", loginViewModel.UserId.ToString() },
                { "userName", loginViewModel.Name },
                { "emailAddress", loginViewModel.EmailAddress },
                { "customers", loginViewModel.Customers },
                { "roles", loginViewModel.Roles },
                { "permissions", loginViewModel.Permissions }
            };

            foreach (var permission in loginViewModel.Permissions)
            {
                payload.Add(permission.Name, "true");
            }

            var jwtToken        = new JwtSecurityToken(new JwtHeader(credentials), payload);
            var jwtTokenHandler = new JwtSecurityTokenHandler();

            return(jwtTokenHandler.WriteToken(jwtToken));
        }
Ejemplo n.º 20
0
        public void TestClaimWithLargeExpValue()
        {
            JwtPayload jwtPayload = new JwtPayload();

            jwtPayload.Add("exp", 1507680819080);
            DateTime expirationTime = jwtPayload.ValidTo;

            Assert.True(DateTime.MaxValue == expirationTime, "EpochTime.DateTime( time ) != jwtPayload.ValidTo");
        }
Ejemplo n.º 21
0
        public String createJWT(Int32 IdUser)
        {
            var timeUnix = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
            var header   = new JwtHeader(new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), SecurityAlgorithms.HmacSha512));
            var payload  = new JwtPayload();

            payload.Add("id", IdUser);
            //La validación de la expiración tiene 5 minutos mas de tiempo por eso al tiempo de expiración
            //se le restan 4 para que solo quede con un minuto de tiempo de vida
            payload.Add("exp", (Convert.ToUInt64(timeUnix) - (60 * 4)));
            payload.Add("iat", (Convert.ToUInt64(timeUnix) - (60 * 5)));
            payload.Add("nbf", (Convert.ToUInt64(timeUnix) - (60 * 5)));

            JwtSecurityToken        jst          = new JwtSecurityToken(header, payload);
            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

            return(tokenHandler.WriteToken(jst));
        }
Ejemplo n.º 22
0
        protected override object[] HttpCallAuth(HttpClient _http, string _method, ref string _url, object[] _keyValues)
        {
            string  _query = "";
            JObject _json  = new JObject();

            for (int i = 0; i < _keyValues.Length - 1; i += 2)
            {
                _query += _query == "" ? "" : "&";
                _query += _keyValues[i] + "=" + System.Web.HttpUtility.UrlEncode(_keyValues[i + 1].ToString());

                Type _valueType = _keyValues[i + 1].GetType();
                if (_valueType == typeof(int))
                {
                    _json[_keyValues[i]] = (int)_keyValues[i + 1];
                }
                else if (_valueType == typeof(bool))
                {
                    _json[_keyValues[i]] = (bool)_keyValues[i + 1];
                }
                else if (_valueType == typeof(decimal))
                {
                    _json[_keyValues[i]] = (decimal)_keyValues[i + 1];
                }
                else if (_valueType == typeof(long))
                {
                    _json[_keyValues[i]] = (long)_keyValues[i + 1];
                }
                else if (_valueType == typeof(JArray))
                {
                    _json[_keyValues[i]] = (JArray)_keyValues[i + 1];
                }
                else
                {
                    _json[_keyValues[i]] = _keyValues[i + 1].ToString();
                }
            }

            JwtPayload _payload = new JwtPayload {
                { "access_key", base.Key }, { "nonce", DateTimePlus.DateTime2JSTime(DateTime.UtcNow).ToString() + DateTime.UtcNow.Millisecond.ToString() }
            };

            if (_method.ToUpper() == "POST")
            {
                _payload.Add("query", _query);
            }
            byte[] _keyBytes           = Encoding.Default.GetBytes(base.Secret);
            var    _securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(_keyBytes);
            var    _credentials        = new Microsoft.IdentityModel.Tokens.SigningCredentials(_securityKey, "HS256");
            var    _header             = new JwtHeader(_credentials);
            var    _secToken           = new JwtSecurityToken(_header, _payload);
            var    _jwtToken           = new JwtSecurityTokenHandler().WriteToken(_secToken);
            var    _authorizationToken = _jwtToken;

            _http.Headers.Add("Authorization", $"Bearer {_authorizationToken}");

            return(_keyValues);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 生成Token
        /// </summary>
        /// <param name="userName">登录用户名</param>
        /// <param name="tokenInfos"></param>
        /// <param name="expDays">有效天数</param>
        /// <returns></returns>
        public static string GenerateToken(String userName, List <TokenInfo> tokenInfos, int expDays = 30)
        {
            var credentials = new SigningCredentials
                                  (securityKey, SecurityAlgorithms.HmacSha384);


            var header = new JwtHeader(credentials);


            var payload = new JwtPayload();
            var now     = WIPCommon.GetUnixTimeStampWithGLWZForSeconds().ToString();
            // 30天过期
            var exp = long.Parse(now) + (expDays * 24 * 60 * 60);//单位:秒

            //注释下面的代码 [EditBy shaocx,2019-01-07]

            /*
             * if (userName.Contains("integrated"))
             * {
             *  exp = long.Parse(now) + 31536000;
             * }
             * //*/
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iat, now));            //发布时间
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Exp, exp.ToString())); //到期时间
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Iss, WIP));            //发行人
            payload.AddClaim(new Claim(JwtRegisteredClaimNames.Sub, userName));       //主题
            // 追加自定义字段 数据库字段
            payload.AddClaim(new Claim("username", userName));                        //自定义对象之用户名称
            // 自动获取payload
            if (tokenInfos != null)
            {
                payload.Add("usergroup", tokenInfos);//自定义对象之用户角色集合
            }
            else
            {
                payload.Add("usergroup", getTokenInfos(userName));//自定义对象之用户角色集合
            }
            var secToken = new JwtSecurityToken(header, payload);
            var handler  = new JwtSecurityTokenHandler();

            String tokenString = handler.WriteToken(secToken);

            return(tokenString);
        }
Ejemplo n.º 24
0
        public void ClaimSourceAndClaimName()
        {
            string claimSources = "_claim_sources";
            string claimNames   = "_claim_names";
            var    context      = new CompareContext();

            JwtPayload payload = new JwtPayload();

            payload.Add(claimSources, JsonClaims.ClaimSourcesAsDictionary);
            payload.Add(claimNames, JsonClaims.ClaimNamesAsDictionary);
            payload.Add("iss", IdentityUtilities.DefaultIssuer);

            JwtSecurityToken        jwtToken   = new JwtSecurityToken(new JwtHeader(), payload);
            JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler();
            string encodedJwt           = jwtHandler.WriteToken(new JwtSecurityToken(new JwtHeader(), payload));
            var    validationParameters = new TokenValidationParameters
            {
                IssuerValidator     = (issuer, st, tvp) => { return(issuer); },
                RequireSignedTokens = false,
                ValidateAudience    = false,
                ValidateLifetime    = false,
            };

            SecurityToken validatedJwt     = null;
            var           claimsPrincipal  = jwtHandler.ValidateToken(encodedJwt, validationParameters, out validatedJwt);
            var           expectedIdentity = JsonClaims.ClaimsIdentityDistributedClaims(
                IdentityUtilities.DefaultIssuer,
                TokenValidationParameters.DefaultAuthenticationType,
                JsonClaims.ClaimSourcesAsDictionary,
                JsonClaims.ClaimNamesAsDictionary);

            IdentityComparer.AreEqual(claimsPrincipal.Identity as ClaimsIdentity, expectedIdentity, context);

            jwtToken   = new JwtSecurityToken(new JwtHeader(), new JwtPayload(IdentityUtilities.DefaultIssuer, null, ClaimSets.EntityAsJsonClaim(IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer), null, null));
            encodedJwt = jwtHandler.WriteToken(jwtToken);
            SecurityToken validatedToken;
            var           cp = jwtHandler.ValidateToken(encodedJwt, validationParameters, out validatedToken);

            IdentityComparer.AreEqual(
                cp.FindFirst(typeof(Entity).ToString()),
                new Claim(typeof(Entity).ToString(), JsonExtensions.SerializeToJson(Entity.Default), JsonClaimValueTypes.Json, IdentityUtilities.DefaultIssuer, IdentityUtilities.DefaultIssuer, cp.Identity as ClaimsIdentity),
                context);
            TestUtilities.AssertFailIfErrors(context.Diffs);
        }
Ejemplo n.º 25
0
        public override string ToString()
        {
            JwtPayload payload = new JwtPayload();

            payload.Add(EventTokenClaimTypes.Identifier, this.Identifier);

            payload.Add(EventTokenClaimTypes.Issuer, this.Issuer);

            if (this.Audience != null && this.Audience.Any())
            {
                string[] audience = this.Audience.ToArray();
                payload.Add(EventTokenClaimTypes.Audience, audience);
            }

            long issuedAt = new UnixTime(this.IssuedAt).EpochTimestamp;

            payload.Add(EventTokenClaimTypes.IssuedAt, issuedAt);

            if (this.NotBefore.HasValue)
            {
                long notBefore = new UnixTime(this.NotBefore.Value).EpochTimestamp;
                payload.Add(EventTokenClaimTypes.NotBefore, notBefore);
            }

            if (!string.IsNullOrWhiteSpace(this.Subject))
            {
                payload.Add(EventTokenClaimTypes.Subject, this.Subject);
            }

            if (this.Expiration.HasValue)
            {
                long expiration = new UnixTime(this.Expiration.Value).EpochTimestamp;
                payload.Add(EventTokenClaimTypes.Expiration, expiration);
            }

            payload.Add(EventTokenClaimTypes.Events, this.Events);

            if (!string.IsNullOrWhiteSpace(this.Transaction))
            {
                payload.Add(EventTokenClaimTypes.Transaction, this.Transaction);
            }

            SecurityToken token  = new JwtSecurityToken(this.Header, payload);
            string        result = EventToken.TokenSerializer.Value.WriteToken(token);

            return(result);
        }
        public void JwtPalyoad_Claims()
        {
            JwtPayload jwtPayload = new JwtPayload();
            // multiple audiences

            jwtPayload.Add(JwtRegisteredClaimNames.Aud, IdentityUtilities.DefaultAudiences);
            string encodedPayload = jwtPayload.Encode();
            JwtPayload newjwtPayload = Base64UrlEncoder.Decode(encodedPayload).DeserializeJwtPayload();

            Assert.IsTrue(IdentityComparer.AreEqual(jwtPayload, newjwtPayload));
        }
Ejemplo n.º 27
0
        public void TestDateTimeClaim()
        {
            JwtPayload jwtPayload = new JwtPayload();
            var        dateTime   = new DateTime(2020, 1, 1, 1, 1, 1, 1);

            jwtPayload.Add("dateTime", dateTime);
            var dateTimeClaim = jwtPayload.Claims.First();

            Assert.True(string.Equals(dateTimeClaim.ValueType, ClaimValueTypes.DateTime, StringComparison.Ordinal), "dateTimeClaim.Type != ClaimValueTypes.DateTime");
            Assert.True(string.Equals(dateTimeClaim.Value, dateTime.ToUniversalTime().ToString("o", CultureInfo.InvariantCulture), StringComparison.Ordinal), "dateTimeClaim.Value != dateTime.ToUniversalTime('o', CultureInfo.InvariantCulture).ToString()");
        }
Ejemplo n.º 28
0
        public JwtPayload GetPayload(DateTime expirationTime, Dictionary <string, object> claims)
        {
            var payload = new JwtPayload();

            AddExpirationClaim(payload, expirationTime);

            foreach (var claim in claims)
            {
                payload.Add(claim.Key, claim.Value);
            }

            return(payload);
        }
        /// <summary>
        /// Returns the encoded parameters as a JwtPayload
        /// </summary>
        /// <returns></returns>
        public JwtPayload ToJwtPayload()
        {
            var payload  = this.Encode();
            var encoded  = payload.Encode();
            var jPayload = new JwtPayload();

            foreach (var values in encoded)
            {
                jPayload.Add(values.Key, values.Value);
            }

            return(jPayload);
        }
        /// <inheritdoc />
        public Task <GitHubClient> NewApplicationAuthenticatedClient()
        {
            // Create a new signed JWT token for authenticating as the application
            var header = new JwtHeader(_credentials.ApplicationCredentials);

            var issued = (long)(DateTime.UtcNow - UnixEpoch).TotalSeconds;

            var payload = new JwtPayload();

            payload.Add("iat", issued);
            payload.Add("exp", issued + _applicationTokenExpirationSeconds);
            payload.Add("iss", _credentials.ApplicationId);

            var token        = new JwtSecurityToken(header, payload);
            var encodedToken = _applicationTokenHandler.WriteToken(token);

            // Return a new client
            var client = new GitHubClient(new ProductHeaderValue(_credentials.ApplicationUserAgent));

            client.Credentials = new Credentials(encodedToken, AuthenticationType.Bearer);

            return(Task.FromResult(client));
        }
        public void JwtPalyoad_ObjectClaims()
        {
            JwtPayload jwtPayload = new JwtPayload();
            int?       time       = 10000;

            jwtPayload.Add("exp", time);
            DateTime payloadTime    = EpochTime.DateTime(time.Value);
            DateTime payloadValidTo = jwtPayload.ValidTo;

            Assert.IsFalse(EpochTime.DateTime(time.Value) != jwtPayload.ValidTo, "EpochTime.DateTime( time ) != jwtPayload.ValidTo");

            int?expirationTime = jwtPayload.Expiration;

            Assert.IsTrue(expirationTime == time, "expirationTime != time");
        }
        public void CreateAndValidateTokens_JsonClaims()
        {
            List<string> errors = new List<string>();

            string issuer = "http://www.GotJWT.com";
            string claimSources = "_claim_sources";
            string claimNames = "_claim_names";

            JwtPayload jwtPayloadClaimSources = new JwtPayload();
            jwtPayloadClaimSources.Add(claimSources, JsonClaims.ClaimSources);
            jwtPayloadClaimSources.Add(claimNames, JsonClaims.ClaimNames);

            JwtSecurityToken jwtClaimSources = 
                new JwtSecurityToken(
                    new JwtHeader(),
                    jwtPayloadClaimSources);

            JwtSecurityTokenHandler jwtHandler = new JwtSecurityTokenHandler();
            string encodedJwt = jwtHandler.WriteToken(jwtClaimSources);
            var validationParameters =
                new TokenValidationParameters
                {
                    IssuerValidator = (s, st, tvp) => { return issuer;},
                    RequireSignedTokens = false,
                    ValidateAudience = false,
                    ValidateLifetime = false,
                };

            SecurityToken validatedJwt = null;
            var claimsPrincipal = jwtHandler.ValidateToken(encodedJwt, validationParameters, out validatedJwt);
            if (!IdentityComparer.AreEqual
                (claimsPrincipal.Identity as ClaimsIdentity,
                 JsonClaims.ClaimsIdentityDistributedClaims(issuer, TokenValidationParameters.DefaultAuthenticationType, JsonClaims.ClaimSources, JsonClaims.ClaimNames)))
            {
                errors.Add("JsonClaims.ClaimSources, JsonClaims.ClaimNames: test failed");
            };

            Claim c = claimsPrincipal.FindFirst(claimSources);
            if (!c.Properties.ContainsKey(JwtSecurityTokenHandler.JsonClaimTypeProperty))
            {
                errors.Add(claimSources + " claim, did not have json property: " + JwtSecurityTokenHandler.JsonClaimTypeProperty);
            }
            else
            {
                if (!string.Equals(c.Properties[JwtSecurityTokenHandler.JsonClaimTypeProperty], typeof(IDictionary<string, object>).ToString(), StringComparison.Ordinal))
                {
                    errors.Add("!string.Equals(c.Properties[JwtSecurityTokenHandler.JsonClaimTypeProperty], typeof(IDictionary<string, object>).ToString(), StringComparison.Ordinal)" +
                        "value is: " + c.Properties[JwtSecurityTokenHandler.JsonClaimTypeProperty]);
                }
            }

            JwtSecurityToken jwtWithEntity =
                new JwtSecurityToken(
                    new JwtHeader(),
                    new JwtPayload(claims: ClaimSets.EntityAsJsonClaim(issuer, issuer)));

            encodedJwt = jwtHandler.WriteToken(jwtWithEntity);
            JwtSecurityToken jwtRead = jwtHandler.ReadToken(encodedJwt) as JwtSecurityToken;

            SecurityToken validatedToken;
            var cp = jwtHandler.ValidateToken(jwtRead.RawData, validationParameters, out validatedToken);
            Claim jsonClaim = cp.FindFirst(typeof(Entity).ToString());
            if (jsonClaim == null)
            {
                errors.Add("Did not find Jsonclaims. Looking for claim of type: '" + typeof(Entity).ToString() + "'");
            };

            string jsString = JsonExtensions.SerializeToJson(Entity.Default);

            if (!string.Equals(jsString, jsonClaim.Value, StringComparison.Ordinal))
            {
                errors.Add(string.Format(CultureInfo.InvariantCulture, "Find Jsonclaims of type: '{0}', but they weren't equal.\nExpecting:\n'{1}'.\nReceived:\n'{2}'", typeof(Entity).ToString(), jsString, jsonClaim.Value));
            }

            TestUtilities.AssertFailIfErrors(MethodInfo.GetCurrentMethod().Name, errors);
        }
        public void JwtPalyoad_ObjectClaims()
        {
            JwtPayload jwtPayload = new JwtPayload();
            int? time = 10000;
            jwtPayload.Add("exp", time );
            DateTime payloadTime = EpochTime.DateTime( time.Value );
            DateTime payloadValidTo = jwtPayload.ValidTo;

            Assert.AreEqual(EpochTime.DateTime(time.Value), jwtPayload.ValidTo, "EpochTime.DateTime( time ) != jwtPayload.ValidTo");

            int? expirationTime = jwtPayload.Exp;
            Assert.AreEqual(expirationTime, time, "expirationTime != time");
        }
        /// <summary>
        /// Creates the JWT payload
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns>The JWT payload</returns>
        protected virtual JwtPayload CreatePayload(Token token)
        {
            var payload = new JwtPayload(
                token.Issuer,
                token.Audience,
                null,
                DateTimeHelper.UtcNow,
                DateTimeHelper.UtcNow.AddSeconds(token.Lifetime));

            var amrClaims = token.Claims.Where(x => x.Type == Constants.ClaimTypes.AuthenticationMethod);
            var jsonClaims = token.Claims.Where(x => x.ValueType == Constants.ClaimValueTypes.Json);
            var normalClaims = token.Claims.Except(amrClaims).Except(jsonClaims);

            payload.AddClaims(normalClaims);

            // deal with amr
            var amrValues = amrClaims.Select(x => x.Value).Distinct().ToArray();
            if (amrValues.Any())
            {
                payload.Add(Constants.ClaimTypes.AuthenticationMethod, amrValues);
            }

            // deal with json types
            // calling ToArray() to trigger JSON parsing once and so later 
            // collection identity comparisons work for the anonymous type
            var jsonTokens = jsonClaims.Select(x => new { x.Type, JsonValue = JRaw.Parse(x.Value) }).ToArray();

            var jsonObjects = jsonTokens.Where(x => x.JsonValue.Type == JTokenType.Object).ToArray();
            var jsonObjectGroups = jsonObjects.GroupBy(x=>x.Type).ToArray();
            foreach(var group in jsonObjectGroups)
            {
                if (payload.ContainsKey(group.Key))
                {
                    throw new Exception(String.Format("Can't add two claims where one is a JSON object and the other is not a JSON object ({0})", group.Key));
                }

                if (group.Skip(1).Any())
                {
                    // add as array
                    payload.Add(group.Key, group.Select(x=>x.JsonValue).ToArray());
                }
                else
                {
                    // add just one
                    payload.Add(group.Key, group.First().JsonValue);
                }
            }

            var jsonArrays = jsonTokens.Where(x => x.JsonValue.Type == JTokenType.Array).ToArray();
            var jsonArrayGroups = jsonArrays.GroupBy(x=>x.Type).ToArray();
            foreach (var group in jsonArrayGroups)
            {
                if (payload.ContainsKey(group.Key))
                {
                    throw new Exception(String.Format("Can't add two claims where one is a JSON array and the other is not a JSON array ({0})", group.Key));
                }

                List<JToken> newArr = new List<JToken>();
                foreach(var arrays in group)
                {
                    var arr = (JArray)arrays.JsonValue;
                    newArr.AddRange(arr);
                }

                // add just one array for the group/key/claim type
                payload.Add(group.Key, newArr.ToArray());
            }

            var unsupportedJsonTokens = jsonTokens.Except(jsonObjects).Except(jsonArrays);
            var unsupportedJsonClaimTypes = unsupportedJsonTokens.Select(x => x.Type).Distinct();
            if (unsupportedJsonClaimTypes.Any())
            {
                throw new Exception(String.Format("Unsupported JSON type for claim types: {0}", unsupportedJsonClaimTypes.Aggregate((x, y) => x + ", " + y)));
            }

            return payload;
        }