Beispiel #1
0
        public static string GenerateToken(Personas user, int expireMinutes = 20)
        {
            var secretKey     = ConfigurationManager.AppSettings["JWT_SECRET_KEY"];
            var audienceToken = ConfigurationManager.AppSettings["JWT_AUDIENCE_TOKEN"];
            var issuerToken   = ConfigurationManager.AppSettings["JWT_ISSUER_TOKEN"];
            var expireTime    = ConfigurationManager.AppSettings["JWT_EXPIRE_MINUTES"];

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

            // create a claimsIdentity
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.PerId.ToString()) });

            //se guarda auditoria de ingreso
            new AuditoriaBI().Save(user.PerId);
            // create token to the user
            var tokenHandler     = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var jwtSecurityToken = tokenHandler.CreateJwtSecurityToken(
                audience: audienceToken,
                issuer: issuerToken,
                subject: claimsIdentity,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddMinutes(Convert.ToInt32(expireTime)),
                signingCredentials: signingCredentials);

            var jwtTokenString = tokenHandler.WriteToken(jwtSecurityToken);

            return(jwtTokenString);
        }
Beispiel #2
0
        public static string GenerateTokenJwt(string UserName)
        {
            // Configuración del Token JWT
            var secretKey     = ConfigurationManager.AppSettings["JWT_SECRET_KEY"];
            var audienceToken = ConfigurationManager.AppSettings["JWT_AUDIENCE_TOKEN"];
            var issuerToken   = ConfigurationManager.AppSettings["JWT_ISSUER_TOKEN"];
            var expireTime    = ConfigurationManager.AppSettings["JWT_EXPIRE_MINUTES"];

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

            //Creamos una ClaimsIdentity
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, UserName) });

            //Generamos el Token para el usuario
            var tokenHandler     = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var jwtSecurityToken = tokenHandler.CreateJwtSecurityToken(
                audience: audienceToken,
                issuer: issuerToken,
                subject: claimsIdentity,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddMinutes(Convert.ToInt32(expireTime)),
                signingCredentials: signingCredentials);

            var jwtTokenString = tokenHandler.WriteToken(jwtSecurityToken);

            return(jwtTokenString);
        }
Beispiel #3
0
        public static string GenerateTokenJwt(string username)
        {
            var ctkn          = new ConfigurationTocken();
            var secretKey     = ctkn.SecretKey;
            var audienceToken = ctkn.host;
            var issuerToken   = ctkn.host;
            var expireTime    = ctkn.timeExpire;

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


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


            var tokenHandler     = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var jwtSecurityToken = tokenHandler.CreateJwtSecurityToken(
                audience: audienceToken,
                issuer: issuerToken,
                subject: claimsIdentity,
                notBefore: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddMinutes(Convert.ToInt32(expireTime)),
                signingCredentials: signingCredentials);

            var jwtTokenString = tokenHandler.WriteToken(jwtSecurityToken);

            return(jwtTokenString);
        }
        public static string GenerarJSONWebToken(string userInfo)
        {
            var secretKey     = Encoding.UTF8.GetBytes(_config["JWT:SecretKey"]);
            var audienceToken = _config["JWT:Audience"];
            var issuerToken   = _config["JWT:Issuer"]; //editor
            var expireTime    = _config["JWT:ExipireMinutes"];


            var securityKey = new SymmetricSecurityKey(secretKey);
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            //var token = new JwtSecurityToken(issuerToken, audienceToken, ca {

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

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

            var jwtTokenString = tokenHandler.WriteToken(jwtSecurityToken);

            return(jwtTokenString);
        }
        private string GenerateTokenJwt(UserApi user, string unicoIdentificador, DateTime time, DateTime expireTime)
        {
            // appsetting for Token JWT
            var secretKey     = EngineData.JwtKey;
            var audienceToken = EngineData.JwtAudience;
            var issuerToken   = EngineData.JwtIssuer;
            //
            var securityKey        = new SymmetricSecurityKey(Encoding.Default.GetBytes(secretKey));
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            // create a claimsIdentity
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] {
                new Claim(ClaimTypes.Name, user.Username),
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.GivenName, user.Password),
                new Claim(ClaimTypes.DateOfBirth, DateTime.Now.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);
        }
