Exemplo n.º 1
0
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string audienceId           = Utils.Configuration.TokenAudienceId;
            string symmetricKeyAsBase64 = Utils.Configuration.TokenAudienceSecret;
            var    keyByteArray         = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
            //var signingKey = new System.IdentityModel.Tokens.SigningCredentials(new System.IdentityModel.Tokens.InMemorySymmetricSecurityKey(keyByteArray),
            //												SignatureAlgorithm,
            //												DigestAlgorithm);
            var signingKey = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray),
                                                                                   SignatureAlgorithm,
                                                                                   DigestAlgorithm);

            var issued  = data.Properties.IssuedUtc;
            var expires = data.Properties.ExpiresUtc;
            var token   = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(_issuer, audienceId, data.Identity.Claims,
                                                                               issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
            var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var jwt     = handler.WriteToken(token);

            return(jwt);
        }
Exemplo n.º 2
0
        private string JWT_NoParameter()
        {
            //Random rand = new Random();
            //TimeSpan diff = DateTime.Now - new DateTime(rand.Next(1,2020), rand.Next(1, 12), rand.Next(1, 20));
            //var nonce = Convert.ToInt64(diff.TotalMilliseconds);
            //var nonce = rand.Next(0, 2147483647);

            //Console.WriteLine(nonce);

            var payload = new JwtPayload {
                { "access_key", httpClient.AccessKey }, { "nonce", nonce }
            };

            byte[] keyBytes    = Encoding.Default.GetBytes(httpClient.SecretKey);
            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;

            //Console.WriteLine(authorizationToken);
            return(authorizationToken);
        }
Exemplo n.º 3
0
        private string createToken(string username)
        {
            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = DateTime.UtcNow.AddDays(7);

            //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token
            var tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, username)
            });

            const string sec                = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
            var          now                = DateTime.UtcNow;
            var          securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
            var          signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);


            //create the jwt
            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:44350", audience: "http://localhost:44350",
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 4
0
        public static string CreateToken(string userName, string role, string secretKey)
        {
            DateTime issuedAt = DateTime.UtcNow;

            DateTime expires = DateTime.UtcNow.AddDays(7);

            var tokenHandler = new JwtSecurityTokenHandler();

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim("userName", userName),
                new Claim("role", role)
            });

            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(secretKey));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            string baseUrl = CloudConfigurationManager.GetSetting("BaseUrl");

            var jwToken =
                tokenHandler.CreateJwtSecurityToken(issuer: baseUrl, audience: baseUrl,
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires,
                                                    signingCredentials: signingCredentials);

            var tokenString = tokenHandler.WriteToken(jwToken);

            return(tokenString);
        }
        private string createToken(UserRequest user)
        {
            DateTime issuedAt = DateTime.UtcNow;
            DateTime expires  = DateTime.UtcNow.AddHours(2);

            var tokenHandler = new JwtSecurityTokenHandler();

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, user.Username),
                new Claim(ClaimTypes.Name, user.Password)
            });

            const string sec                = "z401b09eab3c013d4ca54922bb802bec8fd5wefgewgGHA318192b0a75f201dwegwGWGW8b3727429090fb33759fefaeH5THE1abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
            var          now                = DateTime.UtcNow;
            var          securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
            var          signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(
                    issuer: "https://localhost:44368/",
                    audience: "https://localhost:44368/",
                    subject: claimsIdentity,
                    notBefore: issuedAt,
                    expires: expires,
                    signingCredentials: signingCredentials
                    );
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
        public static string GenerateToken(string username)
        {
            DateTime issuedAt = DateTime.UtcNow;
            DateTime expires  = DateTime.UtcNow.AddHours(2);


            var tokenHandler = new JwtSecurityTokenHandler();

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, "adminName"),
                new Claim(ClaimTypes.Email, "*****@*****.**"),
                new Claim("DisplayName", "User"),
                new Claim(ClaimTypes.Role, "admin")
            });

            var now                = DateTime.UtcNow;
            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(Secret));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey,
                                                                                           Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);


            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:63867", audience: "http://localhost:63867",
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 7
0
        public static string CreateToken(UserIdentityData userIdentity, IConfiguration configuration)
        {
            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires      = DateTime.UtcNow.AddDays(1);
            var      tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim("Id", userIdentity.Id.ToString()),
                new Claim("UserName", userIdentity.UserName),
                new Claim("Email", userIdentity.Email),
            });

            string sec                = configuration["Token:JWT_SECURITY_KEY"];
            var    now                = DateTime.UtcNow;
            var    securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
            var    signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);


            //create the jwt
            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(issuer: configuration["Token:JWT_ISSUER"], audience: configuration["Token:JWT_AUDIENCE"],
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 8
0
        internal static string CreateToken(string username)
        {
            DateTime issuedAt = DateTime.UtcNow;

            DateTime expires = DateTime.UtcNow.AddDays(7);

            var tokenHandler = new JwtSecurityTokenHandler();

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, username)
            });

            string sec = ConfigurationManager.AppSettings["jwt:key"];

            var now = DateTime.UtcNow;

            var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));

            var signingCredential = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);

            var token = (JwtSecurityToken)tokenHandler.CreateJwtSecurityToken(
                issuer: ConfigurationManager.AppSettings["jwt:issuer"],
                audience: ConfigurationManager.AppSettings["jwt:audience"],
                subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredential);

            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 9
