Пример #1
0
        [HttpPost("login")] //metodo login
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password); //verifica che l'utente esista

            if (userFromRepo == null)                                                                           // se il nome o password non esistono nel db restituisce null
            {
                return(Unauthorized());                                                                         // restituisco questo invece di 'nome giusto ma password errata' o viceversa
            }
            var claims = new[]                                                                                  //se il login è avvenuto con succeso passo alla definizione del token mettenedo 2 parametri: Id e nome
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),                               //Id scritto sul token
                new Claim(ClaimTypes.Name, userFromRepo.Username)                                               //nome scirtto sul token
            };

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

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

            var tokenDescriptor = new SecurityTokenDescriptor    //token che viene creato
            {
                Subject            = new ClaimsIdentity(claims), // il token viene creato inserendo l'iD e il nome
                Expires            = DateTime.Now.AddDays(1),    //tempo di scadenza del token
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

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

            return(Ok(new
            {             // token rimandato ai nostri client
                token = tokenHandler.WriteToken(token),
                user
            }));
        }
Пример #2
0
        public async Task <IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
        {
            // Get the corresponding user from the repository
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

            // If login/password don't match => user is null => Unauthorized
            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            // generate JWT
            var tokenHandler = new JwtSecurityTokenHandler();
            // Generate the decode key
            var key = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value);
            // Describe the token
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                    new Claim(ClaimTypes.Name, userFromRepo.Username)
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(key),
                    SecurityAlgorithms.HmacSha512Signature
                    )
            };

            // Create token from description
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

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

            return(Ok(new { tokenString, user }));
        }
Пример #3
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            userForLoginDto.Username = userForLoginDto.Username.ToLower();
            var userFromRepo = await _repo.Login(userForLoginDto.Username, 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 SymmetricSecurityKey(Encoding.UTF8
                                               .GetBytes(_config.GetSection("AppSettings:Token").Value));

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

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

            var tokenHandler = new JwtSecurityTokenHandler();
            var token        = tokenHandler.CreateToken(tokenDescriptor);
            var user         = _mapper.Map <UserForListDto>(userFromRepo);

            return(Ok(new
            {
                token = tokenHandler.WriteToken(token),
                user
            }));
        }
Пример #4
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var UserFromRepo = await _repo.Login(userForLoginDto.UserName.ToLower(), userForLoginDto.Password);

            if (UserFromRepo == null)
            {
                return(Unauthorized());
            }
            // create Token
            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, UserFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, UserFromRepo.UserName)
            };

            // key to sign our token and seve it in the app setting cuz we going to use in a lot of places
            var Key = new SymmetricSecurityKey(Encoding.UTF8
                                               .GetBytes(_config.GetSection("AppSettings:Token").Value));
            // createing Creadentials
            var creds = new SigningCredentials(Key, SecurityAlgorithms.HmacSha512Signature);


            // create security  token  descriptor which is gonig to contain our claims our expiry data for the token and singing credentils.
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            // saving our token
            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new{
                token = tokenHandler.WriteToken(token)
            }));
        }
Пример #5
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            // le eccezioni vengono gestite da un handler globale definito in Startup.cs
            //throw new Exception("AuthController -> Login says NO!");

            var user = await _userManager.FindByNameAsync(userForLoginDto.Username);

            var result = await _signInManager.CheckPasswordSignInAsync(user, userForLoginDto.Password, false);

            if (result.Succeeded)
            {
                var appUser = await _userManager.Users.Include(p => p.Photos).FirstOrDefaultAsync(u => u.NormalizedUserName == userForLoginDto.Username.ToUpper());

                var userToReturn = _mapper.Map <UserForListDto>(appUser);
                // token restituito nella response
                // il token può essere verificato sul sito https://jwt.io/
                return(Ok(new {
                    token = GenerateJwtToken(appUser),
                    user = userToReturn
                }));
            }
            return(Unauthorized());
        }
