コード例 #1
0
        public IActionResult Authenticate(LoginUser userParam)
        {
            // Get the user by username
            User user = userDao.GetUser(userParam.Username);

            // If no user was found or it was a password mismatch, return a generic bad request.
            if (user == null || !passwordHasher.VerifyHashMatch(user.PasswordHash, userParam.Password, user.Salt))
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            // Create an authentication token
            string token = tokenGenerator.GenerateToken(user.Id, user.Username, user.Role);

            // Create a ReturnUser object to return to the client
            ReturnUser retUser = new ReturnUser()
            {
                Id       = user.Id,
                Username = user.Username,
                Role     = user.Role,
                Token    = token
            };

            return(Ok(retUser));
        }
コード例 #2
0
        public IActionResult Authenticate([FromForm] UserLoginParams form)
        {
            User user = null;

            try
            {
                user = _userService.Authenticate(form);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e);
            }
            if (user == null)
            {
                return(BadRequest("Invalid credentials"));
            }

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


            var tokenInfo = _tokenGenerator.GenerateToken(_config.GetValue <string>("AppSettings:Secret"), claims, 15);

            return(Ok(new UserDto
            {
                UserName = user.UserName,
                Email = user.Email,
                Token = tokenInfo.Token,
                ValidTo = tokenInfo.ValidTo
            }));
        }
コード例 #3
0
        public async Task <ActionResult> LoginAsync(LoginDto dto)
        {
            var user = await userManager.FindByNameAsync(dto.Username);

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

            var result = await signInManager.CheckPasswordSignInAsync(user, dto.Password, false);


            if (!result.Succeeded)
            {
                return(BadRequest());
            }

            var roles = await userManager.GetRolesAsync(user);

            IList <Claim> claims = await userManager.GetClaimsAsync(user);

            return(Ok(new
            {
                result = result,
                username = user.UserName,
                UserRoles = roles,
                token = _token.GenerateToken(user, roles, claims)
            }));
        }
コード例 #4
0
        public IActionResult Authenticate(LoginUser userParam)
        {
            // Default to bad username/password message
            IActionResult result = Unauthorized(new { message = "Username or password is incorrect" });

            // Get the user by username
            User user = userDAO.GetUser(userParam.Username);

            // If we found a user and the password hash matches
            if (user != null && passwordHasher.VerifyHashMatch(user.PasswordHash, userParam.Password, user.Salt))
            {
                // Create an authentication token
                string token = tokenGenerator.GenerateToken(user.UserId, user.Username, user.Role);

                int comicCount = collectionDAO.UserTotalComicCount(user.UserId);

                // Create a ReturnUser object to return to the client
                LoginResponse retUser = new LoginResponse()
                {
                    User = new ReturnUser()
                    {
                        UserId = user.UserId, Username = user.Username, Role = user.Role, ComicCount = comicCount
                    }, Token = token
                };

                // Switch to 200 OK
                result = Ok(retUser);
            }

            return(result);
        }
コード例 #5
0
ファイル: AccountService.cs プロジェクト: zeeshanzahoor/Roka
        public LoginResultDTO AuthenticateUser(string UserName, string Password)
        {
            var user = _userRepository.All.FirstOrDefault(m => m.Username == UserName);

            if (user != null && user.Password == Password)
            {
                var LoginResult = new LoginResultDTO()
                {
                    LoginResult = Backbone.Enums.LoginResult.Success,
                    ArtifexUser = new ArtifexUser()
                    {
                        Id = 1, Username = "******"
                    },
                };

                if (LoginResult.LoginResult == Backbone.Enums.LoginResult.Success)
                {
                    String Token = _tokenGenerator.GenerateToken(LoginResult.ArtifexUser);
                    LoginResult.CreateProfile();
                    LoginResult.User.Token = Token;
                    return(LoginResult);
                }
            }


            //TODO: Authenticate from database

            return(null);
        }
コード例 #6
0
        public IActionResult Authenticate(LoginUser userParam)
        {
            // Default to bad username/password message
            IActionResult result = BadRequest(new { message = "Username or password is incorrect" });

            // Get the user by username
            User user = userDAO.GetUser(userParam.Username);

            // If we found a user and the password hash matches
            if (user != null && passwordHasher.VerifyHashMatch(user.PasswordHash, userParam.Password, user.Salt))
            {
                // Create an authentication token
                string token = tokenGenerator.GenerateToken(user.UserId, user.Username /*, user.Role*/);

                // Create a ReturnUser object to return to the client
                ReturnUser retUser = new ReturnUser()
                {
                    UserId   = user.UserId,
                    Username = user.Username,
                    /*Role = user.Role,*/
                    Token = token,
                    //Balance = user.Balance;
                };

                // Switch to 200 OK
                result = Ok(retUser);
            }

            return(result);
        }