Beispiel #6
0
        /// <summary>
        /// Usado por el Authorization serve
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Protect(AuthenticationTicket data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            string securityProviderName = string.Empty;

            data.Properties.Dictionary.TryGetValue("securityProviderName", out securityProviderName);
            Fwk.Security.Identity.jwtSecurityProvider sec_provider = Fwk.Security.Identity.helper.get_secConfig().GetByName(securityProviderName);
            var    audienceToken        = sec_provider.audienceId;
            var    issuerToken          = sec_provider.issuer;
            string symmetricKeyAsBase64 = sec_provider.audienceSecret;
            var    keyByteArray         = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
            var    securityKey          = new SymmetricSecurityKey(keyByteArray);
            var    signingCredentials   = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
            //notBefore
            //var issuedAt = data.Properties.IssuedUtc;
            //var expireTime = data.Properties.ExpiresUtc;
            var expireTime = sec_provider.expires;//ConfigurationManager.AppSettings["JWT_EXPIRE_MINUTES"];

            //var token = new JwtSecurityToken(issuerToken, audienceToken, data.Identity.Claims, issuedAt.Value.UtcDateTime, expireTime.Value.UtcDateTime, signingCredentials);

            //var handler = new JwtSecurityTokenHandler();

            //var jwt = handler.WriteToken(token);

            #region otra manera de generar  el token
            // create a claimsIdentity
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, data.Properties.Dictionary["profesionalName"].ToString()) });

            claimsIdentity.AddClaim(new Claim(ClaimTypes.WindowsAccountName, data.Properties.Dictionary["userName"].ToString()));
            claimsIdentity.AddClaim(new Claim("userName", data.Properties.Dictionary["userName"].ToString()));
            claimsIdentity.AddClaim(new Claim("userId", data.Properties.Dictionary["userId"].ToString()));
            if (data.Properties.Dictionary.ContainsKey("email") != false)
            {
                claimsIdentity.AddClaim(new Claim("email", data.Properties.Dictionary["email"].ToString()));
            }
            //data.Identity.Claims("role");
            //Fwk.HelperFunctions.FormatFunctions.GetStringBuilderWhitSeparator(roles, ',').ToString()
            claimsIdentity.AddClaim(new Claim("roles", data.Properties.Dictionary["roles"].ToString()));

            var tokenHandler     = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var jwtSecurityToken = tokenHandler.CreateJwtSecurityToken(
                audience: audienceToken,
                issuer: issuerToken,
                subject: claimsIdentity,
                notBefore: DateTime.UtcNow,    //antes no
                issuedAt: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddMinutes(Convert.ToInt32(expireTime)),
                signingCredentials: signingCredentials);

            var jwtTokenString = tokenHandler.WriteToken(jwtSecurityToken);
            #endregion

            return(jwtTokenString);
        }
