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)));
            //return Ok("hello from api");
        }
Exemple #2
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);
        }
Exemple #3
0
        public JwtSecurityToken MintToken(List <Claim> claims, string audience, DateTime expirationDateTime)
        {
            string forwardedFor = null;

            // add issuer with forwarded for address if exists (added by reverse proxy)
            if (this.httpContextAccessor.HttpContext.Request.Headers.Where(t => t.Key == "X-Forwarded-For").Count() > 0)
            {
                forwardedFor = this.httpContextAccessor.HttpContext.Request.Headers.Where(t => t.Key == "X-Forwarded-For").FirstOrDefault().Value
                               .First();
                this.logger.LogInformation("Added issuer with X-Forwarded-For address.");
            }

            // Create Security key  using private key above:
            // not that latest version of JWT using Microsoft namespace instead of System
            var securityKey =
                new RsaSecurityKey(this.rsaHelpers.DecodeRsa(this.config.IdentityGatewayService.PrivateKey));

            // Also note that securityKey length should be >256b
            // so you have to make sure that your private key has a proper length
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: forwardedFor ?? "https://" + this.httpContextAccessor.HttpContext.Request.Host.ToString() + "/",
                audience: audience,
                expires: expirationDateTime.ToUniversalTime(),
                claims: claims.ToArray(),
                signingCredentials: credentials);

            return(token);
        }
Exemple #4
0
        public ViewResult GenerateToken(string jsontext, string key, string algorithm)
        {
            try
            {
                jsontext = jsontext.Replace("\r", String.Empty);
                jsontext = jsontext.Replace("\n", String.Empty);
                var json = JsonConvert.DeserializeObject(jsontext);
                //KEY (your - 256 - bit - secret )
                var verificarion = Encoding.UTF8.GetBytes(key);

                var sKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
                var signingcredential = new Microsoft.IdentityModel.Tokens.SigningCredentials(sKey, algorithm);
                //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);
                AlgorithmModel model       = new AlgorithmModel();
                model.token = tokenString;
                return(View(model));
            }
            catch
            {
                ViewBag.Message = "Please enter a valid key";
                return(View(new AlgorithmModel()));
            }
        }
Exemple #5
0
        public string CreateToken(Dictionary <string, string> claims)
        {
            //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(
                claims.Select(d => new Claim(d.Key, d.Value))
                );

            string sec                = this.JwtKey;
            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: "http://localhost:80", audience: "http://localhost:80",
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
        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),
                //new Claim(ClaimTypes.Pol, 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:50191", audience: "http://localhost:50191",
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemple #7
0
        public string CriarToken(string nome, string email)
        {
            // Definindo uma Const Key que deve ser uma chave secreta privada armazenada em algum lugar seguro
            string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b372742           9090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

            // Criando a chave de segurança usando a chave privada acima:
            // não a versão mais recente do JWT usando o namespace Microsoft em vez do sistema
            var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));

            // Observe também que o comprimento da segurança deve ser > 256b
            // então você deve ter certeza de que sua chave privada tenha um comprimento adequado
            //
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
                                  (securityKey, SecurityAlgorithms.HmacSha256Signature);

            //  Finalmente criando um Token
            var header = new JwtHeader(credentials);

            // Alguns PayLoad que contêm informações sobre o usuário
            var payload = new JwtPayload
            {
                { "Nome ", nome },
                { "Email", email },
            };

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

            // Token em String para que você possa usá-lo em seu usuário
            var tokenString = handler.WriteToken(secToken);

            // Retornando token
            return(tokenString);
        }