0
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];

            string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["as:AudienceSecret"];

            var keyByteArray       = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray);
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            var issued  = data.Properties.IssuedUtc;
            var expires = data.Properties.ExpiresUtc;
            var token   = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials);

            var handler = new JwtSecurityTokenHandler();

            var jwt = handler.WriteToken(token);

            return(jwt);
        }
Exemplo n.º 10
0
        private string GenerateToken(IDictionary <string, string> keyValues)
        {
            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = DateTime.UtcNow.AddDays(7);

            var tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            ClaimsIdentity claimsIdentity = new ClaimsIdentity();

            foreach (var item in keyValues)
            {
                claimsIdentity.AddClaim(new Claim(item.Key, item.Value));
            }

            const string secretKey          = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
            var          securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(secretKey));
            var          signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);


            //create the jwt
            var token = tokenHandler.CreateJwtSecurityToken(issuer: "http://localhost:8080",
                                                            audience: "http://localhost:8080",
                                                            subject: claimsIdentity,
                                                            notBefore: issuedAt,
                                                            expires: expires,
                                                            signingCredentials: signingCredentials);

            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
        /// <summary>
        /// This method will generat a JWT token.
        /// </summary>
        /// <returns>Returns the JWT token for the Configuration App.</returns>
        public string GenerateToken()
        {
            DateTime issuedAt = DateTime.UtcNow;
            var      tenantId = this.appSettings.TenantId;
            var      audience = this.appSettings.ClientId;
            var      issuer   = $"https://sts.windows.net/{tenantId}/";

            // Set the time when it expires.
            DateTime expires = DateTime.UtcNow.AddHours(1);

            var tokenHandler = new JwtSecurityTokenHandler();

            // Create a identity and add claims to the user which we want to log in.
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim("appid", audience),
            });

            // Need to get the below secret key from key vault
            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(this.appSettings.ClientSecret));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            // Creates the JWT token.
            var token = (JwtSecurityToken)tokenHandler.CreateJwtSecurityToken(
                issuer: issuer,
                audience: audience,
                subject: claimsIdentity,
                notBefore: issuedAt,
                expires: expires,
                signingCredentials: signingCredentials);

            return(tokenHandler.WriteToken(token));
        }
        private string CreateToken(string username)
        {
            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = DateTime.UtcNow.AddDays(1);

            var tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, username)
            });

            string sec                = ConfigurationManager.AppSettings["loginKey"].ToString();
            var    now                = DateTime.UtcNow;
            var    securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
            var    signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);
            var    issuer             = ConfigurationManager.AppSettings["keyIssuer"].ToString();

            //create the jwt
            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(issuer: issuer, audience: issuer,
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 13
0
        void Run()
        {
            var now         = DateTime.UtcNow;
            var securityKey = new Microsoft.IdentityModel.Tokens.
                              SymmetricSecurityKey(Encoding.UTF8.GetBytes(_passphrase));

            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, "HS256");
            var header             = new JwtHeader(signingCredentials);
            var payload            = new JwtPayload
            {
                { "unique_name", _name },
                { "scope", "https://apigee.com/example" },
                { "iat", RenderAsEpoch(now) },
                { "nbf", RenderAsEpoch(now) },
                { "exp", RenderAsEpoch(now.AddSeconds(_expiry)) }
            };
            var secToken    = new JwtSecurityToken(header, payload);
            var handler     = new JwtSecurityTokenHandler();
            var tokenString = handler.WriteToken(secToken);

            Console.WriteLine("\ntoken:\n" + tokenString);

            var    decodedToken       = handler.ReadToken(tokenString);
            String decodedTokenString = decodedToken.ToString();
            //Console.WriteLine("\nDecoded: \n"+ decodedTokenString);

            var parts = decodedTokenString.Split(".", 2);

            foreach (String part in parts)
            {
                dynamic parsedJson = Newtonsoft.Json.JsonConvert.DeserializeObject(part);
                string  formatted  = Newtonsoft.Json.JsonConvert.SerializeObject(parsedJson /* decodedToken */, Newtonsoft.Json.Formatting.Indented);
                Console.WriteLine("\n" + formatted); \
            }
        }
