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);
        }
예제 #2
0
        public static string Gen(string username)
        {
            var tokenHandler         = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            ConfigurationTocken ctkn = new ConfigurationTocken();
            var key             = System.Text.Encoding.ASCII.GetBytes(ctkn.SecretKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, username) }),
                Expires            = DateTime.UtcNow.AddMinutes(ctkn.timeExpire),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);
            //var userClaims = await _userManager.GetRolesAsync(user);
            List <Claim> claims = new List <Claim>();

            claims.Add(new Claim(JwtRegisteredClaimNames.Sub, username));
            claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
            claims.Add(new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64));
            var jwt = new JwtSecurityToken(
                claims: claims);
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(encodedJwt);
        }
예제 #3
0
        private string GenerateJwtToken(string userId, string username)
        {
            // Function handles create the JWT token based on the provided
            // user ID and username

            // Generate the user claims by User Id & Name
            Claim[] jwtClaims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userId),
                new Claim(ClaimTypes.Name, username)
            };

            // Generate the Key, using the App token
            SymmetricSecurityKey jwtKey = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            // Generate the creds
            SigningCredentials credentials = new SigningCredentials(jwtKey, SecurityAlgorithms.HmacSha512Signature);

            // Create a  JWT Desc object
            SecurityTokenDescriptor jwtDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(jwtClaims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = credentials
            };

            System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler jwtHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            // Finally create the JWT token & return it
            SecurityToken jwtToken = jwtHandler.CreateToken(jwtDescriptor);

            return(jwtHandler.WriteToken(jwtToken));
        }
예제 #4
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);
        }
예제 #5
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);
        }
예제 #6
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);
        }
예제 #7
0
        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);
        }
예제 #8
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);
        }
예제 #9
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);
        }
예제 #10
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);
        }
예제 #11
0
        private string GenerateJwtToken(User user)
        {
            var tokenhandler    = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var keys            = System.Text.Encoding.ASCII.GetBytes(jwtKey);
            var tokendescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }),
                Expires            = DateTime.UtcNow.AddHours(24),
                SigningCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(keys),
                                                                                           Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256Signature)
            };
            var tokens = tokenhandler.CreateToken(tokendescriptor);

            return(tokenhandler.WriteToken(tokens));
        }
        public string GenerateJwtToken(User user)
        {
            var tokenHandler    = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes("[SECRET USED TO SIGN AND VERIFY JWT TOKENS, IT CAN BE ANY STRING]");
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new List <Claim>()
                {
                    new Claim(nameof(User.Id).ToLowerInvariant(), user.Id.ToString()),
                    new Claim(nameof(User.Name).ToLowerInvariant(), user.Name)
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
예제 #13
0
        /// <summary>
        /// Generate user specific JWT string
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public static string GenerateEncodedJWT(OCM.API.Common.Model.User user)
        {
            var claims = new List <System.Security.Claims.Claim>();

            claims.Add(new Claim("UserID", user.ID.ToString()));
            claims.Add(new Claim("nonce", user.CurrentSessionToken.ToString()));


            var signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.ASCII.GetBytes(user.CurrentSessionToken));

            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
            var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(ISSUER, AUDIENCE, claims, DateTime.UtcNow, DateTime.UtcNow.AddMonths(1), signingCredentials);

            var handler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();

            var jwt = handler.WriteToken(token);

            return(jwt);
        }
        public static ClaimsPrincipal ValidateJwtToken(string jwtToken)
        {
            var tokenHandler = new JwtSecurityTokenHandler()
            {
                RequireExpirationTime = true
            };
            var now                = DateTime.UtcNow;
            var securityKey        = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.Default.GetBytes(jwtToken));
            var signingCredentials = new Microsoft.IdentityModel.Tokens.SigningCredentials(
                securityKey,
                SecurityAlgorithms.HmacSha256Signature);
            var header = new JwtHeader(signingCredentials);

            var payload = new JwtPayload
            {
                { "access_token", response },
                { "scope", "Read Data Write Data" },
                //{ "created","1510553155114"},
                //{"jti","2640942c-892c-409a-9ca8-959a538c2128"},
            };

            var secToken = new JwtSecurityToken(header, payload);

            var handler     = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var tokenString = handler.WriteToken(secToken);

            var readToken = handler.ReadJwtToken(generatedToken);
            var rawHeader = readToken.RawHeader;

            var headers = Base64UrlEncoder.Decode(rawHeader);

            var myClaims = readToken.Claims;
            var claims   = Base64UrlEncoder.Decode(myClaims.ToString());

            //var payload = header + "." + claims;

            //var signature = Base64UrlEncoder.Decode(HMACSHA256(payload, CLIENT_SECRET));

            //var encodedJWT = payload + "." + signature;

            return(null);
        }