コード例 #7
0
        public async Task <IActionResult> SignInAsync([FromBody] Models.AccountViewModels.LoginViewModel loginModel)
        {
            JsonResponseModel result;
            var signinResult = await _signInManager.PasswordSignInAsync(loginModel.Email, loginModel.Password, true, lockoutOnFailure : false);

            if (signinResult.Succeeded)
            {
                var userInfo = await _userRepository.FetchAsync(u => u.Email == loginModel.Email);

                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Jti, GuidIdGenerator.Instance.NewId()),
                    new Claim(JwtRegisteredClaimNames.Sub, userInfo.Email),
                    new Claim(JwtRegisteredClaimNames.NameId, userInfo.Id.ToString()),
                };
                var token = _tokenGenerator.GenerateToken(claims);

                var userToken = new UserTokenEntity
                {
                    AccessToken = token.AccessToken,
                    ExpiresIn   = token.ExpiresIn,
                    UserEmail   = userInfo.Email,
                    UserId      = userInfo.Id,
                    UserName    = userInfo.UserName
                };
                result = new Models.JsonResponseModel <JWT.TokenEntity> {
                    Data = userToken, Msg = "", Status = Models.JsonResponseStatus.Success
                };
            }
            else
            {
                if (signinResult.IsLockedOut)
                {
                    result = new Models.JsonResponseModel <JWT.TokenEntity> {
                        Msg = "Account locked out", Status = Models.JsonResponseStatus.RequestError
                    };
                }
                else
                {
                    result = new Models.JsonResponseModel <JWT.TokenEntity> {
                        Msg = "failed to authenticate", Status = Models.JsonResponseStatus.AuthFail
                    };
                }
            }
            return(Ok(result));
        }
コード例 #8
0
        public async Task <UserLoginResponse> LoginUser(LoginRequest request)
        {
            var user = await _userRepository.LoginUserAsync(request);

            var token = _tokenGenerator.GenerateToken(user);

            return(new UserLoginResponse(user, token));
        }
コード例 #9
0
        private ActionResult <ApplicationUserViewModel> GenerateAuthenticateUser(ApplicationUser user)
        {
            ApplicationUserViewModel userViewModel = _mapper.Map <ApplicationUserViewModel>(user);

            userViewModel.Token = _tokenGenerator.GenerateToken(user.UserName);

            return(userViewModel);
        }
コード例 #10
0
        public async Task <IResponse> Handle(AuthenticateCommand request, CancellationToken cancellationToken)
        {
            var userLogged = await loginContext.AuthenticateAsync(request.Login, request.Password, request.Role.ToString());

            var jwt = await tokenGenerator.GenerateToken(userLogged);

            jwt.User = mapper.Map <UserDTOWithCredentials>(userLogged);
            return(await response.Generate(collections : jwt));
        }
コード例 #11
0
        public async Task <IActionResult> Login([FromBody] LoginViewModel loginViewModel)
        {
            try
            {
                //var userDTO = _mapper.Map<UserDTO>(loginViewModel);

                var userBanco = await _userService.GetByName(loginViewModel.Login);

                if (userBanco == null)
                {
                    return(Ok(new ResultViewModel
                    {
                        Message = "Usuario informado não existe.",
                        Success = true,
                        Data = null
                    }));
                }
                else
                {
                    if (userBanco.Password != loginViewModel.Password)
                    {
                        return(Ok(new ResultViewModel
                        {
                            Message = "Senha errada.",
                            Success = true,
                            Data = null
                        }));
                    }
                }

                //var tokenLogin =  _configuration["Jwt:Login"];
                //var tokenPassword =  _configuration["Jwt:Password"];

                //if (loginViewModel.Login == tokenLogin && loginViewModel.Password == tokenPassword)
                if (loginViewModel.Login == userBanco.Name && loginViewModel.Password == userBanco.Password)
                {
                    return(Ok(new ResultViewModel
                    {
                        Message = "Usuário autenticado com sucesso!",
                        Success = true,
                        Data = new
                        {
                            Token = _tokenGenerator.GenerateToken(),
                            TokenExpires = DateTime.UtcNow.AddHours(int.Parse(_configuration["Jwt:HoursToExpire"]))
                        }
                    }));
                }
                else
                {
                    return(StatusCode(401, Responses.UnauthorizedErrorMessage()));
                }
            }
            catch (Exception)
            {
                return(StatusCode(500, Responses.ApplicationErrorMessage()));
            }
        }