Exemplo n.º 14
0
        public static string GenerateTokenKey(string userName)
        {
            var issuedAt = DateTime.Now;
            var expires  = DateTime.UtcNow.AddDays(7);

            var tokenHandler = new JwtSecurityTokenHandler();

            var claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userName) });

            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(SECRET_KEY));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            //Create token key
            var token = (JwtSecurityToken)tokenHandler.CreateJwtSecurityToken(
                issuer: ISSUER,
                audience: ISSUER,
                subject: claimsIdentity,
                notBefore: issuedAt,
                expires: expires,
                signingCredentials: signingCredentials
                );

            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 15
0
        public string GetJWTToken(Device device)
        {
            if (JWTService.TokenKeysHolder.keys.Count == 0)
            {
                return(null);
            }
            string sec = JWTService.TokenKeysHolder.keys[0].k;

            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Convert.FromBase64String(sec));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);
            var header             = new JwtHeader(signingCredentials);

            header.Add("kid", JWTService.TokenKeysHolder.keys[0].kid);
            var claims = new[]
            {
                new Claim("serialID", device.OriginalID.ToString()),
                new Claim("carID", device.CarID.ToString(), ClaimValueTypes.Integer64),
                new Claim("deviceID", device.ID.ToString(), ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Exp, ((Int32)(DateTime.UtcNow.AddDays(1).Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString(), ClaimValueTypes.Integer64),
                new Claim(JwtRegisteredClaimNames.Aud, "https://auth.mgduke.com")
            };
            var payload     = new JwtPayload(claims);
            var secToken    = new JwtSecurityToken(header, payload);
            var handler     = new JwtSecurityTokenHandler();
            var tokenString = handler.WriteToken(secToken);


            return(tokenString);
        }
        private string createToken(string username)
        {
            DateTime issuedAt = DateTime.UtcNow;
            DateTime expires  = DateTime.UtcNow.AddMinutes(60);

            var tokenHandler = new JwtSecurityTokenHandler();

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, username)
            });

            const string sec                = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
            var          now                = DateTime.UtcNow;
            var          securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
            var          signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);


            //create the jwt
            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(
                    subject: claimsIdentity,
                    notBefore: issuedAt,
                    expires: expires,
                    signingCredentials: signingCredentials
                    );
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 17
0
        public string createToken(string username)
        {
            DateTime issuedAt     = DateTime.UtcNow;
            DateTime expires      = DateTime.UtcNow.AddDays(7);
            var      tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, username)
                , new Claim(ClaimTypes.Role, "ADMIN-SuperUser")
            });
            var sec                = "This is my Security Key";
            var now                = DateTime.UtcNow;
            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);
            //create the jwt
            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(
                    issuer: "http://localhost:50191",
                    audience: "http://localhost:50191",
                    subject: claimsIdentity,
                    notBefore: issuedAt,
                    expires: expires,
                    signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 18
0
    public string Protect(AuthenticationTicket data)
    {
        if (data == null)
        {
            throw new ArgumentNullException("data");
        }
        var claims = new List <Claim>();

        //Custom claim
        claims.Add(new Claim("HairCount", "46"));
        data.Identity.AddClaims(claims);
        string audienceId = AzureADConstants.GraphResourceId;
        Guid   guidClientId;
        bool   isValidAudience = Guid.TryParse(AzureADConstants.ClientId, out guidClientId);

        if (!isValidAudience)
        {
            throw new InvalidOperationException("AuthenticationTicket.Properties does not include audience");
        }

        var keyByteArray       = TextEncodings.Base64Url.Decode(AzureADConstants.AppKey);
        var securityKey        = new SymmetricSecurityKey(keyByteArray);
        var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
            securityKey,
            SecurityAlgorithms.HmacSha256Signature);
        var    issued  = data.Properties.IssuedUtc;
        var    expires = data.Properties.ExpiresUtc;
        string _issuer = AzureADConstants.Authority;
        var    token   = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingCredentials);
        var    handler = new JwtSecurityTokenHandler();

        return(handler.WriteToken(token));
    }