Exemple #8
0
        public static string GenerateToken(string username, DateTime expiredTime)
        {
            // Create Security key  using private key above:
            // not that latest version of JWT using Microsoft namespace instead of System
            var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));

            // so you have to make sure that your private key has a proper length
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
            //  Finally create a Token
            var header = new JwtHeader(credentials);

            //Some PayLoad that contain information about the  customer
            var payload = new JwtPayload
            {
                { username, expiredTime.ToString() },
                { "scope", "http://dummy.com/" },
            };

            var secToken = new JwtSecurityToken(header, payload);
            var handler  = new JwtSecurityTokenHandler();

            // Token to String so you can use it in your client
            var tokenString = handler.WriteToken(secToken);

            return(tokenString);
        }
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var userFromRepo = await _repo.Login(userForLoginDto.UserName.ToLower(), userForLoginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.UserName)
            };

            var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey
                          (Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new Microsoft.IdentityModel.Tokens.SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

            var tokenDesk = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDesk);

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
Exemple #10
0
        private string GenerateTokenJwt(UserApi user, string unicoIdentificador, DateTime time, DateTime expireTime)
        {
            // appsetting for Token JWT
            var secretKey     = EngineData.SecretKey;
            var audienceToken = EngineData.Audience;
            var issuerToken   = EngineData.Issuer;

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

            // create a claimsIdentity
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.Name, user.Email),
                new Claim(ClaimTypes.DateOfBirth, user.CreateDate.ToString()),
                new Claim("HoraToken", DateTime.UtcNow.ToString()),
                new Claim(ClaimTypes.Anonymous, unicoIdentificador)
            });

            // create token to the user
            var tokenHandler     = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var jwtSecurityToken = tokenHandler.CreateJwtSecurityToken(
                audience: audienceToken,
                issuer: issuerToken,
                subject: claimsIdentity,
                notBefore: time,
                expires: expireTime,
                signingCredentials: signingCredentials);

            string token = tokenHandler.WriteToken(jwtSecurityToken);

            return(token);
        }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        WatchRef.ServiceSoapClient client = new WatchRef.ServiceSoapClient();
        WatchRef.AuthControl       auth   = new WatchRef.AuthControl();

        string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8basdcvb9090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

        var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
        var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
        var header      = new JwtHeader(credentials);

        var payload = new JwtPayload
        {
            { "Username", txtUsername.Text },
            { "Password", txtPassword.Text },
        };

        var secToken = new JwtSecurityToken(header, payload);
        var handler  = new JwtSecurityTokenHandler();

        auth.Token = handler.WriteToken(secToken);

        client.Login(auth);
        Response.Redirect("TumSaatler.aspx");
    }
        /// <summary>
        /// Creates a JWT using the reseller / partners impersonation token settings and the customers account id
        /// </summary>
        /// <param name="impersonatedAccountId">The account id of the customer you want to impersonate</param>
        /// <param name="resellerId">The account id for the reseller / partner</param>
        /// <param name="issuer">Your unique JWT issuer you provided to the dotdigital CPaaS team</param>
        /// <param name="secret">Your unique JWT secret you provided to the dotdigital CPaaS team</param>
        /// <returns></returns>
        private static string CreateImpersonationToken(int impersonatedAccountId, int resellerId, string issuer, string secret)
        {
            // Create Security key using the secret
            var securityKey        = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
                                         (securityKey, SecurityAlgorithms.HmacSha256);

            //  Create a token
            var header = new JwtHeader(signingCredentials);

            // Create the JWT payload including the details on the customer to impersonate.
            var payload = new JwtPayload
            {
                { "accountId", impersonatedAccountId },
                { "resellerId", RESELLER_ACCOUNT_ID },
                { "aud", "https://api.comapi.com" },
                { "iss", issuer },
                { "exp", (long)(DateTime.UtcNow.AddMinutes(115) - new DateTime(1970, 1, 1)).TotalSeconds } // Expires 115 minutes in the the future based on UTC
            };

            var secToken = new JwtSecurityToken(header, payload);
            var handler  = new JwtSecurityTokenHandler();

            // Export the JWT as a string
            return(handler.WriteToken(secToken));
        }