Пример #6
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var user = await _userManager.FindByNameAsync(userForLoginDto.UserName);

            if (user == null)
            {
                return(Unauthorized());
            }
            var result = await _signInManager.CheckPasswordSignInAsync(user, userForLoginDto.Password, false);

            if (result.Succeeded)
            {
                var appUser = _mapper.Map <UserForListDto>(user);

                return(Ok(new
                {
                    token = GenerateJwtToken(user).Result
                    ,
                    user = appUser
                }));
            }
            return(Unauthorized());
        }
        public async Task<IActionResult> Login(UserForLoginDto userForLoginDto)
        {

            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

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

            var creds = new SigningCredentials(GetKey(), SecurityAlgorithms.HmacSha512Signature);

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

            var tokenHandler = new JwtSecurityTokenHandler();
            var token = tokenHandler.CreateToken(tokenDescriptor);
            var user = _mapper.Map<UserForListDto>(userFromRepo);

            return Ok(new { token = tokenHandler.WriteToken(token), user });
        }
Пример #8
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var user = await _userManager.FindByNameAsync(userForLoginDto.Username);

            var result = await _signInManager
                         .CheckPasswordSignInAsync(user, userForLoginDto.Password, false);

            if (result.Succeeded)
            {
                var appUser = await _userManager.Users.Include(p => p.Photos)
                              .FirstOrDefaultAsync(u => u.NormalizedUserName == userForLoginDto.Username.ToUpper());

                var userToReturn = _mapper.Map <UserForListDto>(appUser);

                return(Ok(new
                {
                    token = GenerateJwtToken(appUser).Result,
                    user = userToReturn
                }));
            }

            return(Unauthorized());
        }
Пример #9
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            // var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);
            var user = await _userManager.FindByNameAsync(userForLoginDto.Username);

            var result = await _signInManager.CheckPasswordSignInAsync(user, userForLoginDto.Password, false);

            // if (userFromRepo == null)
            //     return Unauthorized();
            if (result.Succeeded)
            {
                var appUser = _mapper.Map <UserForListDto>(user);

                return(Ok(new
                {
                    // token = tokenHandler.WriteToken(token),
                    token = GenerateJwtToken(user).Result,
                    user = appUser
                }));
            }

            return(Unauthorized());
        }
Пример #10
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var user = await _userManager.FindByNameAsync(userForLoginDto.UserName);

            if (user == null)
            {
                return(Unauthorized("Username not found !"));
            }
            var result = await _signInManager.CheckPasswordSignInAsync(user, userForLoginDto.Password, false);

            if (result.Succeeded)
            {
                var appUser      = _userManager.Users.Where(u => u.NormalizedUserName == userForLoginDto.UserName.ToUpper()).FirstOrDefault();
                var userToReturn = _mapper.Map <UserForDisplayDetailDto>(appUser);
                return(Ok(new
                {
                    token = GenerateJwtToken(appUser).Result,
                    user = userToReturn
                }));
            }

            return(Unauthorized("Incorrect Password !"));
        }
Пример #11
0
        //post URL http:5000/api/auth/login
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            // missed photoUrl here, before use _context.Users.Include(p => p.Photos)
            var user = await _userManager.FindByNameAsync(userForLoginDto.username);

            if (user != null)
            {
                var result = await _signInManager.CheckPasswordSignInAsync(user, userForLoginDto.password, false);

                if (result.Succeeded)
                {
                    // get photo
                    var userFromRepo = await _context.Users.Include(p => p.Photos).FirstOrDefaultAsync(x => x.UserName == user.UserName);

                    var appUser = _mapper.Map <UserForListDto>(userFromRepo);
                    return(Ok(new {
                        token = GenerateJwtToken(user).Result,
                        user = appUser
                    }));
                }
            }
            return(Unauthorized());
        }
Пример #12
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var user = await _userManager.FindByNameAsync(userForLoginDto.Username); // Not good. It would be better to use FindByIdAsync but that method is accepting string as ID not int.

            var result = await _signInManager
                         .CheckPasswordSignInAsync(user, userForLoginDto.Password, false); // 3rd parameter is used for locking acc if lets say user tries to login 3 time fails.

            if (result.Succeeded)
            {
                var appUser = await _userManager.Users.Include(p => p.Photos)
                              .FirstOrDefaultAsync(u => u.NormalizedUserName == userForLoginDto.Username.ToUpper());

                var userToReturn = _mapper.Map <UserForListDto>(appUser);

                return(Ok(new
                {
                    token = GenerateJwtToken(appUser).Result,
                    user = userToReturn
                }));
            }

            return(Unauthorized());
        }
