private static ExternalLoginInfo CreateExternalLogin(LoginDto loginDto) { return new ExternalLoginInfo { ExternalUserId = loginDto.ExternalUserId, ProviderKey = loginDto.LoginType.ToString(), ProviderType = loginDto.LoginType }; }
public async Task <ActionResult <UserDto> > LoginAsync(LoginDto loginDto) { var user = await _userManager.FindByEmailAsync(loginDto.Email); if (user == null) { return(Unauthorized(new ApiResponse(401))); } var result = await _signInManager.CheckPasswordSignInAsync(user, loginDto.Password, false); if (!result.Succeeded) { return(Unauthorized(new ApiResponse(401))); } return(new UserDto() { Email = user.Email, DisplayName = user.DisplayName, Token = _tokenService.CreateToken(user) }); }
public async Task <ActionResult <UserDto> > Login(LoginDto loginDto) { var user = await _userManager.Users.Include(p => p.Photos).FirstOrDefaultAsync(x => x.UserName == loginDto.UserName.ToLower()); if (user == null) { return(Unauthorized("user not found")); } var result = await _signInManager.CheckPasswordSignInAsync(user, loginDto.Password, false); if (!result.Succeeded) { return(Unauthorized()); } return(new UserDto { UserName = user.UserName, Token = await _tokenService.CreateToken(user), PhotoUrl = user.Photos.FirstOrDefault(x => x.IsMain)?.Url, KnownAs = user.KnownAs }); }
public void OnClickLoginButton(object sender, EventArgs e) { if (string.IsNullOrEmpty(TxtUsername.StringValue)) { UIErrorHelper.ShowAlert("Please enter valid username", "Alert"); } else if (string.IsNullOrEmpty(TxtPassword.StringValue)) { UIErrorHelper.ShowAlert("Please enter valid password", "Alert"); } else { LoginDto = new LoginDto() { User = TxtUsername.StringValue, Pass = TxtPassword.StringValue, TenantName = ServerDto.Tenant, DomainName = ServerDto.Tenant }; this.Close(); NSApplication.SharedApplication.StopModalWithCode(1); } }
public async Task <ActionResult> Login([FromForm] LoginDto loginDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await signInManager.PasswordSignInAsync( loginDto.Email, loginDto.Password, false, false); if (result.Succeeded) { //generate token var user = userManager.Users.SingleOrDefault( u => u.Email == loginDto.Email); var response = await GenerateJwtToken(user); return(Ok(response)); } else { return(BadRequest(result)); } }
public async Task <UserDto> LoginAsync(LoginDto dto) { if (dto == null) { throw new ArgumentNullException($"Dto cannot be null"); } var user = await unitOfWork.UserRepository.GetAsync(dto.Email, true); if (user == null) { throw new Exception("User not found"); } var valid = await userManager.CheckPasswordAsync(user, dto.Password); if (!valid) { throw new Exception("Password is incorrect"); } return(await GetUserDtoWithTokenAsync(user)); }
public async Task <IActionResult> OnPostLoginUserAsync(LoginDto loginUser) { if (!ModelState.IsValid) { return(RedirectToPage(new { loginError = "Fill all fields" })); } User user = new User { Password = loginUser.Password, Email = loginUser.Email, }; string responseString = await _userApi.AuthentificationToken(user); try { var handler = new JwtSecurityTokenHandler(); var claims = handler.ReadJwtToken(responseString).Claims; string id = claims.FirstOrDefault(claim => claim.Type == "userId").Value; if (!string.IsNullOrEmpty(id)) { HttpContext.Session.SetString("userId", id); } } catch (Exception e) { if (responseString.Length < 50) { var errorResponse = new { loginError = responseString }; return(RedirectToPage(errorResponse)); } else { throw; } } return(RedirectToPage("Product", new { pageNumber = 1 })); }
public async Task <IActionResult> Login(LoginDto login) { var user = await _authRepository.Login(login.Username, login.Password); if (user is null) { return(Unauthorized()); } var claims = new[] { new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.Username) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes( _configuration.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) })); }
/// <summary> /// 用户登录 /// </summary> /// <param name="loginDto"></param> /// <returns></returns> public async Task <Result> LoginAsync(LoginDto loginDto) { Result result = new Result(); try { var data = await UserRepository.FindAsNoTracking().Include(a => a.Account).Where(a => a.EId == loginDto.UserName || a.Account.Mobile == loginDto.UserName).Select(a => new LoginUser() { Id = a.Id, Account = a.EId, OrganizationsId = a.OrganizationsId.ToString(), Password = a.Account.Password, RoleIdList = a.UserRoles.Select(b => b.RoleId).ToList(), State = a.Account.State, Saltd = a.Account.Saltd, Head = a.Account.Head, RealName = a.Account.RealName, Mobile = a.Account.Mobile, Sex = a.Account.Sex, IsLocked = a.IsLocked, LockDuration = a.LockDuration, RegisterTime = a.RegisterTime, LockMessage = a.LockMessage, MerchantId = a.MerchantId, MerchantName = a.Merchant.Name }).FirstOrDefaultAsync(); LoginUserVerify(loginDto, result, data, true); } catch (Exception ex) { result.Code = 50; result.ResultEnum = ResultEnum.Warning; result.Message = ex.Message; } return(result); }
public async Task <IActionResult> Login(LoginDto loginInformation) { var userSeleccionado = await userRepository.ObtenerPorEmail(loginInformation.Email); if (userSeleccionado == null) { return(Unauthorized()); } if (!Utilidades.Utils.VerifyPasswordHash(loginInformation.Password, userSeleccionado.PasswordHash, userSeleccionado.PasswordSalt)) { return(Unauthorized()); } var claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, userSeleccionado.Id.ToString()), new Claim(ClaimTypes.Name, $"{userSeleccionado.Nombres} {userSeleccionado.Apellidos}") }; var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("Miclavedecontraseña")); 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) })); }
public async Task <ActionResult <UserDto> > Login(LoginDto loginDto) { /* This eager loading, It stores the query result in memory as we excute the query. * Eager loading is must where you need data immediately and below query excuation is depends on above query result. * If you write query with differed execuation/ Lazy loading in that case your query will not excute until you add ToList, Count etc. It is useful when you want to chain your queries and you don't want to store your query result in-memory. * You should know when to user eager loading and Lazy loading otherwise it can create problem. * Note:- If you're not sure what to use, then go for eager loading, but it is not efficient program since eager loading stores the query results in-memory. */ //We still have access to Users table but after we added identity in our project we have access to that able via userManager. var user = await userManager.Users .Include(x => x.Photos) .SingleOrDefaultAsync(n => n.UserName == loginDto.Username.ToLower()); if (user == null) { return(Unauthorized("Invalid username or password")); } //After user has enterd correct username we gonna use signInManager to verfiy password of user. var result = await signInManager.CheckPasswordSignInAsync(user, loginDto.Password, false); //If password in incorrect then we will say that user is Unauthorized. if (!result.Succeeded) { return(Unauthorized()); } return(Ok(new UserDto { Username = user.UserName, Token = await tokenService.CreateToken(user), PhotoUrl = user.Photos.FirstOrDefault(x => x.IsMain)?.Url, KnownAs = user.KnownAs, Gender = user.Gender })); }
public async Task <IActionResult> Login([FromBody] LoginDto input) { if (!ModelState.IsValid) { return(BadRequest()); } var isUserValid = await _userService.Login(input); if (!isUserValid) { return(NotFound()); } var userData = await _userService.GetByUsername(input.Username); var user = await _userRepository.GetByIdAsync(userData.Id); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, input.Username), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim("UserId", user.Id.ToString()), new Claim("UserRole", user.IsAdmin ? "Admin" : "User"), }; var token = new JwtSecurityToken ( issuer: _configuration["Issuer"], audience: _configuration["Audience"], claims: claims, //expires: DateTime.UtcNow.AddDays(30), // 30 gün geçerli olacak notBefore: DateTime.UtcNow, signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SigningKey"])),//appsettings.json içerisinde bulunan signingkey değeri SecurityAlgorithms.HmacSha256) ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), success = true, user = userData })); }
public async Task <ResultDto> Login(LoginDto model) { try { var res = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false); if (!res.Succeeded) { return new ResultDto { IsSuccessful = false } } ; var user = await _userManager.FindByEmailAsync(model.Email); await _signInManager.SignInAsync(user, isPersistent : false); var id = ctx.Users.Where(el => el.Email == model.Email).FirstOrDefault().Id; return(new ResultLoginDto { IsSuccessful = true, Token = _jwtTokenService.CreateToken(user), Message = id }); } catch (Exception ex) { return(new ResultDto { IsSuccessful = false, Message = ex.Message }); } }
public async Task <IActionResult> Login([FromBody] LoginDto loginDto) { var user = await userManager.FindByNameAsync(loginDto.Email); if (user != null && await userManager.CheckPasswordAsync(user, loginDto.Password)) { var userRoles = await userManager.GetRolesAsync(user); var authClaims = new List <Claim> { new Claim(ClaimTypes.Email, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; foreach (var userRole in userRoles) { authClaims.Add(new Claim(ClaimTypes.Role, userRole)); } var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"])); var token = new JwtSecurityToken( issuer: _configuration["JWT:ValidIssuer"], audience: _configuration["JWT:ValidAudience"], expires: DateTime.Now.AddHours(3), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } return(Unauthorized()); }
public async Task <object> Authenticate(LoginDto user) { var baseUser = new UserEntity(); if (user != null && !string.IsNullOrWhiteSpace(user.Email) && !string.IsNullOrWhiteSpace(user.Password)) { baseUser = await repository.FindByLogin(user.Email); if (baseUser != null && baseUser.Password == user.Password) { return(SuccessObject(user.Email)); } if (baseUser == null) { return(new { authenticated = false, message = "E-mail não encontrado." }); } if (baseUser.Password != user.Password) { return(new { authenticated = false, message = "Senha incorreta." }); } } return(new { authenticated = false, message = "Authentication failed. " }); }
private void btnLogin_Click(object sender, EventArgs e) { int?selectedBranchId = null; if (comboBranch.SelectedItem != null) { selectedBranchId = GetBranchIdFromComboBox(); } var credentials = new LoginDto { Email = txtboxEmail.Text, Password = txtboxPassword.Text, RememberMe = false }; var validate = LoginRepository.AuthenticateLogin(credentials); var UserInformation = new UserInformationDto() { FirstName = validate.FirstName, LastName = validate.LastName, BranchId = selectedBranchId.Value }; if (validate.IsAuthenticated) { MessageBox.Show(validate.ResponseMessage); var mainForm = new MainForm(UserInformation, ServiceRepository, ItemRepository, VehicleRepository, TransactionRepository, EmployeeRepository, AttendanceRepository); mainForm.LoginForm = this; mainForm.Show(); this.Hide(); } else { MessageBox.Show(validate.ResponseMessage); } }
public async Task <IActionResult> LoginCompany(LoginDto loginDto) { var company = await _repo.LoginCompany(loginDto); if (company == null) { return(Unauthorized()); } var claims = new [] { new Claim(ClaimTypes.NameIdentifier, company.Id.ToString()), new Claim(ClaimTypes.Name, company.Name), new Claim(ClaimTypes.Role, "company") }; var key = new SymmetricSecurityKey(Encoding.UTF8 .GetBytes(_config.GetSection("Jwt:Key").Value)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); var tokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddMonths(1), SigningCredentials = creds }; var tokenHandler = new JwtSecurityTokenHandler(); var token = tokenHandler.CreateToken(tokenDescriptor); return(Ok(new { token = tokenHandler.WriteToken(token) })); }
public async Task <UserDto> LogIn(LoginDto dto) { Profile profile = null; if (dto.IsPhone) { profile = await db.Profiles.Include(x => x.User).SingleAsync(x => x.PhoneNumber == dto.Login); } else if (dto.IsEmail) { profile = await db.Profiles.Include(x => x.User).SingleAsync(x => x.Email == dto.Login); } else { profile = await db.Profiles.Include(x => x.User).SingleOrDefaultAsync(x => x.UserName == dto.Login); } if (profile == null || profile.User.PasswordHash != GetHashString($"{profile.User.SecurityStamp}#{dto.Password}")) { throw new UnauthorizedAccessException(); } var res = new UserDto { Id = profile.Id, UserName = profile.UserName, Email = profile.Email, Phone = profile.PhoneNumber }; res.Roles = await db.UserInRole .Where(x => x.UserId == profile.Id) .Select(x => x.RoleId) .ToArrayAsync(); return(res); }
public async Task <IActionResult> Post(LoginDto informacionLogin) { var usuarioSeleccionado = await _context.Usuarios.FirstOrDefaultAsync(x => x.NroIdentificacion == informacionLogin.NroIdentificacion); if (usuarioSeleccionado == null) { return(Unauthorized()); } if (!Utilidades.Utils.VerifyPasswordHash(informacionLogin.Password, usuarioSeleccionado.PasswordHash, usuarioSeleccionado.PasswordSalt)) { return(Unauthorized()); } var claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, usuarioSeleccionado.Id.ToString()), new Claim(ClaimTypes.Name, $"{usuarioSeleccionado.Nombres} {usuarioSeleccionado.Apellidos}") }; var key = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("Miclavedecontrasena")); 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) })); }
public async Task <ResultDto <LoginUserDto> > LoginAsync(LoginDto dto) { var result = new ResultDto <LoginUserDto>(); try { var data = await _testDB.User.AsNoTracking().Where(x => x.Name.Equals(dto.UserName) || x.Mobile.Equals(dto.UserName)).Select(s => new LoginUserDto() { Id = s.Id, Name = s.Name, Password = s.Password, Status = s.Status, SaltValue = s.SaltValue }).FirstOrDefaultAsync(); if (null == data) { result.Message = "User does not exist"; return(result); } else if (!data.Password.Equals(_encryptUtil.GetMd5By32(dto.Password + data.SaltValue))) { result.Message = "UserNameOrPassword error"; return(result); } result.ActionResult = true; result.Message = "success"; result.Data = data; return(result); } catch (Exception ex) { result.Message = ex.Message; } return(result); }
public async Task <IActionResult> Login([FromBody] LoginDto loginDto) { var user = await _userManager.FindByEmailAsync(loginDto.Login) ?? await _userManager.FindByNameAsync(loginDto.Login); if (user == null || !await _userManager.CheckPasswordAsync(user, loginDto.Password)) { return(Unauthorized()); } var roles = await _userManager.GetRolesAsync(user); var claims = new List <Claim>() { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role))); var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"])); var token = new JwtSecurityToken( issuer: _configuration["JWT:ValidIssuer"], audience: _configuration["JWT:ValidAudience"], expires: DateTime.Now.AddHours(3), claims: claims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); return(Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); }
public async Task <ServiceResponse <string> > Login(LoginDto login) { var response = new ServiceResponse <string>(); try { var user1 = new User(); var user = await _unitOfWork.GetRepository <User>().GetOneAsync(u => u.Referral.ToLower().Equals(login.Username.ToLower())); if (user == null) { response.Success = false; response.Message = $"User '{login.Username}' not found."; } else if (!Password.VerifyHash(login.Password, user.PasswordHash, user.PasswordSalt)) { response.Success = false; response.Message = $"Wrong password for user '{user.Referral}'."; } else if (user.Status != Enums.User.Status.ACTIVE) { response.Success = false; response.Message = $"Not active user '{user.Referral}'."; } else { response.Data = Token.Create(userId: user.RowId.ToString(), username: user.Referral, firstName: user.Name, role: user.Role.ToString(), langCode: user.LanguageCode, tenantId: user.TenantId.ToString()); response.Message = $"Token created for user '{user.Referral}'."; } } catch (Exception ex) { #warning new ExceptionHandler<TEntity>().HandleException(ex); } return(response); }
// credit https://medium.com/@mehanix/lets-talk-security-salted-password-hashing-in-c-5460be5c3aae public async Task <bool> Login(LoginDto dto) { User currentUser = FindUser(dto.UserName); byte[] salt = new byte[16]; byte[] oldHash = new byte[20]; byte[] hashBytes = Convert.FromBase64String(currentUser.Hash); Array.Copy(hashBytes, 0, salt, 0, 16); Array.Copy(hashBytes, 16, oldHash, 0, 20); var pbkdf2 = new Rfc2898DeriveBytes(dto.Password, salt, 10000); var newHash = pbkdf2.GetBytes(20); if (oldHash.SequenceEqual(newHash)) { var claims = new List <Claim>() { new Claim(ClaimTypes.Name, currentUser.Name), new Claim("FriendlyName", currentUser.FriendlyName), new Claim(ClaimTypes.Role, currentUser.Role.ToString()), }; var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties(); await httpAccess.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); return(true); } else { return(false); } }
public LoginDto VerificationLogin(LoginDto Login) { try { var Data = _loginRepo.GetByID(Login.USER_ID); var ReData = Mapper.Map <LoginDto>(Data); var decryptResult = ""; if (Data != null) { var dataReadByte = Convert.FromBase64String(ReData.PASSWORD); var dataString = Encoding.UTF8.GetString(dataReadByte); SerializedPackage serializedPackage = null; var serializer = new XmlSerializer(typeof(SerializedPackage)); using (TextReader TextReader = new StringReader(dataString)) { serializedPackage = (SerializedPackage)serializer.Deserialize(TextReader); } decryptResult = _encrypt.Decrypt(serializedPackage.KeyBase64, serializedPackage.CipherDataBase64); } if (ReData != null && Login.USER_ID.ToLower() == ReData.USER_ID.ToLower() && Login.PASSWORD == decryptResult) { return(ReData); } else { return(null); } } catch (Exception) { throw; } }
public async Task <ActionResult> Login([FromBody] LoginDto model) { var user = await _userManager.FindByNameAsync(model.Username); if (user != null && await _userManager.CheckPasswordAsync(user, model.Password)) { var roleId = _context.UserRoles.Where(x => x.UserId == user.Id).Select(x => x.RoleId).First(); var role = await _context.Roles.FindAsync(roleId); Claim[] claim = new[] { new Claim(JwtRegisteredClaimNames.UniqueName, user.Id), new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName), new Claim(ClaimTypes.Role, role.Name) }; var signinKey = new SymmetricSecurityKey( Encoding.UTF8.GetBytes(_configuration["Jwt:SigningKey"])); int expiryInMinutes = Convert.ToInt32(_configuration["Jwt:ExpiryInMinutes"]); var token = new JwtSecurityToken( issuer: _configuration["Jwt:Site"], audience: _configuration["Jwt:Site"], claims: claim, expires: DateTime.UtcNow.AddMinutes(expiryInMinutes), signingCredentials: new SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256) ); return(Ok( new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo })); } return(Unauthorized()); }
public async Task <object> FindByLogin(LoginDto user) { var baseUser = new UserEntity(); if (user != null && !string.IsNullOrWhiteSpace(user.Email)) { baseUser = await _repository.FindByLogin(user.Email); if (baseUser == null) { return(new { authenticated = false, message = "Falha ao autenticar" }); } else { var identity = new ClaimsIdentity( new GenericIdentity(user.Email), new [] { new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //jti O id do token new Claim(JwtRegisteredClaimNames.UniqueName, user.Email), } ); DateTime createDate = DateTime.Now; DateTime expirationDate = createDate + TimeSpan.FromSeconds(_tokenConfigurations.Seconds); //60 segundos = 1 minuto var handler = new JwtSecurityTokenHandler(); string token = CreateToken(identity, createDate, expirationDate, handler); return(SuccessObject(createDate, expirationDate, token, baseUser)); } } else { return(null); } }
public async Task <ApiResponseDto> Login(LoginDto loginParameters) { ApiResponseDto resp; HttpResponseMessage response = await _httpClient.PostAsJsonAsync("api/Account/Login", loginParameters); using (response) { response.EnsureSuccessStatusCode(); #if ServerSideBlazor if (response.Headers.TryGetValues("Set-Cookie", out var cookieEntries)) { var uri = response.RequestMessage.RequestUri; var cookieContainer = new CookieContainer(); foreach (var cookieEntry in cookieEntries) { cookieContainer.SetCookies(uri, cookieEntry); } var cookies = cookieContainer.GetCookies(uri).Cast <Cookie>(); foreach (var cookie in cookies) { await _jsRuntime.InvokeVoidAsync("jsInterops.setCookie", cookie.ToString()); } } #endif var content = await response.Content.ReadAsStringAsync(); resp = JsonConvert.DeserializeObject <ApiResponseDto>(content); } return(resp); }
public async Task <IActionResult> Login([FromBody] LoginDto applicationUser) { // Trim email, NOT PASSWORD applicationUser.Email = applicationUser.Email.Trim(); if (ModelState.IsValid) { // Get identity RequestMessageResponse errorResponse = new RequestMessageResponse() { Success = false, Message = "" }; ClaimsIdentity identity = await _jwtService.GetClaimsIdentity(applicationUser, errorResponse); if (identity == null) { return(BadRequest(errorResponse)); } // Serialize and return the response var response = new { id = identity.Claims.Single(c => c.Type == "id").Value, access_token = _jwtService.GenerateEncodedToken(applicationUser.Email, identity), expires_in = _jwtService.GetValidForTotalSeconds(), }; // Return result var json = JsonConvert.SerializeObject(response, _serializerSettings); return(new OkObjectResult(json)); } return(BadRequest(new RequestMessageResponse() { Success = false, Message = "Bad request" })); }
private async Task <LoginDto> IssueAccessToken(UserAccount user) { //var keyLoginTokenPrefix = "FiiiShop:Token:"; //var keyLoginToken = $"{keyLoginTokenPrefix}{user.Id}"; //var accessToken = AccessTokenGenerator.IssueToken(user.Id.ToString()); //RedisHelper.StringSet(Constant.REDIS_TOKEN_DBINDEX, keyLoginToken, accessToken, TimeSpan.FromSeconds(AccessTokenGenerator.DefaultExpiryTime)); ProfileRouter pRouter = new ProfileRouterDAC().GetRouter(user.CountryId); var profile = GetProfileByAccountId(pRouter, user.Id); string countryCode = ""; if (profile.Country.HasValue) { var country = new CountryDAC().GetById(user.CountryId); if (country != null) { countryCode = country.Code; } } var result = new LoginDto { UserId = user.Id.ToString("N"), Email = user.Email, LastName = profile.LastName, FirstName = profile.FirstName, CountryCode = countryCode, ProvinceName = profile.State, CityName = profile.City, Address = profile.Address1 + (string.IsNullOrEmpty(profile.Address1 + profile.Address2) ? "" : " ") + profile.Address2, Postcode = profile.Postcode, Cellphone = profile.Cellphone }; return(await Task.FromResult(result)); }
public async Task <ActionResult <UserDto> > Login(LoginDto loginDto) { var user = await userManager.Users .SingleOrDefaultAsync(x => x.Email == loginDto.Email.ToLower()); if (user == null) { return(Unauthorized("Invalid username")); } var result = await signInManager .CheckPasswordSignInAsync(user, loginDto.Password, false); if (!result.Succeeded) { return(Unauthorized()); } return(new UserDto { Email = user.Email, Token = await _tokenService.CreateToken(user) }); }
public async Task <IActionResult> Login(LoginDto details) { //determen witch screen to display var user = await _repository.checkData(details); if (user is null) { ViewBag.Error = @"Wrong Username or Password"; return(View()); } HttpContext.Session.SetComplex("User", user); if (user is Administrator) { return(RedirectToAction("AdministratorHomePage")); } if (user is StorageWorker) { return(RedirectToAction("WarehousePage", "Warehouse")); } else { return(RedirectToAction("Index", "Home")); } }
public async Task<RequestResult<LoginTokenDto>> Login(string email, string password) { ResponseBool _response = new ResponseBool { Success = false, ErrorInfo = "" }; var c = Config.Init(); IWarehouseReceiptClient wrc = WarehouseReceiptClientFactory.Create(c.WREndPoint, c.VAOKey); try { LoginDto dto = new LoginDto(email, password); var logInDetals = await wrc.LoginClient.GetLoginToken(dto); if (logInDetals.Result.Token != null) { return logInDetals; } } catch (Exception ex) { _response.ErrorInfo = "Eagc Login Failed \n" + ex.Message; } return null; }
public IToken Post(LoginDto loginDto) { IToken token; this.authenticationService.Login(loginDto.UserName, loginDto.Password, loginDto.ToString(), out token); return token; }