Beispiel #1
0
        public async Task <AuthenticationResultModel> Authenticate(UserModel model)
        {
            var result = new AuthenticationResultModel();
            var hash   = model.Password;

            var user = await _context.Users.FirstOrDefaultAsync(_ => _.Username == model.Username &&
                                                                _.Password == hash);

            if (user == null)
            {
                result.Success = false;
                result.Error   = new ErrorModel
                {
                    Code         = 1002,
                    ErrorMessage = "Incorrect login or password"
                };
            }
            else
            {
                result.User    = _mapper.Map <UserModel>(user);
                result.Success = true;
            }

            return(result);
        }
Beispiel #2
0
        public async Task <IActionResult> Post([FromBody] AuthenticationModel model)
        {
            User user = await _userManager.FindByEmailAsync(model.Email);

            if (user is null || !await _userManager.CheckPasswordAsync(user, model.Password))
            {
                throw new ApiException("The email or password is incorrect.", StatusCodes.Status401Unauthorized);
            }

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

            var token = new JwtSecurityToken(
                issuer: AuthOptions.ISSUER,
                audience: AuthOptions.AUDIENCE,
                claims: claims,
                expires: DateTime.Now.AddMinutes(AuthOptions.LIFETIME),
                signingCredentials: new SigningCredentials(
                    AuthOptions.GetSymmetricSecurityKey(),
                    SecurityAlgorithms.HmacSha256)
                );

            string encodedJwt = new JwtSecurityTokenHandler().WriteToken(token);

            var result = new AuthenticationResultModel
            {
                AccessToken    = encodedJwt,
                DisplayName    = user.DisplayName,
                ExpirationTime = AuthOptions.LIFETIME
            };

            return(Ok(result));
        }
Beispiel #3
0
        public async Task <AuthenticationResultModel> GenerateJwtByRefreshToken(string token)
        {
            var user = _context.Users.SingleOrDefault(u => u.RefreshTokens.Any(t => t.Token == token));

            if (user == null)
            {
                return(AuthenticationResultModel.Failed($"Token did not match any users."));
            }

            var refreshToken = user.RefreshTokens.Single(x => x.Token == token);

            if (!refreshToken.IsActive)
            {
                return(AuthenticationResultModel.Failed($"Token Not Active."));
            }

            //Revoke Current Refresh Token
            refreshToken.Revoked = DateTime.UtcNow;

            //Generate new Refresh Token and save to Database
            var newRefreshToken = RefreshTokenGenerator.CreateRefreshToken();

            user.RefreshTokens.Add(newRefreshToken);
            _context.Update(user);
            _context.SaveChanges();

            return(await GetAuthenticationResultModel(user, newRefreshToken));
        }
Beispiel #4
0
        public async Task <AuthenticationResultModel> GenerateJwtByUserPass(AuthenticationRequestModel model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(AuthenticationResultModel.Failed($"No Accounts Registered with {model.Email}."));
            }

            if (await _userManager.CheckPasswordAsync(user, model.Password))
            {
                var refreshToken = new RefreshToken();
                if (user.RefreshTokens.Any(a => a.IsActive))
                {
                    refreshToken = user.RefreshTokens.FirstOrDefault(a => a.IsActive);
                }
                else
                {
                    refreshToken = RefreshTokenGenerator.CreateRefreshToken();
                    user.RefreshTokens.Add(refreshToken);
                    _context.Update(user);
                    _context.SaveChanges();
                }

                return(await GetAuthenticationResultModel(user, refreshToken));
            }

            return(AuthenticationResultModel.Failed("Incorrect Credentials for user {user.Email}."));
        }
        public async Task <AuthenticationResultModel> AuthenticateAsync(UsersMaster user)
        {
            // authentication successful so generate jwt token
            AuthenticationResultModel authenticationResult = new AuthenticationResultModel();
            var tokenHandler = new JwtSecurityTokenHandler();

            try
            {
                var key = Encoding.ASCII.GetBytes(_appSettings.JwtSettings.Secret);

                ClaimsIdentity Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim("UserId", user.UserId.ToString()),
                    new Claim("FirstName", user.FirstName),
                    new Claim("LastName", user.LastName),
                    new Claim("EmailId", user.Email == null?"":user.Email),
                    new Claim("UserName", user.UserName == null?"":user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                });
                foreach (var item in GetUserRole(user.UserId))
                {
                    Subject.AddClaim(new Claim(ClaimTypes.Role, item.RoleName));
                }

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject            = Subject,
                    Expires            = DateTime.UtcNow.Add(_appSettings.JwtSettings.TokenLifetime),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);

                authenticationResult.Token = tokenHandler.WriteToken(token);


                var refreshToken = new RefreshToken
                {
                    Token        = Guid.NewGuid().ToString(),
                    JwtId        = token.Id,
                    UserId       = user.UserId,
                    CreationDate = DateTime.UtcNow,
                    ExpiryDate   = DateTime.UtcNow.AddMonths(6)
                };
                await _context.RefreshTokens.AddAsync(refreshToken);

                await _context.SaveChangesAsync();

                authenticationResult.RefreshToken = refreshToken.Token;
                authenticationResult.Success      = true;
                return(authenticationResult);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        public AuthenticationResultModel Authenticate(AuthenticationInputModel input)
        {
            var outputModel = new AuthenticationResultModel {
                Input = input
            };

            var operation = _authentications.FirstOrDefault(a => a.Metadata.AuthenticationType == input.TypeString);

            outputModel.Result = operation == null ? "Implementation cannot be found" : operation.Value.Authenticate(input.Username, input.Password);

            return(outputModel);
        }
        internal ManagementSession(ManagementService service, string username, AuthenticationResultModel authentication)
        {
            this.service = service;
            this.Token   = authentication.AccessToken;
            var accessToken = authentication.AccessToken;

            CurrentUserId        = authentication.UserId;
            this.refreshToken    = authentication.RefreshToken;
            this.CurrentUserName = username;

            Initialize(accessToken, new DateTimeOffset(authentication.ExpireDate));
        }