コード例 #12
0
        public async Task <string> Create(object payloadObject, string subject, string issuer, string audience, string payloadObjectClaim, IContractResolver contractResolver = null)
        {
            var payload = BuildJwtPayload(payloadObject, issuer, subject, audience, payloadObjectClaim, contractResolver);
            var header  = await BuildJwtHeader();

            var token = await _tokenGenerator.GenerateToken(header, payload);

            return(token);
        }
コード例 #13
0
ファイル: UsersController.cs プロジェクト: cantte/Kaizen
        private async Task <ActionResult <ApplicationUserViewModel> > GenerateAuthenticateUser(ApplicationUser user)
        {
            ApplicationUserViewModel userView = _mapper.Map <ApplicationUserViewModel>(user);
            string role = await _userRepository.GetUserRoleAsync(user);

            userView.Token = _tokenGenerator.GenerateToken(user.Id, user.UserName, role);

            return(userView);
        }
コード例 #14
0
ファイル: UserService.cs プロジェクト: horlor/KnowledgeBase
        public async Task <LoginResult> Login(string username, string password)
        {
            var(result, role, refreshToken) = await userRepo.SignIn(username, password);

            var session = new LoginResult()
            {
                Success = false
            };

            if (result == SignInResult.Success)
            {
                session.Success      = true;
                session.Role         = role;
                session.AccessToken  = tokenGenerator.GenerateToken(username, role);
                session.RefreshToken = refreshToken;
                session.Username     = username;
            }
            return(session);
        }
コード例 #15
0
        public async Task <UserLoginModel> Handle(LoginUserQuery request, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(request.Email) || string.IsNullOrEmpty(request.Password))
            {
                return(null);
            }

            var user = await _context.Users
                       .SingleOrDefaultAsync(x => x.Email == request.Email);

            if (user == null)
            {
                throw new NotFoundException(nameof(User), request);
            }

            if (!VerifyPasswordHash(request.Password, user.PasswordHash, user.PasswordSalt))
            {
                return(null);
            }

            var refreshToken = _tokenGenerator.GenerateToken();

            var existsToken = await _context.RefreshTokens
                              .Where(x => x.UserId == user.Id)
                              .SingleOrDefaultAsync(cancellationToken);

            if (existsToken == null)
            {
                var refreshT = new RefreshToken
                {
                    UserId  = user.Id,
                    Token   = refreshToken,
                    Expires = DateTime.UtcNow.AddDays(5)
                };
                _context.RefreshTokens.Add(refreshT);
            }
            else if (existsToken.Expires < DateTime.UtcNow)
            {
                existsToken.Token   = refreshToken;
                existsToken.Expires = DateTime.UtcNow.AddDays(5);
                _context.RefreshTokens.Update(existsToken);
            }

            await _context.SaveChangesAsync(cancellationToken);

            string secret = _appSettings.Secret;

            var userLoginModel = _mapper.Map <UserLoginModel>(user);

            userLoginModel.Token        = _accessTokenGenerator.GenerateAccessToken(secret, userLoginModel);
            userLoginModel.RefreshToken = refreshToken;

            return(userLoginModel);
        }
コード例 #16
0
        public async Task <IActionResult> Authenticate(UserSignInDTO userdata)
        {
            var loginresult = await _authmanager.AuthenticateUserCredentials(userdata.SuppliedUserName.ToLower(), userdata.SuppliedPassword, userdata.VerificationCode);

            if (loginresult.ValidatedUser == null)
            {
                return(CreateUnauthorizedError(loginresult.Error));
            }
            loginresult.ValidatedUser.Token = _tokenManager.GenerateToken(loginresult.ValidatedUser);
            return(Ok(loginresult.ValidatedUser));
        }
コード例 #17
0
        public IActionResult Login(LoginViewModelInput loginViewModelInput)
        {
            var    user  = _tokenGenerator.createTesteUser();
            string token = _tokenGenerator.GenerateToken(user);

            return(Ok(new
            {
                Token = token,
                User = user
            }));
        }