Exemplo n.º 19
0
        public IHttpActionResult GetToken()
        {
            //Create Security Key
            string securityKey = "This My Security key made by ";
            //Symetric Key
            var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));

            //var symmetricSecuritykey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
            ////signingCredintals
            var signingCredintals = new Microsoft.IdentityModel.Tokens.SigningCredentials(key, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);
            //var signingCredintals = new SigningCredentials(symmetricSecuritykey, SecurityAlgorithms.HmacSha256Signature);

            //add Claims
            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim(ClaimTypes.Role, "Admin"));
            claims.Add(new Claim(ClaimTypes.Role, "User"));

            claims.Add(new Claim("LoggenInUserId", "123"));
            ////Create token
            var token = new JwtSecurityToken(
                issuer: "smesk.in",
                audience: "readers",
                expires: DateTime.Now.AddHours(1),
                signingCredentials: signingCredintals,
                claims: claims
                );

            return(Ok(new JwtSecurityTokenHandler().WriteToken(token)));
        }
Exemplo n.º 20
0
    public AuthenticationTicket Unprotect(string protectedText)
    {
        if (string.IsNullOrWhiteSpace(protectedText))
        {
            throw new ArgumentNullException("protectedText");
        }

        var keyByteArray       = TextEncodings.Base64Url.Decode(AzureADConstants.AppKey);
        var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keyByteArray);
        var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
            securityKey,
            SecurityAlgorithms.HmacSha256Signature);
        var    handler          = new JwtSecurityTokenHandler();
        var    securityToken    = handler.ReadToken(protectedText);
        string rawToken         = ((JwtSecurityToken)securityToken).RawData;
        string audienceId       = AzureADConstants.GraphResourceId;
        var    validationParams = new TokenValidationParameters()
        {
            ValidateLifetime   = false,
            ValidAudience      = audienceId,
            ValidIssuer        = audienceId,
            ValidateIssuer     = false,
            ValidateAudience   = false,
            TokenDecryptionKey = securityKey,
            IssuerSigningKey   = securityKey
        };
        SecurityToken validatedToken;
        var           principal = handler.ValidateToken(rawToken, validationParams, out validatedToken);
        var           identity  = principal.Identities;

        return(new AuthenticationTicket(identity.First(), new AuthenticationProperties()));
    }
Exemplo n.º 21
0
        public static string GenerateServerToken(IAuthenticationManager auth)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            ClaimsIdentity identity = (ClaimsIdentity)auth.User.Identity;

            DateTime issuedAt = DateTime.UtcNow;
            DateTime expires  = DateTime.UtcNow.AddDays(1);

            string secret             = WebAppSettings.ServiceSecret;
            var    now                = DateTime.UtcNow;
            var    securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var    signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            var token = tokenHandler.CreateJwtSecurityToken(
                issuer: "http://noah-chatbot-web",
                audience: "http://noah-chatbot-service",
                subject: identity,
                notBefore: issuedAt,
                expires: expires,
                signingCredentials: signingCredentials);

            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 22
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));
        }
Exemplo n.º 23
0
        public string CreateToken(int userId, string username, string fullName, string checksumKey, System.DateTime expires, string roles)
        {
            //Set issued at date
            System.DateTime issuedAt = System.DateTime.UtcNow;

            //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token
            var tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.SerialNumber, userId.ToString()),
                new Claim(ClaimTypes.Name, username),
                new Claim(ClaimTypes.Surname, fullName),
                new Claim(ClaimTypes.Sid, checksumKey),
                new Claim(ClaimTypes.Expired, DVG.WIS.Utilities.Utils.DateTimeToUnixTime(expires).ToString()),
                new Claim(ClaimTypes.Role, roles),
            });

            string sec                = AppSettings.Instance.GetString(Const.JWTSecretKey);
            string issuer             = AppSettings.Instance.GetString(Const.JWTIssuer);
            string audience           = AppSettings.Instance.GetString(Const.JWTAudience);
            var    now                = DateTime.UtcNow;
            var    securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
            var    signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            //create the jwt
            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(issuer: issuer, audience: audience,
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
        // The Method is used to generate token for user when user is authentic.
        public string GenerateTokenForUser(string userName, int userId)
        {
            var signingKey         = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(communicationKey));
            var now                = DateTime.UtcNow;
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(signingKey,
                                                                                           System.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature,
                                                                                           System.IdentityModel.Tokens.SecurityAlgorithms.Sha256Digest);

            var claimsIdentity = new ClaimsIdentity(new List <Claim>()
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
            }, "Custom");

            var securityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
            {
                //AppliesToAddress = "http://www.example.com",
                //TokenIssuerName = "self",

                Issuer  = "self",
                Expires = DateTime.MaxValue,

                Subject            = claimsIdentity,
                SigningCredentials = signingCredentials,
                //Lifetime = new Lifetime(now, now.AddYears(1)),
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var plainToken            = tokenHandler.CreateToken(securityTokenDescriptor);
            var signedAndEncodedToken = tokenHandler.WriteToken(plainToken);

            return(signedAndEncodedToken);
        }