예제 #15
0
        public Employee Authenticate(string username, string password)//User
        {
            var employee = _unitOfWork.EmployeeRepository.GetAll().SingleOrDefault(x => x.UserName == username && DecodePasswordFrom64(x.Password) == password);

            // return null if user not found
            if (employee == null)
            {
                return(null);
            }

            var employeeRoleIds = employee.EmployeeRoles.Select(r => (long)r.RoleId).ToList();
            var roles           = _unitOfWork.RoleRepository.GetRoles(employeeRoleIds.ToArray());//.Where(r => userRoleIds.Contains(r.Id));


            var role = employee.EmployeeRoles.FirstOrDefault().Roles;
            // authentication successful so generate jwt token
            var tokenHandler    = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.JWT_Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, employee.Id.ToString()),
                    new Claim(ClaimTypes.Role, role.Id.ToString())
                }),
                //Expires = DateTime.UtcNow.AddDays(7),
                Expires            = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token         = tokenHandler.CreateToken(tokenDescriptor);
            var tokenToBeSent = tokenHandler.WriteToken(token);

            //user.Token = tokenHandler.WriteToken(token);
            // remove password before returning
            //user.Password = null;

            employee.Token    = tokenToBeSent.ToString();
            employee.Password = null;

            return(employee);
            //return tokenToBeSent;
        }
예제 #16
0
        static string GetJwtFromTokenIssuer()
        {
            byte[] key = Convert.FromBase64String("80ssGCKB931r2r8Lm3om1SIt5YY05yBZ34pna3+dYi8=");

            var symmetricKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(key);
            //var symmetricKey = new InMemorySymmetricSecurityKey(key);

            var signingCredentials =
                new Microsoft.IdentityModel.Tokens.SigningCredentials(symmetricKey, SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);

            var claimsIdentity = new System.Security.Claims.ClaimsIdentity(new System.Security.Claims.Claim[]
            {
                new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Johnny")
            });

            var descriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor
            {
                Subject            = claimsIdentity,
                Audience           = "http://localhost:5000/api",
                Issuer             = "http://authzserver.demo",
                Expires            = DateTime.UtcNow.AddMinutes(1),
                SigningCredentials = signingCredentials
            };

            //var descriptor = new SecurityTokenDescriptor()
            //{
            //    TokenIssuerName = "http://authzserver.demo",
            //    AppliesToAddress = "http://localhost:5000/api",
            //    Lifetime = new System.IdentityModel.Protocols.WSTrust.Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(1)),
            //    SigningCredentials = signingCredentials,
            //    Subject = new System.Security.Claims.ClaimsIdentity(new System.Security.Claims.Claim[]
            //    {
            //        new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, "Johnny")
            //    })
            //};

            var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(descriptor);

            return(tokenHandler.WriteToken(token));
        }
예제 #17
0
        private void CreateToken()
        {
            var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var now          = DateTime.UtcNow;
            var apiSecret    = "adMvFxlEqySjPJQnzcTWm4I97oQz65khAlji";

            byte[] symmetricKey = System.Text.Encoding.ASCII.GetBytes(apiSecret);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Issuer = "*****@*****.**",


                Expires = now.AddSeconds(3600),

                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(symmetricKey), SecurityAlgorithms.RsaSha256),
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            var tokenString = tokenHandler.WriteToken(token);
        }
예제 #18
0
        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 tok.SymmetricSecurityKey(Encoding.UTF8.
                                                   GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new tok.SigningCredentials(key, tok.SecurityAlgorithms.HmacSha256Signature);

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

            var tokenHandler = new jwt.JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var user = _mapper.Map <UserForListDto>(userFromRepo);

            return(Ok(new
            {
                token = tokenHandler.WriteToken(token),
                user
            }));
        }
예제 #19
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
            });
        }