コード例 #18
0
        public TokensModel CreateItem(double latitude, double longitude, int duration, string address, double?accuracy)
        {
            var token        = _tokenGenerator.GenerateToken();
            var privateToken = _tokenGenerator.GenerateToken();
            var item         = new NavigationItem
            {
                Latitude  = latitude,
                Longitude = longitude,
                StartTime = DateTime.Now,
                Expired   = null,
                Address   = address ?? "",
                Accuracy  = accuracy
            };

            item.ExpirationTime = item.StartTime.AddMinutes(duration);
            _items.AddOrUpdate(token, s => item, (s, ni) => item);
            _privateTokenMap.AddOrUpdate(privateToken, t => token, (t, i) => token);
            return(new TokensModel {
                PublicToken = token, PrivateToken = privateToken
            });
        }
コード例 #19
0
        public async Task <ProfileCreateResponse> Create([FromBody] ProfileCreate profileCreate)
        {
            var patient = await registeredPatientBussiness.Create(profileCreate);

            var token = tokenGenerator.GenerateToken(patient.QRCode.FormatAsString(), Role.Patient).Token;

            return(new ProfileCreateResponse()
            {
                QRCode = patient.QRCode,
                Token = token
            });
        }
コード例 #20
0
        public IActionResult Login([FromBody] AuthorizationWriteViewModel loginViewModel)
        {
            var    valid = _authorizationService.ValidCredentials(loginViewModel.Username, loginViewModel.Password);
            string token = "";

            if (valid)
            {
                var userId = _userService.GetUserByName(loginViewModel.Username).Id;
                token = _tokenGenerator.GenerateToken(userId);
            }
            return(Ok(token));
        }
コード例 #21
0
        public async Task <Response <string> > CreateLinkAsync(string originUrl, string note, string akaName, bool isEnabled)
        {
            try
            {
                using (var conn = DbConnection)
                {
                    const string sqlLinkExist = "SELECT TOP 1 FwToken FROM Link l WHERE l.OriginUrl = @originUrl";
                    var          tempToken    = await conn.ExecuteScalarAsync <string>(sqlLinkExist, new { originUrl });

                    if (null != tempToken)
                    {
                        if (_tokenGenerator.TryParseToken(tempToken, out var tk))
                        {
                            _logger.LogInformation($"Link already exists for token '{tk}'");
                            return(new SuccessResponse <string>(tk));
                        }

                        string message = $"Invalid token '{tempToken}' found for existing url '{originUrl}'";
                        _logger.LogError(message);
                    }

                    const string sqlTokenExist = "SELECT TOP 1 1 FROM Link l WHERE l.FwToken = @token";
                    string       token;
                    do
                    {
                        token = _tokenGenerator.GenerateToken();
                    } while (await conn.ExecuteScalarAsync <int>(sqlTokenExist, new { token }) == 1);

                    _logger.LogInformation($"Generated Token '{token}' for url '{originUrl}'");

                    var link = new Link
                    {
                        FwToken       = token,
                        IsEnabled     = isEnabled,
                        Note          = note,
                        AkaName       = akaName,
                        OriginUrl     = originUrl,
                        UpdateTimeUtc = DateTime.UtcNow
                    };
                    const string sqlInsertLk = @"INSERT INTO Link (OriginUrl, FwToken, Note, AkaName, IsEnabled, UpdateTimeUtc) 
                                                 VALUES (@OriginUrl, @FwToken, @Note, @AkaName, @IsEnabled, @UpdateTimeUtc)";
                    await conn.ExecuteAsync(sqlInsertLk, link);

                    return(new SuccessResponse <string>(link.FwToken));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, e.Message);
                return(new FailedResponse <string>(e.Message));
            }
        }
コード例 #22
0
        public IActionResult Login(AuthenticateUser model)
        {
            IActionResult result = Unauthorized();

            var user = userDAO.GetUser(model.Username);

            if (user.Username != null && passwordHasher.VerifyPasswordMatch(user.Password, model.Password, user.Salt))
            {
                var token = tokenGenerator.GenerateToken(user.Username, user.Role);
                result = Ok(token);
            }
            return(result);
        }
コード例 #23
0
        public async Task <ActionResult <StringServiceResult> > Authenticate([FromBody] AuthenticateUserRequest request)
        {
            var result = await _userService.AuthenticateAsync(request);

            if (result.IsSuccess)
            {
                var jwtToken = _tokenGenerator.GenerateToken(result.Data.Id);

                return(Ok(StringServiceResult.Success(jwtToken)));
            }

            return(BadRequest(ServiceResult.Error(result.Message)));
        }