Exemple #13
0
        static string GenerateJWT(RSA rsa)
        {
            //var securityKey = new Microsoft.IdentityModel.Tokens.X509SecurityKey(GetByThumbprint("YOUR-CERT-THUMBPRINT-HERE"));
            //var securityKey = new Microsoft.IdentityModel.Tokens.X509SecurityKey(new X509Certificate2(Convert.FromBase64String("MIIDBTCCAe2gAwIBAgIQbiJkXaenk61AKixVocnLRTANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDEyJhY2NvdW50cy5hY2Nlc3Njb250cm9sLndpbmRvd3MubmV0MB4XDTE5MTAwNTAwMDAwMFoXDTI0MTAwNDAwMDAwMFowLTErMCkGA1UEAxMiYWNjb3VudHMuYWNjZXNzY29udHJvbC53aW5kb3dzLm5ldDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ2H9Y6Z+3BXUCtlbmXr6H5owYy15XTl3vdpOZLUkk4OV9LMsB1phjNp+wgl28eAgrNNfu4BTVlHdR9x6NTrSiIapsYjzzEz4mOmRh1Bw5tJxit0VEGn00/ZENniTjgeEFYgDHYwjrfZQ6dERBFiw1OQb2IG5f3KLtx92lUXeIZ7ZvTaPkUpc4Qd6wQZmWgzPqWFocRsJATGyZzXiiXQUrc9cVqm1bws3P0lFBcqNtv+AKDYKT5IRYLsyCkueQC9R6LUCsZVD7bVIkeQuA3iehJKIEAlk/e3j5E4VaCRs642ajb/z9kByTl2xL2k0AeZGc8/Rcy7SQn0LBcJNZGp/SMCAwEAAaMhMB8wHQYDVR0OBBYEFOLhl3BDPLNVYDe38Dp9JbUmd4kKMA0GCSqGSIb3DQEBCwUAA4IBAQAN4XwyqYfVdMl0xEbBMa/OzSfIbuI4pQWWpl3isKRAyhXezAX1t/0532LsIcYkwubLifnjHHqo4x1jnVqkvkFjcPZ12kjs/q5d1L0LxlQST/Uqwm/9/AeTzRZXtUKNBWBOWy9gmw9DEH593sNYytGAEerbWhCR3agUxsnQSYTTwg4K9cSqLWzHX5Kcz0NLCGwLx015/Jc7HwPJnp7q5Bo0O0VfhomDiEctIFfzqE5x9T9ZTUSWUDn3J7DYzs2L1pDrOQaNs/YEkXsKDP1j4tOFyxic6OvjQ10Yugjo5jg1uWoxeU8pI0BxY6sj2GZt3Ynzev2bZqmj68y0I9Z+NTZo")));

            var securityKey = new Microsoft.IdentityModel.Tokens.RsaSecurityKey(rsa);

            var mod = rsa.ExportParameters(includePrivateParameters: false).Modulus;

            // The "key ID" used for RSA key in GPG/PGP is the last 8 hex digits (4 bytes) of the modulus of the key.
            securityKey.KeyId = Base64UrlEncode(mod, mod.Length - 4, 4);

            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, "RS256");

            var header = new JwtHeader(credentials);

            var payload = new JwtPayload
            {
                { "aud", "https://management.core.windows.net/" },
                { "iss", "https://sts.windows.net/72f988bf-86f1-41af-91ab-2d7cd011db47/" },
                { "exp", (Int32)(new DateTime(2019, 12, 9, 0, 0, 0, DateTimeKind.Utc).Subtract(new DateTime(1970, 1, 1))).TotalSeconds },
                { "iat", (Int32)(new DateTime(2019, 12, 7, 0, 0, 0, DateTimeKind.Utc).Subtract(new DateTime(1970, 1, 1))).TotalSeconds }
            };

            var token = new JwtSecurityToken(header, payload);

            var input     = string.Join(".", new[] { token.EncodedHeader, token.EncodedPayload });
            var signature = SignRS256(input, rsa);

            return(string.Join(".", new[] { input, Base64UrlEncoder.Encode(signature) }));
        }