Beispiel #7
0
        public static string GenerateTokenJwt(Guid userId, string userName, string email, List <string> rolesArray, string securityProviderName)
        {
            var sec_provider = helper.get_secConfig().GetByName(securityProviderName);

            if (sec_provider == null)
            {
                throw new ArgumentNullException("No se encuentra configurado el proveedor (securityProviderName) en securityConfig.json");
            }

            string symmetricKeyAsBase64 = sec_provider.audienceSecret;
            var    keyByteArray         = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
            var    audienceToken        = sec_provider.audienceId;
            var    issuerToken          = sec_provider.issuer;
            var    securityKey          = new SymmetricSecurityKey(keyByteArray);

            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
            var expireTime         = 600;// ConfigurationManager.AppSettings["JWT_EXPIRE_MINUTES"];


            // create a claimsIdentity
            ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "") });

            //claimsIdentity.AddClaim(new Claim(ClaimTypes.WindowsAccountName, username));
            claimsIdentity.AddClaim(new Claim("userName", userName));
            claimsIdentity.AddClaim(new Claim("userId", userId.ToString()));
            if (!string.IsNullOrEmpty(email))
            {
                claimsIdentity.AddClaim(new Claim("email", email));
            }

            if (rolesArray != null && rolesArray.Count() != 0)
            {
                var roles = Fwk.HelperFunctions.FormatFunctions.GetStringBuilderWhitSeparator(rolesArray, ',').ToString();
                claimsIdentity.AddClaim(new Claim("roles", roles.ToString()));
            }


            // create token to the user
            var tokenHandler     = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var jwtSecurityToken = tokenHandler.CreateJwtSecurityToken(
                audience: audienceToken,
                issuer: issuerToken,
                subject: claimsIdentity,
                notBefore: DateTime.UtcNow.AddMinutes(-10), //antes no para System.IdentityModel.Tokens. es ValidFrom
                issuedAt: DateTime.UtcNow,
                expires: DateTime.UtcNow.AddMinutes(Convert.ToInt32(expireTime)),
                signingCredentials: signingCredentials);

            var jwtTokenString = tokenHandler.WriteToken(jwtSecurityToken);

            return(jwtTokenString);
        }
Beispiel #8
0
        /// <summary>
        /// Retorna informacion basada en el dominio
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static string GenerateTokenJwt_test(string userName)
        {
            // appsetting for Token JWT


            var secretKey = apiAppSettings.serverSettings.apiConfig.api_secretKey;
            // audiencia quien genera el tocken
            var audienceToken = apiAppSettings.serverSettings.apiConfig.api_audienceToken;
            //identifica quien consume y uusa el tocken : El cliente
            var issuerToken = apiAppSettings.serverSettings.apiConfig.api_issuerToken;
            //hora de caducidad a partir de la cual el JWT NO DEBE ser aceptado para su procesamiento.
            var expireTime = apiAppSettings.serverSettings.apiConfig.api_expireTime;

            var securityKey        = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(secretKey));
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);

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

            claimsIdentity.AddClaim(new Claim(ClaimTypes.WindowsAccountName, userName));

            //if (aDUser != null)
            //{
            //    claimsIdentity.AddClaim(new Claim("FirstName", userName));
            //    claimsIdentity.AddClaim(new Claim("UserAccountControl", aDUser.UserAccountControl));
            //    claimsIdentity.AddClaim(new Claim("Department", aDUser.Department));
            //    claimsIdentity.AddClaim(new Claim("LastName", aDUser.LastName));
            //    claimsIdentity.AddClaim(new Claim("LoginNameWithDomain", aDUser.LoginNameWithDomain));
            //    claimsIdentity.AddClaim(new Claim("EmailAddress", aDUser.EmailAddress));
            //}
            //if (groups != null && groups.Count != 0)
            //{
            //    var roles = Fwk.HelperFunctions.FormatFunctions.GetStringBuilderWhitSeparator(groups, ',').ToString();
            //    claimsIdentity.AddClaim(new Claim("groups", roles.ToString()));
            //}



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

            var jwtTokenString = tokenHandler.WriteToken(jwtSecurityToken);

            return(jwtTokenString);
        }
Beispiel #9
0
        public TokenDto BuildToken(UsuarioDto pUsuarioLogin)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, pUsuarioLogin.UsuarioId),
                new Claim("vDataUsuario", JsonConvert.SerializeObject(pUsuarioLogin)),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var claimsIdentity = new ClaimsIdentity(claims);

            //TODO: appsetting for Demo JWT - protect correctly this settings
            var secretKey     = _configuration["JWT:key"];
            var audienceToken = _configuration["JWT:Audience_Token"];
            var issuerToken   = _configuration["JWT:Issuer_Token"];
            var expireTime    = _configuration["JWT:Expire_Minutes"];

            var securityKey        = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(secretKey));
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
            var expiration         = DateTime.UtcNow.AddMinutes(Convert.ToInt32(expireTime));

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

            return(new TokenDto()
            {
                Token = tokenHandler.WriteToken(jwtSecurityToken),
                Expiration = expiration
            });
        }