예제 #20
0
        /// <summary>
        /// Authenticate a user.
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public TokenGetDto Authenticate(UserAuthenticationGetDto dto)
        {
            TokenGetDto tokenDto = new TokenGetDto();

            User u = _userRepo.GetUser(dto.Mail);

            if (!u.Password.Equals(dto.Password, StringComparison.OrdinalIgnoreCase))
            {
                throw new IncorrectPasswordException();
            }

            var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
            var now          = DateTime.UtcNow;

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim("email", u.Mail),
                    new Claim("userId", u.Id.ToString()),
                    new Claim("personId", u.PersonId.ToString())
                }),
                Expires            = now.AddMinutes(2000),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.JwtToken.SecretKey)), SecurityAlgorithms.HmacSha256),
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            tokenDto = new TokenGetDto()
            {
                Token   = tokenHandler.WriteToken(token),
                ValidTo = token.ValidTo
            };

            return(tokenDto);
        }
예제 #21
0
        public static bool TryIssueToken
        (
            string issuer
            , string audience
            , IEnumerable <Claim> claims
            , out Microsoft.IdentityModel.Tokens.SecurityToken plainToken
            , out string secretTokenString
            , Microsoft
            .IdentityModel
            .Tokens
            .SymmetricSecurityKey
            signingKey
            , Microsoft
            .IdentityModel
            .Tokens
            .SigningCredentials
            signingCredentials
        )
        {
            bool r = false;

            plainToken        = null;
            secretTokenString = null;
            try
            {
                //var signingKey = new Microsoft
                //                           .IdentityModel
                //                           .Tokens
                //                           .SymmetricSecurityKey
                //                                   (
                //                                       Encoding
                //                                           .GetEncoding(plainTextSecurityKeyEncoding)
                //                                           .GetBytes(plainTextSecurityKey)
                //                                   );
                //var signingCredentials
                //            = new Microsoft.IdentityModel.Tokens.SigningCredentials
                //                (
                //                    signingKey
                //                    , signingCredentialsAlgorithm
                //                    , signingCredentialsDigest
                //                );
                // ComplexClaim
                var claimsIdentity = new ClaimsIdentity
                                     (
                    claims
                    , "Custom"
                                     );
                var securityTokenDescriptor = new Microsoft.IdentityModel.Tokens.SecurityTokenDescriptor()
                {
                    Issuer             = issuer,
                    Audience           = audience,
                    IssuedAt           = DateTime.Now,
                    Subject            = claimsIdentity,
                    SigningCredentials = signingCredentials,
                };

                var tokenHandler = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
                plainToken        = tokenHandler.CreateToken(securityTokenDescriptor);
                secretTokenString = tokenHandler.WriteToken(plainToken);
                r = true;
            }
            catch //(Exception)
            {
                //throw;
            }
            return
                (r);
        }
        public static bool TryIssueToken
        (
            string issuer
            , string audience
            , string userName
            , IEnumerable <Claim> claims
            , out Microsoft
            .IdentityModel
            .Tokens
            .SecurityToken plainToken
            , out string secretTokenString
            , Microsoft
            .IdentityModel
            .Tokens
            .SymmetricSecurityKey
            signingKey
            , Microsoft
            .IdentityModel
            .Tokens
            .SigningCredentials
            signingCredentials
            //, IIdentity identity = null
        )
        {
            bool r = false;

            plainToken        = null;
            secretTokenString = null;
            try
            {
                IIdentity user = new JsonWebTokenUser
                                 (
                    userName
                    , "jwt"
                    , true
                                 );
                var claimsIdentity          = new ClaimsIdentity(user, claims);
                var securityTokenDescriptor =
                    new Microsoft
                    .IdentityModel
                    .Tokens
                    .SecurityTokenDescriptor()
                {
                    Issuer             = issuer,
                    Audience           = audience,
                    IssuedAt           = DateTime.Now,
                    Subject            = claimsIdentity,
                    SigningCredentials = signingCredentials,
                };
                var tokenHandler = new System
                                   .IdentityModel
                                   .Tokens
                                   .Jwt
                                   .JwtSecurityTokenHandler();
                plainToken        = tokenHandler.CreateToken(securityTokenDescriptor);
                secretTokenString = tokenHandler.WriteToken(plainToken);
                r = true;
            }
            catch (Exception e)
            {
                //throw;
            }
            return
                (r);
        }