Exemple #14
0
        /// <summary>
        /// Builds a Json Web Token from the certificate for a specific user to be used in the webview.
        /// </summary>
        /// <param name="x509Certificate2">The certificate PFX</param>
        /// <param name="customerUserId">The customer user id</param>
        /// <param name="apiEndpoint">Endpoint URL called by the WebView</param>
        /// <returns>A JSON Web Token</returns>
        public static string BuildWebViewDefaultToken(X509Certificate2 x509Certificate2, string customerUserId, string apiEndpoint = "https://sca-multitenant.securibox.eu")
        {
            Uri endpointUri = new Uri(apiEndpoint);
            var iss         = x509Certificate2.Issuer;
            var nbf         = DateTime.UtcNow.AddMinutes(-1);
            var exp         = DateTime.UtcNow.AddHours(5);
            var aud         = endpointUri.Scheme + "://" + endpointUri.Host;

            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim("sub", endpointUri.Host));
            claims.Add(new Claim("jti", Guid.NewGuid().ToString("D")));
            claims.Add(new Claim("uid", customerUserId));

            SigningCredentials credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
                new X509SecurityKey(x509Certificate2),
                SecurityAlgorithms.RsaSha256Signature,
                SecurityAlgorithms.Sha256Digest
                );

            var header           = new JwtHeader(credentials);
            var payload          = new JwtPayload(issuer: iss, audience: aud, claims: claims, notBefore: nbf, expires: exp);
            var jwtSecurityToken = new JwtSecurityToken(header, payload);

            jwtSecurityToken.Header.Remove("kid");
            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            return(handler.WriteToken(jwtSecurityToken));
        }
        public string GenerateToken(DateTime date, string user, TimeSpan time)
        {
            var expire = date.Add(time);
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(
                    JwtRegisteredClaimNames.Iat,
                    new DateTimeOffset(date).ToUniversalTime().ToUnixTimeSeconds().ToString(),
                    ClaimValueTypes.Integer64
                    )
            };

            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
                new SymmetricSecurityKey(Encoding.ASCII.GetBytes(GlobalSettings.SYS_SINGINKEY)),
                SecurityAlgorithms.HmacSha256Signature
                );

            var jwt = new JwtSecurityToken(
                issuer: GlobalSettings.SYS_ISSUER,
                audience: GlobalSettings.SYS_AUDIENCE,
                claims: claims,
                notBefore: date,
                expires: expire,
                signingCredentials: signingCredentials
                );

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
        public static string GenerateToken <T>(string key, T information)
        {
            // Create Security key  using private key above:
            // not that latest version of JWT using Microsoft namespace instead of System
            var securityKey = new Microsoft
                              .IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));

            // Also note that securityKey length should be >256b
            // so you have to make sure that your private key has a proper length
            //
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
                                  (securityKey, SecurityAlgorithms.HmacSha256Signature);

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

            //Some PayLoad that contain information about the  customer
            var payload = new JwtPayload {
                { information.GetType().Name, Newtonsoft.Json.JsonConvert.SerializeObject(information) }
            };

            var secToken = new JwtSecurityToken(header, payload);
            var handler  = new JwtSecurityTokenHandler();

            // Token to String so you can use it in your client
            return(handler.WriteToken(secToken));
        }