Beispiel #8
0
#pragma warning restore CS0067

        private async void ChangeControlsState(bool isEntered, AuthenticationResultModel result)
        {
            _loginViewModel.ResultOfLoginTry = string.Empty;
            await Task.Delay(100);

            if (isEntered)
            {
                _loginViewModel.ForegroundColor  = Brushes.Green;
                _loginViewModel.ResultOfLoginTry = $"Welcome again, {result.User.Nickname}!";
            }
            else
            {
                _loginViewModel.ClearPassword();
                _loginViewModel.ResultOfLoginTry = result.Error.ErrorMessage;
            }
        }
Beispiel #9
0
        public async Task <AuthenticationResultModel> Register(RegistrationModel registration)
        {
            //Check if username already exists.
            var existingUser = _userService.GetAll(u => u.Username == registration.Username).FirstOrDefault();

            if (existingUser != null)
            {
                throw new ExceptionUsernameAlreadyExists();
            }

            var passwordHash = PasswordHelper.HashPassword(registration.Password);

            var userToCreate = new User
            {
                FirstName    = registration.FirstName.ToLower(),
                LastName     = registration.LastName.ToLower(),
                Email        = registration.Email.ToLower(),
                Username     = registration.Username.ToLower(),
                PasswordHash = passwordHash
            };

            //userToCreate.UserRole.Add(new UserRole
            //{
            //    RoleId = (long)Roles.BasicUser
            //});

            await _userService.Create(userToCreate);

            var createdUser = _userService.GetAllThenInclude(
                u => u.Id == userToCreate.Id,
                IncludeBuilder <User> .Include(u => u.UserRole).ThenInclude(ur => ur.Role).Done()
                ).Single();

            //Registration successful so generate jwt token
            var token = GenerateToken(createdUser);

            var authenticationResultModel = new AuthenticationResultModel
            {
                UserId = createdUser.Id,
                Token  = token
            };

            return(authenticationResultModel);
        }
        public AuthenticationResultModel Authenticate(User loginCredentials)
        {
            var user = FindUser(loginCredentials);

            if (user == null)
            {
                throw new UserNotFound();
            }

            var tokenString = GenerateJwtToken(user);

            var result = new AuthenticationResultModel
            {
                User        = user,
                TokenString = tokenString
            };

            return(result);
        }
Beispiel #11
0
        private async Task <AuthenticationResultModel> GetAuthenticationResultModel(ApplicationUser user,
                                                                                    RefreshToken refreshToken)
        {
            //Generates new jwt

            var authenticationModel = new AuthenticationResultModel();

            authenticationModel.IsAuthenticated = true;
            JwtSecurityToken jwtSecurityToken = await _tokenGenerator.CreateJwtToken(user);

            authenticationModel.Token    = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            authenticationModel.Email    = user.Email;
            authenticationModel.UserName = user.UserName;
            var rolesList = await _userManager
                            .GetRolesAsync(user).ConfigureAwait(false);

            authenticationModel.Roles        = rolesList.ToList();
            authenticationModel.RefreshToken = refreshToken;
            return(authenticationModel);
        }
Beispiel #12
0
        public AuthenticationResultModel CreateUser(UserModel i_Model)
        {
            AuthenticationResultModel registerResult = new AuthenticationResultModel
            {
                Error    = eErrors.None,
                HasError = false,
                UserRole = eUserRole.RegularUser
            };

            if (CheckUserRegistrationValidation(i_Model))
            {
                using (MyDiveEntities MyDiveDB = new MyDiveEntities())
                {
                    int userID = MyDiveDB.stp_CreateUser(
                        i_Model.Username,
                        i_Model.Password,
                        i_Model.Email,
                        i_Model.FirstName,
                        i_Model.LastName,
                        i_Model.Association,
                        i_Model.UserLicenseNumber,
                        i_Model.LicenseTypeID,
                        i_Model.Birthday,
                        (int)eUserRole.RegularUser,
                        i_Model.ProfilePicture.Picture,
                        (int)ePictureType.ProfilePicture);
                    registerResult.UserID = userID;
                }
            }
            else
            {
                Logger.Instance.Notify("user info in insufficient", eLogType.Error, JsonConvert.SerializeObject(i_Model));
                registerResult.Error    = eErrors.InsufficientData;
                registerResult.HasError = true;
            }

            return(registerResult);
        }
        public async Task <ResponseModel <TokenModel> > LoginAsync(LoginModel login)
        {
            ResponseModel <TokenModel> response = new ResponseModel <TokenModel>();

            try
            {
                UsersMaster loginUser = _context.UsersMasters.FirstOrDefault(c => c.UserName == login.UserName && c.Password == login.Password);

                if (loginUser == null)
                {
                    response.IsSuccess = false;
                    response.Message   = "Invalid Username And Password";
                    return(response);
                }


                AuthenticationResultModel authenticationResult = await AuthenticateAsync(loginUser);

                if (authenticationResult != null && authenticationResult.Success)
                {
                    response.Data = new TokenModel()
                    {
                        Token = authenticationResult.Token, RefreshToken = authenticationResult.RefreshToken
                    };
                }
                else
                {
                    response.Message   = "Something went wrong!";
                    response.IsSuccess = false;
                }

                return(response);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #14
0
        public AuthenticationResultModel Authenticate(LoginModel login)
        {
            var user = _userService.GetAllThenInclude(
                u => u.Username.ToLower() == login.Username.ToLower(),
                IncludeBuilder <User> .Include(u => u.UserRole).ThenInclude(userRole => userRole.Role).Done()
                )
                       .SingleOrDefault();

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

            //Return null if the user doesn't have a password
            if (string.IsNullOrWhiteSpace(user.PasswordHash))
            {
                return(null);
            }

            //Return null if the password is invalid
            if (!PasswordHelper.ValidatePassword(login.Password, user.PasswordHash))
            {
                return(null);
            }

            //Authentication successful so generate jwt token
            var token = GenerateToken(user);

            var authenticationResultModel = new AuthenticationResultModel
            {
                UserId = user.Id,
                Token  = token
            };

            return(authenticationResultModel);
        }
        public async Task <IActionResult> SubmitAuthenticationResult([FromBody] AddAuthenticationResultModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var transaction = await _dbContext.Transactions.FindAsync(model.TransactionId);

            if (transaction == null)
            {
                return(NotFound());
            }

            var device = _dbContext.Devices.FirstOrDefault(d => d.UserId == transaction.UserId);

            if (device == null)
            {
                return(NotFound());
            }

            var authenticationResult = _dbContext.AuthenticationResults
                                       .FirstOrDefault(a => a.TransactionId == model.TransactionId);

            if (authenticationResult != null)
            {
                return(BadRequest("Authentication result already created for this transaction id"));
            }


            var verification = model.VerifySignature(device.PublicKey);

            if (!verification)
            {
                return(BadRequest());
            }

            authenticationResult = new AuthenticationResultModel
            {
                ActualClientIP         = model.ActualClientIP,
                CertificateFingerprint = model.CertificateFingerprint,
                ClientIPMatch          = model.ClientIPMatch,
                Result        = model.Result,
                ServerIP      = model.ServerIP,
                ServerURI     = model.ServerURI,
                TransactionId = model.TransactionId
            };

            await _dbContext.AddAsync(authenticationResult);

            var result = await _dbContext.SaveChangesAsync();

            if (result != 1)
            {
                return(StatusCode(500));
            }

            // Web apps will continue to query the database using the original transaction id

            return(Ok());
        }