コード例 #24
0
        public async Task <IActionResult> Login(SyncLoginModel mod)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            // Password Hash
            var currentUser = _context.Users.Where(x => x.Email.ToUpper().CompareTo(mod.EmailAddress.ToUpper()) == 0 && x.Status == true).FirstOrDefault();

            if (currentUser == null || !Hash.Validate(mod.Password, currentUser.salt, currentUser.PasswordHash))
            {
                return(BadRequest(new { message = "Your login input is incorrect" }));
            }

            var d = await _context.DesktopClients.Where(x => mod.ClientName.ToUpper().CompareTo(x.ClientName.ToUpper()) == 0 &&
                                                        mod.ClientMacAddress.ToUpper().CompareTo(x.ClientMacAddress.ToUpper()) == 0 &&
                                                        mod.ClientType.ToUpper().CompareTo(x.ClientType.ToUpper()) == 0).FirstOrDefaultAsync();

            //gets the type of the user
            var type = _oService.Strip(currentUser.GetType().ToString());

            if (d == null)
            {
                var dc = new DesktopCreateModel()
                {
                    ClientMacAddress = mod.ClientMacAddress,
                    ClientName       = mod.ClientName,
                    ClientType       = mod.ClientType,
                };
                d = await _dService.CreateDesktopClientAsync(dc);
            }

            var token = await _tokGen.GenerateToken(d, currentUser.Id, type);


            return(Ok(token));
        }
コード例 #25
0
        public async Task <AuthenticateResponse> Handle(AuthenticateRequest request, CancellationToken cancellationToken)
        {
            var user = await repository.GetByUserNameAsync(request.UserName);

            if (user == null || !BCryptNet.Verify(request.Password, user.PasswordHash))
            {
                throw new AuthenticationException($"Could not log in user {request.UserName}.");
            }

            var response = mapper.Map <AuthenticateResponse>(user);

            response.Token = tokenGenerator.GenerateToken(user);
            return(response);
        }
コード例 #26
0
            private async Task <AnonymousTokenResponse> CreateAnonymousTokenForRequestAsync(AnonymousTokenRequest request)
            {
                var signingKeyPair = await _keyStore.GetActiveSigningKeyPair();

                var privateKey  = signingKeyPair.PrivateKey;
                var publicKey   = signingKeyPair.PublicKey;
                var maskedPoint = signingKeyPair.EcParameters.Curve.DecodePoint(Convert.FromBase64String(request.MaskedPoint));

                var token          = _tokenGenerator.GenerateToken(privateKey, publicKey, signingKeyPair.EcParameters, maskedPoint);
                var signedPoint    = token.Q;
                var proofChallenge = token.c;
                var proofResponse  = token.z;

                return(new AnonymousTokenResponse(signingKeyPair.Kid, signedPoint, proofChallenge, proofResponse));
            }
コード例 #27
0
        public async Task <User> Authenticate(string username, string password)
        {
            var userTable = await userRepository.GetAuthenticatedUserDetails(username, password);

            var user = MapAuthenticatedUserDetails(userTable.Tables[0]);

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

            user.Token = tokenGenerator.GenerateToken(user);

            return(user);
        }
コード例 #28
0
ファイル: TokenGeneratorTest.cs プロジェクト: cantte/Kaizen
        public void Generate_And_Verify_Token()
        {
            var token = _tokenGenerator.GenerateToken("123", "admin", "Administrator");

            Assert.IsTrue(token.Length > 0);

            var handler   = new JwtSecurityTokenHandler();
            var tokenRead = handler.ReadToken(token) as JwtSecurityToken;

            Assert.IsNotNull(tokenRead);

            var tokenRole = tokenRead.Claims.First(claim => claim.Type == "role").Value;

            Assert.AreEqual("Administrator", tokenRole);
        }
コード例 #29
0
        public async Task <GenerateTokenResponseModel> Generate(GenerateTokenRequestModel model)
        {
            var k = await _privateKeyStore.GetAsync();

            var K = await _publicKeyStore.GetAsync();

            var P = _ecParameters.Curve.DecodePoint(Hex.Decode(model.PAsHex));

            var token = _tokenGenerator.GenerateToken(k, K.Q, _ecParameters, P);
            var Q     = token.Q;
            var c     = token.c;
            var z     = token.z;

            return(new GenerateTokenResponseModel(Q, c, z));
        }
コード例 #30
0
        public AccessToken CreateToken(int minHoursForRefresh, string tokenType)
        {
            string token      = _tokenGenerator.GenerateToken(8);
            var    addedToken = _context.AccessToken.Add(new AccessToken
            {
                HoursForRefresh = minHoursForRefresh,
                LastActivated   = DateTime.MinValue,
                TokenType       = tokenType,
                Token           = token
            });

            _context.SaveChanges();

            return(addedToken.Entity);
        }