Пример #13
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            //no longer user this login method
            //var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);
            var user = await _userManager.FindByNameAsync(userForLoginDto.Username);

            var result = await _signInManager.CheckPasswordSignInAsync(
                user, userForLoginDto.Password, false); // false - not lock out user when attempting to sign in

            //if (userFromRepo == null) return Unauthorized();
            if (result.Succeeded)
            {
                var appUser = _mapper.Map <UserForListDto>(user);

                return(Ok(new
                {
                    token = GenerateJwtToken(user).Result,
                    user = appUser
                }));
            }

            return(Unauthorized());
        }
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var userFromRepo = await _repo.Login(userForLoginDto.Username, 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 SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

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

            var tokenDescriptor = new SecurityTokenDescriptor()
            {
                Subject = new ClaimsIdentity(claims),
            }
        }
Пример #15
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            //Revisar que exista ese usuario y que haya puesto la contra correcta.
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

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

            //Creamos los claims que debe llevar el token
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };

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

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

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

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new{
                token = tokenHandler.WriteToken(token)
            }));
        }
Пример #16
0
        public async Task <IActionResult> Login(UserForLoginDto userLoginData)
        {
            var userFromRepo = await _authRepository.LoginAsync(userLoginData.Username, userLoginData.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized("Username and password does not match"));
            }

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

            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_cfg.GetSection("AppSettings:Token").Value));

            var creds           = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.UtcNow.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

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

            return(Ok(new
            {
                token = tokenHandler.WriteToken(token),
                user
            }));
        }
Пример #17
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)
            }; // The claims contains the user id and name.

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

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

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            }; // Generating the token based on the claims, signed with a secure key. This key is used to authenticate when this is sent back from client in further requests

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

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

            return(Ok(new
            {
                token = tokenHandler.WriteToken(token), // Pass the token to the client
                user
            }));
        }
Пример #18
0
        public async Task <IActionResult> Login(UserForLoginDto login)
        {
            if (login is null)
            {
                throw new ArgumentNullException(nameof(login));
            }

            var userFromRepo = await _repo.Login(login.Username, login.Password);

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

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

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

            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

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

            var tokenHandler = new JwtSecurityTokenHandler();
            var createToken  = tokenHandler.CreateToken(tokenDescriptor);
            var writeToken   = tokenHandler.WriteToken(createToken);

            return(Ok(writeToken));
        }
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            throw new Exception("Generated exception!");

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

            // to have valid token we need to sign it with key
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value)); // make key from token

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);                           // hash key

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

            var tokenHandler = new JwtSecurityTokenHandler();      // handler to create token and pass it

            var token = tokenHandler.CreateToken(tokenDescriptor); // make token

            return(Ok(new {
                token = tokenHandler.WriteToken(token) // return token to client
            }));
        }
Пример #20
0
        public async Task <IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var userFromRepo = await _repo.Login(userForLoginDto.UserName.ToLower(), userForLoginDto.Password);

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

            // generate token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                    new Claim(ClaimTypes.Name, userFromRepo.Username)
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                            SecurityAlgorithms.HmacSha512Signature)
            };

            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

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

            return(Ok(new { tokenString, user }));
        }
Пример #21
0
        public async Task <IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
        {
            //throw new Exception("Computer really says no!");
            // try
            // {
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

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

            // generate token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value);
            var tokenDescriptor = new SecurityTokenDescriptor {
                Subject = new ClaimsIdentity(new Claim[] {
                    new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                    new Claim(ClaimTypes.Name, userFromRepo.Username)
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials =
                    new SigningCredentials(
                        new SymmetricSecurityKey(key),
                        SecurityAlgorithms.HmacSha512Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(Ok(new { tokenString }));
            // }
            // catch
            // {

            //     return StatusCode(500, 'Computer really says no!')
            // }
        }
Пример #22
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            //throw new Exception("Computer says no");
            var userFromRepo = await this._repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

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

            //return a toke, add JWTs token
            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };

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

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

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

            var tokenHandler = new JwtSecurityTokenHandler();

            SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new
            {
                Token = tokenHandler.WriteToken(token)
            }));    //anonymous type as an object
        }