Exemplo n.º 25
0
        public static string GenerateToken(string user)
        {
            try
            {
                var     key    = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes("bqTg9m8QbckG5zUQVGPHAVKw52VJlKoHN0FhNNE9"));//quipserve@gbamnigeria
                var     creds  = new Microsoft.IdentityModel.Tokens.SigningCredentials(key, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);
                Claim[] claims = new Claim[]
                {
                    new Claim(ClaimTypes.Name, user)
                };
                var logged_token = new JwtSecurityToken(
                    issuer: "yourdomain.com",
                    audience: "yourdomain.com",
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(30),
                    signingCredentials: creds);

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

                return(token);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 26
0
        private string CreateToken(E_PERSONA pPersona)
        {
            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = DateTime.UtcNow.AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["JWT_EXPIRE_DAYS"]));
            //DateTime expires = DateTime.UtcNow.AddMinutes(Convert.ToInt32(ConfigurationManager.AppSettings["JWT_EXPIRE_DAYS"]));

            //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token
            var tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, pPersona.Nombre)
            });

            string sec                = ConfigurationManager.AppSettings["JWT_SECRET_KEY"];
            var    now                = DateTime.UtcNow;
            var    securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
            var    signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);
            //create the jwt
            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(issuer: ConfigurationManager.AppSettings["JWT_ISSUER_TOKEN"], audience: ConfigurationManager.AppSettings["JWT_AUDIENCE_TOKEN"],
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 27
0
        public string createAccessToken()
        {
            string secret   = TokenSecret;
            string issuer   = "http://localhost.local/";
            string audience = "http://localhost.local/";

            var claims = new[]
            {
                new Claim("name", this.email),
                new Claim("role", this.role)
            };

            var signingKey = new Microsoft.IdentityModel.
                             Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));

            var creds = new Microsoft.IdentityModel.
                        Tokens.SigningCredentials(signingKey,
                                                  Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);

            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                expires: DateTime.Now.AddMinutes(30),
                claims: claims,
                signingCredentials: creds
                );

            return(new System.IdentityModel.Tokens.
                   Jwt.JwtSecurityTokenHandler().WriteToken(token));
        }
Exemplo n.º 28
0
        public string Get(string cadena)
        {
            string[] data     = cadena.Split('|');
            User     userdata = new User();

            userdata.name     = data[0];
            userdata.password = data[1];
            string jsontext = JsonConvert.SerializeObject(userdata);

            jsontext = jsontext.Replace("\r", String.Empty);
            jsontext = jsontext.Replace("\n", String.Empty);
            var sKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(data[2]));
            var signingcredential = new Microsoft.IdentityModel.Tokens.SigningCredentials(sKey, "HS256");
            //HEADER
            var header = new JwtHeader(signingcredential);
            //PAYLOAD
            var payload = new JwtPayload();

            payload = JwtPayload.Deserialize(jsontext);
            var    secToken    = new JwtSecurityToken(header, payload);
            var    handler     = new JwtSecurityTokenHandler();
            var    tokenString = handler.WriteToken(secToken);
            string token       = tokenString;

            return(token);
        }
Exemplo n.º 29
0
        /// <summary>
        /// JWT is created
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        private string createToken(string username)
        {
            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = DateTime.UtcNow.AddDays(1);

            //http://stackoverflow.com/questions/18223868/how-to-encrypt-jwt-security-token
            var tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, username)
            });

            var now                = DateTime.UtcNow;
            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);

            //create the jwt
            var token = tokenHandler.CreateJwtSecurityToken(issuer: host, audience: host,
                                                            subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemplo n.º 30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static string CreateToken(string username)
        {
            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = DateTime.UtcNow.AddDays(7);

            var tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, username)
            });


            var now                = DateTime.UtcNow;
            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(ENC_KEY));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature);


            var token =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(issuer: ISSUER, audience: AUDIENCE,
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }