public IActionResult Authenticate([FromBody] UserAuthDto userModel) { try { var user = _userService.Authenticate(userModel.Phone, userModel.Password); if (user == null) { return(BadRequest(new { message = "Phone or password is incorrect" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenString = tokenHandler.WriteToken(token); // return basic user info (without password) and token to store client side return(Ok(new UserAuthDto { Id = user.Id, Phone = user.Phone, Role = user.Role, Token = tokenString })); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public UserAuthDto ValidateUser(UserLoginDto user) { UserAuthDto ret = new UserAuthDto(); Users authUser = null; string Pass = user.UserPassword; string ePass = Encrypt.GetSHA256(Pass); //se conecta a la base de datos para verificar las datos del usuario en cuestion using (var db = new CruzRojaContext()) authUser = db.Users.Include(u => u.Persons) .Include(u => u.Roles) .Include(u => u.Estates) .ThenInclude(u => u.LocationAddress) .Include(u => u.Estates.EstatesTimes) .ThenInclude(u => u.Times) .ThenInclude(u => u.Schedules) .Where(u => u.UserDni == user.UserDni && u.UserPassword == ePass).FirstOrDefault(); if (authUser != null) { ret = _mapper.Map <UserAuthDto>(authUser); //si los datos son correctos se crea el objeto del usuario autentificado } return(ret); //retornamos el valor de este objeto }
public async Task LoginCheckPasswordUnauthorizedStatus() { //Arrange var userForLogin = new UserAuthDto { Username = "******", Password = "******" }; var userManager = GetMockUserManager(); var signInManager = GetMockSignInManager(); var user = new User { Id = 1, UserName = "******" }; AuthController controller = new AuthController(configMock.Object, userManager.Object, signInManager.Object); userManager.Setup(um => um.FindByNameAsync("test")) .Returns(Task.FromResult(user)).Verifiable(); signInManager.Setup(sm => sm.CheckPasswordSignInAsync(user, userForLogin.Password, It.IsAny <bool>())) .Returns(Task.FromResult(Microsoft.AspNetCore.Identity.SignInResult.Failed)).Verifiable(); //Act var action = await controller.Login(userForLogin) as UnauthorizedResult; //Assert userManager.Verify(um => um.FindByNameAsync("test"), Times.Once); signInManager.Verify(sm => sm.CheckPasswordSignInAsync(user, userForLogin.Password, It.IsAny <bool>()), Times.Once); Assert.Equal(401, action.StatusCode); }
public ApiResultDto GetToken([FromBody] UserAuthDto param) { TokenDto token; string userAgent = ""; var ip = GetIPAddress(); if (Request.Headers.Contains("User-Agent")) { var headers = Request.Headers.GetValues("User-Agent"); var sb = new System.Text.StringBuilder(); foreach (var header in headers) { sb.Append(header); // Re-add spaces stripped when user agent string was split up. sb.Append(" "); } userAgent = sb.ToString().Trim(); } var rslt = new AuthBLL().Login(param.name, param.password, userAgent, ip, out token); if (rslt == ERROR_CODE.SUCCESS) { return(ResultSuccess(token)); } return(ResultError(rslt)); }
public async Task <UserLoggedDto> Authenticate(UserAuthDto userAuthDto) { var user = await _userRepository.GetByAsync(u => u.Login == userAuthDto.Login && u.Password == userAuthDto.Password); if (user == null) { throw new Exception("Login or password are invalid. Try again"); } // authentication successful so generate jwt token var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, user.Id.ToString()), new Claim(ClaimTypes.Role, user.Role) }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var student = await _studentRepository.GetByAsync(s => s.UserId == user.Id); UserLoggedDto userLoggedDto = new UserLoggedDto { UserId = user.Id, Login = user.Login, Role = user.Role, Token = tokenHandler.WriteToken(token), StudentId = student?.StudentId }; return(userLoggedDto); }
public async Task InvokeAsync(HttpContext context) { Console.WriteLine(">>>>>>>>>>>>>>>>>>> from class middle ware "); var cookies = context.Request.Cookies; //TODO: we need to figure out some way that we don't have to replicate the logic for authorization here. if (cookies.TryGetValue(Constants.AuthCookieName, out var value)) { Console.WriteLine($"path: {context.Request.Path}\nmethod: {context.Request.Method}"); UserAuthDto userAuthDto = null; if (_userUtils.TryValidatedAuthCookie(value, out userAuthDto)) { var shouldThrottle = await _rateLimiter.ShouldThrottle(context.Request.Method, context.Request.Path, userAuthDto.UserId.ToString()); if (shouldThrottle) { Console.WriteLine("throttling the api"); context.Response.StatusCode = 429; return; } } } Console.WriteLine("next middleware in the pipleine is called"); await _next(context); }
public Object validateTeacher(TeacherDto teacherDto) { BaseResponseDto <UserAuthDto> baseResponseDto = new BaseResponseDto <UserAuthDto>(); Notification notification = new Notification(); Teacher autTheacher = null; autTheacher = this.teacherRepository.GetByDni(teacherDto.Dni, teacherDto.SchoolID); if (autTheacher.Dni == null) { notification.addError("El DNI: " + teacherDto.Dni + " no existe o aún no está registrado"); return(this.getApplicationErrorResponse(notification.getErrors())); } if (!Hashing.CheckMatch(autTheacher.password, teacherDto.Password)) { notification.addError("La contraseña es incorrecta"); return(this.getApplicationErrorResponse(notification.getErrors())); } UserAuthDto userAuthDto = null; userAuthDto = this.buildUserAuthDto(autTheacher); List <UserAuthDto> usersAuthDto = new List <UserAuthDto>(); usersAuthDto.Add(userAuthDto); baseResponseDto.Data = usersAuthDto; return(baseResponseDto); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { _connectedUser = JsonConvert.DeserializeObject <UserAuthDto>(e.Parameter.ToString()); await AddCoordinatorViewModel.LoadAsync(_connectedUser); base.OnNavigatedTo(e); }
internal async Task LoadAsync(UserAuthDto userAuthDto, List <Volunteer> volunteers, List <School> schools) { try { ProggressBarVisible(true); foreach (var school in schools) { _schools.Add(new BaseEntityDto <School>(school)); } _volunteers = volunteers; _connectedUser = userAuthDto; _connectedUserAuth = _connectedUser; _httpClientService.SetAuthorizationHeaderToken(_httpClientService.HttpClient, _connectedUser.Token); foreach (var value in await LoadVolunteersAsync(_volunteers.Take(5).ToList())) { _volunteersDto.Add(value); _allVolunteersDto.Add(value); } RaisePropertyChanged(nameof(Volunteers)); ProggressBarVisible(false); await LoadRemainingVolunteers(5); } catch (Exception ex) { MessageDialog messageDialog = new MessageDialog("An error occured: " + ex.Message); await messageDialog.ShowAsync(); } finally { ProggressBarVisible(false); } }
public async Task <IActionResult> AuthenticateAsync([FromBody] UserAuthDto dto) { var user = await _unitOfWork.UserRepository .SingleOrDefaultAsync(x => x.UserName.Equals(dto.userName, StringComparison.InvariantCultureIgnoreCase)); if (user == null) { return(BadRequest(new { Error = "Username or password is incorrect" })); } var result = await _signInManager.PasswordSignInAsync(user, dto.Password, false, false); if (!result.Succeeded) { return(BadRequest(new { Error = "Username or password is incorrect" })); } var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.JwtSecret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.GivenName, user.FirstName), new Claim(ClaimTypes.Email, user.Email), }), Expires = DateTime.UtcNow.AddDays(7), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return(Ok(token)); }
public SetStageDialog(UserAuthDto userAuthDto, AdminEntity adminEntity) { this.InitializeComponent(); _httpClientService = new HttpClientService(); _httpClientService.SetAuthorizationHeaderToken(_httpClientService.HttpClient, userAuthDto.Token); _adminEntity = adminEntity; }
internal async Task LoadAsync(UserAuthDto connectedUser, List <Volunteer> volunteers, List <School> schools) { try { foreach (var volunteer in volunteers) { _volunteersDto.Add(new BaseEntityDto <Volunteer>(volunteer)); } foreach (var school in schools) { _schools.Add(new BaseEntityDto <School>(school)); } ProggressBarVisible(true); _connectedUserAuth = connectedUser; _volunteers = volunteers; _httpClientService.SetAuthorizationHeaderToken(_httpClientService.HttpClient, _connectedUserAuth.Token); foreach (var value in await EntityLoadingHelper.LoadProjectsAsync(_volunteers.Take(1).ToList(), _httpClientService, _projects.ToList())) { _projects.Add(value); _allProjects.Add(value); } RaisePropertyChanged(nameof(Projects)); RaisePropertyChanged(nameof(SelectedMainType)); ProggressBarVisible(false); await LoadRemainingProjects(1); } catch (Exception ex) { MessageDialog messageDialog = new MessageDialog("An error occured: " + ex.Message); await messageDialog.ShowAsync(); } }
public String BuildJwtToken(UserAuthDto userAuthDto) { var claimsdata = new[] { new Claim(JwtRegisteredClaimNames.Sub, userAuthDto.name), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim("shortName", userAuthDto.shortName), new Claim("fullName", userAuthDto.fullName), new Claim("teacherID", userAuthDto.id.ToString()), new Claim("roleID", userAuthDto.roleID.ToString()), new Claim("schoolID", userAuthDto.schoolID.ToString()) }; //var claimsdata = new[] { new Claim(ClaimTypes.Name, userAuthDto.name) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)); var signInCred = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature); var token = new JwtSecurityToken( issuer: "mysite.com", audience: "mysite.com", expires: DateTime.Now.AddMinutes(1), claims: claimsdata, signingCredentials: signInCred ); var tokenString = new JwtSecurityTokenHandler().WriteToken(token); return(tokenString); }
public bool TryValidatedAuthCookie(string authCookie, out UserAuthDto userAuthDto) { userAuthDto = null; if (string.IsNullOrEmpty(authCookie)) { return(false); } try { userAuthDto = new JwtBuilder() .WithAlgorithm(new HMACSHA256Algorithm()) .WithSecret(Constants.JwtSecret) .MustVerifySignature() .Decode <UserAuthDto>(authCookie); } catch (TokenExpiredException ex) { return(false); } if (userAuthDto == null || userAuthDto.UserId < 1) { return(false); } return(true); }
//token generator private string BuildToken(UserAuthDto auth) { //get secret key var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); //add claims var claims = new Claim[] { new Claim("userId", auth.UserId.ToString()), new Claim("roles", auth.Role) }; //generate token var token = new JwtSecurityToken ( issuer: configuration["Jwt:Issuer"], audience: configuration["Jwt:Issuer"], expires: DateTime.Now.AddMinutes(30), signingCredentials: creds, claims: claims ); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public async Task <string> AuthenticateAsync(UserAuthDto data) { var result = await _usersRepository.SignInAsync(data); if (result == false) { return(null); } var tokenKey = Encoding.ASCII.GetBytes(_key); var tokenHandler = new JwtSecurityTokenHandler(); var tokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(new List <Claim>() { new Claim(ClaimTypes.Name, data.Email) }), Expires = DateTime.UtcNow.AddHours(12), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); return(tokenHandler.WriteToken(token)); }
public async Task LoadAsync(BaseEntityDto <Coordinator> coordinator) { ProggressBarVisible(true); _connectedUserAuth = coordinator.ConnectedUser; _connectedUser = _connectedUserAuth; _httpClientService.SetAuthorizationHeaderToken(_httpClientService.HttpClient, _connectedUser.Token); _connectedUserJson = JsonConvert.SerializeObject(_connectedUser, Formatting.Indented); if (_connectedUser.Role == "Admin") { AddCoordCommandVisibility = Visibility.Visible; } else { AddCoordCommandVisibility = Visibility.Collapsed; } _reportCoordView = new ReportsVolView(_connectedUserAuth); OnPropertyChanged(nameof(AddCoordCommandVisibility)); List <Volunteer> getVolunteers = await LoadItems(); _volunteerCoordView = new VolunteerCoordView(_connectedUser, _volunteers, _schools); _projectsCoordView = new ProjectVolView(_connectedUser, _volunteers, _schools); ProggressBarVisible(false); _volunteersDto = await LoadVolunteerDtosAsync(getVolunteers); _volunteerCoordView = new VolunteerCoordView(_volunteersDto, _schools); var projects = await LoadProjectsAsync(_volunteers); _projectsCoordView = new ProjectVolView(projects, _volunteers, _schools); }
protected async override void OnNavigatedTo(NavigationEventArgs e) { _connectedUser = JsonConvert.DeserializeObject <UserAuthDto>(e.Parameter.ToString()); await SchoolsAndTeachersViewModel.Load(_connectedUser); base.OnNavigatedTo(e); }
public IActionResult Authenticate([FromBody] UserAuthDto userAuthDto) { try { var user = _userService.Authenticate(userAuthDto.Username, userAuthDto.Password); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, user.Id) }), Expires = DateTime.UtcNow.AddDays(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature) }; var token = tokenHandler.CreateToken(tokenDescriptor); var tokenToSend = tokenHandler.WriteToken(token); return(Ok(new UserAuthenticateModel { Id = user.Id, Username = user.Username, Token = tokenToSend })); } catch (AppException e) { return(BadRequest(new { message = e.Message })); } }
public async Task <ActionResult <string> > Login([FromForm] UserAuthDto user) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var emailConfig = await _configService.GetSettingsAsync(); if (emailConfig.EmailConfirmIsOn) { var isEmailConfirmed = await _emailConfirmService.ValidateConfirmedEmailAsync(user); if (!isEmailConfirmed) { return(BadRequest(new { msg = "Email not confirmed" })); } } var result = await _accountService.LoginAsync(user); if (result.SignInResult.Succeeded) { return(Ok(result.Jwt)); } return(BadRequest(result.SignInResult)); }
public async Task LoadAsync(UserEditDto userEditDto) { _userEditDtoJson = JsonConvert.SerializeObject(userEditDto); _userEditDto = userEditDto; _connectedUser = userEditDto.ConnectedUser; _httpClientService.SetAuthorizationHeaderToken(_httpClientService.HttpClient, _connectedUser.Token); if (_userEditDto.IsNew == null) { isNewSchool = true; isNewTeacher = true; } else { switch (_userEditDto.Type) { case Shared.Helpers.TypeEnum.School: isNewSchool = false; _school = await _httpClientService.GetTAsync <School>($"school/getbyIdInclude/{_userEditDto.Entity.Id}"); var mediaSchool = _school.Medias.OrderByDescending(x => x.UploadDate).FirstOrDefault(); _schoolImagePath = await GetFilePath(_httpClientService, "school", _school, mediaSchool); _schoolProfileImage = _schoolImagePath != null ? new BitmapImage(new Uri(_schoolImagePath)) : null; break; case Shared.Helpers.TypeEnum.Teacher: isNewTeacher = false; _teacher = await _httpClientService.GetTAsync <Teacher>($"teacher/getbyIdInclude/{_userEditDto.Entity.Id}"); SelectedSchool = new SchoolDto(_teacher.School); var media = _teacher.Medias.OrderByDescending(x => x.UploadDate).FirstOrDefault(); _teacherImagePath = await GetFilePath(_httpClientService, "teacher", _teacher, media); _teacherProfileImage = _teacherImagePath != null ? new BitmapImage(new Uri(_teacherImagePath)) : null; break; default: isNewTeacher = true; isNewSchool = true; break; } RaisePropertyChanged(nameof(School)); RaisePropertyChanged(nameof(Teacher)); RaisePropertyChanged(nameof(SelectedSchool)); RaisePropertyChanged(nameof(ProfileImageSource)); RaisePropertyChanged(nameof(TeacherProfileImage)); } var getSchools = await _httpClientService.GetListTAsync <School>("school/getall"); foreach (var school in getSchools) { _schools.Add(new SchoolDto(school)); } _teachersList = getSchools.Select(s => s.Principle).Distinct().ToList(); _selectTeachers = new ObservableCollection <string>(_teachersList); RaisePropertyChanged(nameof(Schools)); RaisePropertyChanged(nameof(SelectTeachers)); }
public async Task <bool> SignInAsync(UserAuthDto userAuthDto) { var User = await _userManager.FindByIdAsync(userAuthDto.Email); var Result = await _signInManager.PasswordSignInAsync(User, userAuthDto.Password, userAuthDto.RememberMe, false); return(Result.Succeeded); }
public ReportsVolView(UserAuthDto connectedUserAuth) { this.InitializeComponent(); _connectedUserAuth = connectedUserAuth; ReportsViewModel = App.Container.Resolve <ReportsViewModel>(); DataContext = ReportsViewModel; Loaded += ReportsVolView_Loaded; }
protected async override void OnNavigatedTo(NavigationEventArgs e) { _userAuthDto = JsonConvert.DeserializeObject <UserAuthDto>(e.Parameter as string); _userAuthDtoJson = e.Parameter as string; _httpClientService.SetAuthorizationHeaderToken(_httpClientService.HttpClient, _userAuthDto.Token); var vehicles = JsonConvert.DeserializeObject <List <VehicleEntity> >(await _httpClientService.GetAsync("Vehicles/all")); listVehicles.ItemsSource = vehicles; }
public async Task LoadAsync(UserAuthDto connectedUser) { _connectedUserJson = JsonConvert.SerializeObject(connectedUser); _connectedUser = connectedUser; _httpClientService.SetAuthorizationHeaderToken(_httpClientService.HttpClient, _connectedUser.Token); _schools = await GetSchoolDtos(_httpClientService); RaisePropertyChanged(nameof(Schools)); }
public ProjectVolView(BaseEntityDto <Volunteer> volunteer) { this.InitializeComponent(); _volunteer = volunteer; _connectedUser = volunteer.ConnectedUser; ProjectVolViewModel = App.Container.Resolve <ProjectVolViewModel>(); DataContext = ProjectVolViewModel; Loaded += ProjectVolView_Loaded; }
public void Load(BaseEntityDto <Volunteer> volunteerDto) { _volunteerDto = volunteerDto; _connectedUser = volunteerDto.ConnectedUser; _generalInfoView = new GeneralInfoView(_volunteerDto); _projectVolView = new ProjectVolView(_volunteerDto); _frameContent = _generalInfoView; RaisePropertyChanged(nameof(FrameContent)); }
internal void LoadAsync(UserAuthDto userAuthDto) { _connectedUserAuth = userAuthDto; if (_connectedUserAuth.Role == "Vol") { _signInButtonVisibility = Visibility.Visible; RaisePropertyChanged(nameof(SignInButtonVisibility)); } }
public async Task <IActionResult> Authenticate([FromBody] UserAuthDto userParam) { var token = await _userService.AuthenticateAsync(userParam.Username, userParam.Password); if (token == null) { return(BadRequest(new { message = "Username or Password is incorrect" })); } return(Ok(token)); }
//This method is use to register user to our database public async Task <User> RegisterUser(UserAuthDto user) { user.UserTypeId = Convert.ToInt32(UserTypeNames.Customer); var mappedData = _mapper.Map <User>(user); _context.Users.Add(mappedData); await _context.SaveChangesAsync(); return(mappedData); }