Пример #23
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var userFomRepo = await _repo.Login(userForLoginDto.Username, userForLoginDto.Password);

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

            //build a token to retrun to the user
            var claims = new []
            {
                new Claim(ClaimTypes.NameIdentifier, userFomRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFomRepo.Name)
            };

            //need a key for our token which will be hashed
            var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

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

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

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
Пример #24
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            userForLoginDto.Username = userForLoginDto.Username.ToLower();
            var user = await _repo.Login(userForLoginDto.Username, userForLoginDto.Password);

            if (user == null)
            {
                return(Unauthorized("Incorrect Credientials"));
            }


            // Send the token to the user so that any further request will be authenticated based on the JWT Token

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

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

            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddHours(2),
                SigningCredentials = cred
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
Пример #25
0
        public async Task <IActionResult> Login(UserForLoginDto user)
        {
            //throw new Exception("... this shit is getting on my nerves - exception ! ....");

            var userFromRepo = await _repo.Login(user.UserName.ToLower(), user.Password);

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

            var secret = _config.GetSection("Cembo_Settings:Token").Value;

            var token = new JWTToken(userFromRepo, secret);

            var tokenBuild = token.Build();

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

            return(Ok(new {
                token = tokenBuild,
                userFromApi
            }));
        }
Пример #26
0
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

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

            // Create Login Token - JWT
            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),   // DatabaseId
                new Claim(ClaimTypes.Name, userFromRepo.UserName)                   // User Name
            };

            // Sign the Token
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

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

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

            // Create JWT Token Handler
            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new {     // Do new as this will create an object and return JSON rather than just a string with token in
                token = tokenHandler.WriteToken(token)
            }));
        }
Пример #27
0
        public async Task <IActionResult> Login(UserForLoginDto loginDto)
        {
            var user = await _authRepository.Login(loginDto.UserName.ToLower(), loginDto.Password);

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

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

            // secret
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

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

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
Пример #28
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)
            };// hàm này lấy ra ID đăng nhập và Username

            var key = new SymmetricSecurityKey(Encoding.UTF8
                                               .GetBytes(_config.GetSection("AppSettings:Token").Value));
            //lấy ra key

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

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims), //điều kiện id
                Expires            = DateTime.Now.AddDays(1),    // điều kiện giới hạn 1 ngày
                SigningCredentials = creds                       // mã hóa
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(Ok(new {
                token = tokenHandler.WriteToken(token)
            }));
        }
Пример #29
0
        public async Task <IActionResult> Login([FromBody] UserForLoginDto userForLoginDto)
        {
            try
            {
                Users userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

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

                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Encoding.ASCII.GetBytes("super secret key");

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                        new Claim(ClaimTypes.Name, userFromRepo.Username)
                    }
                                                 ),
                    Expires            = DateTime.Now.AddDays(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
                };
                var token       = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                var user = _mapper.Map <UserForListDto>(userFromRepo);
                return(Ok(new { tokenString, user }));
            }
            catch (Exception)
            {
                return(StatusCode(500, "It is wrong login apply."));
            }
        }
        public async Task <IActionResult> Login(UserForLoginDto userForLoginDto)
        {
            var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());//not tell user like your username is not valid(hacker can try to brute force)
            }
            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()), //convert int Id to String because ClaimTypes is string
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };

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

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

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

            var tokenHandler = new JwtSecurityTokenHandler();

            var token         = tokenHandler.CreateToken(tokenDescriptor);
            var localUserData = _mapper.Map <LocalUserData>(userFromRepo);


            return(Ok(new
            {
                token = tokenHandler.WriteToken(token),
                localUserData
            }));//return token as object type
        }