Exemple #17
0
        private string CreateToken(string username)
        {
            string sec = ConfigurationManager.AppSettings["jwtKey"];

            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = DateTime.UtcNow.AddDays(int.Parse(ConfigurationManager.AppSettings["jwtValidity"]));

            //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 =
                (JwtSecurityToken)
                tokenHandler.CreateJwtSecurityToken(issuer: ConfigurationManager.AppSettings["jwtIssuer"],
                                                    audience: ConfigurationManager.AppSettings["jwtIssuer"],
                                                    subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
        public string genToken(string usn, string Permit)
        {
            string key = " WarakornT.!#~ WarakornT.!~% WarakornT.!@~ WarakornT.!!~ WarakornT.!&~ WarakornT.!~~!@#!";

            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
            {
                { "name", usn },
                { "role", Permit } // 0 = not permit, 1 = admin, 2 = RD, 3 = Extra user
            };

            var secToken = new JwtSecurityToken(header, payload);
            var handler  = new JwtSecurityTokenHandler();

            var tokenString = handler.WriteToken(secToken);

            var token = handler.ReadJwtToken(tokenString);

            return(token.RawData.ToString());
        }
        public string GenerateToken(DateTime date, string user, TimeSpan validDate)
        {
            var expire = date.Add(validDate);

            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, user),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(
                    JwtRegisteredClaimNames.Iat,
                    new DateTimeOffset(date).ToUniversalTime().ToUnixTimeSeconds().ToString(),
                    ClaimValueTypes.Integer64
                    ),
                new Claim("roles", "Cliente"),
                new Claim("roles", "Administrador")
            };

            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
                new SymmetricSecurityKey(Encoding.ASCII.GetBytes("aaAAaaAA1234sdsdsdsddferrtrfgfgfrgfgfgdgfdfdf")),
                SecurityAlgorithms.HmacSha256Signature
                );

            var jwt = new JwtSecurityToken(
                issuer: "Ejemplo",
                audience: "Public",
                claims: claims,
                notBefore: date,
                expires: expire,
                signingCredentials: signingCredentials
                );

            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
        public void SB()
        {
            var keyByteArray = System.Text.Encoding.ASCII.GetBytes("qMCdFDQuF23RV1Y-1Gq9L3cF3VmuFwVbam4fMTdAfcc");

            var audienceid = "414e1927a3884f68abc79f7283837fd2";

            var issuer = "http://www.abc.com";

            var securityKey = new SymmetricSecurityKey(keyByteArray);

            var sigigCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

            JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();

            JwtSecurityToken token = handler.CreateJwtSecurityToken(issuer, audienceid, null, DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromHours(1), DateTime.UtcNow + TimeSpan.FromHours(1), sigigCredentials);

            string jwt = handler.WriteToken(token);


            TokenValidationParameters tokenValidationParameters = new TokenValidationParameters()
            {
                IssuerSigningKey = securityKey,
                ValidAudience    = audienceid,
                ValidIssuer      = issuer
            };

            SecurityToken securityToken = null;

            handler.ValidateToken(jwt, tokenValidationParameters, out securityToken);

            bool istrue = securityToken.Issuer == issuer ? true : false;

            Assert.True(istrue);
        }
Exemple #21
0
        public static string GenerateToken(string userId, string username, string firstname, string lastname)
        {
            //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),
                new Claim("userid", userId),
                new Claim("username", username),
                new Claim("firstname", firstname),
                new Claim("lastname", lastname),
                //TODO:add other claim
            });


            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: "AuthAPI", audience: "MvcWebClient",
                                                            subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
            var tokenString = tokenHandler.WriteToken(token);

            return(tokenString);
        }
Exemple #22
0
        public ActionResult <string> Token()
        {
            //var header = Request.Headers["Authorization"];
            //var credValue = header.ToString().Substring("Basci ".Length).Trim();
            //var userNameAndPassenc = Encoding.UTF8.GetString(Convert.FromBase64String(credValue));
            //var userNameAndPass = userNameAndPassenc.Split(":");
            var claims = new[] {
                new Claim(ClaimTypes.Name, "username")
            };
            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(AppConstants.JWTBearerToken.Token));

            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
                key, SecurityAlgorithms.HmacSha256Signature);
            var tokennString = new JwtSecurityToken(
                issuer: AppConstants.JWTBearerToken.Issuer,
                audience: AppConstants.JWTBearerToken.Audience,
                expires: DateTime.Now.AddMinutes(AppConstants.JWTBearerToken.Expires),
                claims: claims,
                signingCredentials: signingCredentials
                );

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

            return(token);
        }
Exemple #23
0
        public virtual string JwtPayloadToToken(JwtPayload Payload)
        {
            var ByteLenght = System.Text.ASCIIEncoding.Unicode.GetByteCount(this.Key);

            if (ByteLenght < 256)
            {
                throw new ArgumentException($"the byte count of the key should be greater than 256 bytes,the current length is:{ByteLenght}");
            }

            // Create Security key  using private key above:
            // not that latest version of JWT using Microsoft namespace instead of System
            var SecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.Key));

            // securityKey length MUST be >256 based on the length of the key
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256Signature);

            // Lets create the token
            var header = new JwtHeader(credentials);

            // Lets add the header and payload
            JwtSecurityToken SecurityToken = new JwtSecurityToken(header, Payload);

            var Handler = new JwtSecurityTokenHandler();

            // Convert the token to string and send it to your client
            string TokenString = Handler.WriteToken(SecurityToken);

            return(TokenString);
        }
Exemple #24
0
        private JwtPayload ReadToken(string tokenString)
        {
            // Define const Key this should be private secret key  stored in some safe place
            string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

            // Create Security key  using private key above:
            // not that latest version of JWT using Microsoft namespace instead of System
            var securityKey = new Microsoft
                              .IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));

            // Also note that securityKey length should be >256b
            // so you have to make sure that your private key has a proper length
            //
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
                                  (securityKey, SecurityAlgorithms.HmacSha256Signature);

            //
            var handler = new JwtSecurityTokenHandler();

            // And finally when  you received token from client
            // you can  either validate it or try to  read
            var token = handler.ReadJwtToken(tokenString);

            return(token.Payload);
        }
        private string createToken(TurfUser userInfo)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            //create a identity and add claims to the user which we want to log in
            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username),
                new Claim(JwtRegisteredClaimNames.Email, userInfo.Email),
                new Claim("UserType", userInfo.UserType.ToString()),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

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


            var token = new JwtSecurityToken(issuer: "http://localhost:50191",
                                             audience: "http://localhost:50191",
                                             claims,
                                             expires: DateTime.Now.AddMinutes(120),
                                             signingCredentials: signingCredentials);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }
        /// <summary>
        /// Creates a new JWT Token for securing endpoints
        /// </summary>
        /// <returns>A string containing a new JWT token</returns>
        public static string GenerateJwtToken()
        {
            var credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials
                                  (SIGNING_KEY, SecurityAlgorithms.HmacSha256);

            var header = new JwtHeader(credentials);

            // set the number in AddMinutes to set session length
            DateTime expires = DateTime.UtcNow.AddMinutes(10);
            // convert to unix seconds
            int ts = (int)(expires - new DateTime(1970, 1, 1)).TotalSeconds;

            var payload = new JwtPayload
            {
                { "sub", "testSubject" },
                { "Name", "Tom" },
                { "email", "*****@*****.**" },
                { "exp", ts },
                { "iss", "https://localhost:44321" },
                { "aud", "https://localhost:44321" }
            };

            var secToken = new JwtSecurityToken(header, payload);
            var handler  = new JwtSecurityTokenHandler();

            return(handler.WriteToken(secToken));
        }
Exemple #27
0
        public string ReturnJWT(DateTime expirationDate, int permissionId_i, int userId_i)
        {
            // Create Security key  using private key above:
            // not that latest version of JWT using Microsoft namespace instead of System
            SymmetricSecurityKey securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(_key));

            // Also note that securityKey length should be >256b
            // so you have to make sure that your private key has a proper length
            SigningCredentials credentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

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

            // Some PayLoad that contain information about the  customer
            JwtPayload payload = new JwtPayload
            {
                { "expirationDate", expirationDate },
                { "permissionId", permissionId_i },
                { "userId", userId_i }
            };

            JwtSecurityToken        secToken = new JwtSecurityToken(header, payload);
            JwtSecurityTokenHandler handler  = new JwtSecurityTokenHandler();

            // Token to String so you can use it in your client
            ErrInfLogger.LockInstance.InfoLog("Token created.");
            return(handler.WriteToken(secToken));
        }
Exemple #28
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 signingKey = new HmacSigningCredentials(keyByteArray);

            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 handler = new JwtSecurityTokenHandler
            {
                MapInboundClaims = false
            };
            // we are clearing the map of the rename of the properties. see https://mderriey.com/2019/06/23/where-are-my-jwt-claims/ for details
            //handler.InboundClaimTypeMap.Clear();

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

            var jwt = handler.WriteToken(token);

            return(jwt);
        }
Exemple #29
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 signingKey = 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, signingKey);

            var handler = new JwtSecurityTokenHandler();

            var jwt = handler.WriteToken(token);

            return(jwt);
        }
Exemple #30
0
        public string GenerateToken(List <Claim> claims)
        {
            //Set issued at date
            DateTime issuedAt = DateTime.UtcNow;
            //set the time when it expires
            DateTime expires = DateTime.UtcNow.AddDays(_appSettings.ExpireDay);

            //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(claims);



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


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

            return(tokenString);
        }