public HttpResponseMessage Login([FromBody] LoginModel loginModel) { string email = loginModel.email; string password = loginModel.password; CustomResponse response; User loginUser = _repository.Login(loginModel); if (loginUser != null) { //LoginUser var userToken = new UserTokenDTO() { email = email, password = password, expireDate = DateTime.Now.AddDays(TOKEN_EXPIRE_DAY) }; //Serializing userToken var jsonString = JsonConvert.SerializeObject(userToken); // Token generation var token = FTH.Extension.Encrypter.Encrypt(jsonString, LoginUtility.PRIVATE_KEY); LoginResponseDTO userDTO = GenericMapper.MapToLoginResponseDTO(loginUser, token); response = ResponseMessageHelper.CreateResponse(HttpStatusCode.OK, false, userDTO, ConstantResponse.LOGIN_SUCCESS); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.OK, response)); } else { response = ResponseMessageHelper.CreateResponse(HttpStatusCode.Unauthorized, true, null, ConstantResponse.LOGIN_FAILED); return(Request.CreateResponse <CustomResponse>(HttpStatusCode.Unauthorized, response)); } }
public async Task <UserProfileDTO> GetUserByAccessToken(UserTokenDTO token) { try { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(JwtOptions.KEY); var tokenVakidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; var principle = tokenHandler.ValidateToken(token.AccessToken, tokenVakidationParameters, out SecurityToken securityToken); if (securityToken is JwtSecurityToken jwtSecurityToken && jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) { var email = principle.FindFirst(ClaimTypes.Email)?.Value; var user = await Database.UserRepository.GetByEmail(email); return(await GetUserDTO(user)); } } catch (Exception) { return(new UserProfileDTO()); } return(new UserProfileDTO()); }
public async Task <IActionResult> PostUser([FromBody] UserCreateDTO userCreateDTO) { _logger.Info("Executing PostUser() method..."); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // Custom Validation var isEmailExists = await _userService.IsEmailExistsAsync(userCreateDTO.Email); if (isEmailExists) { ModelState.AddModelError("Email", "Podany adres email istnieje w bazie."); return(BadRequest(ModelState)); } bool result = await _userService.CreateUserAsync(userCreateDTO); if (!result) { _logger.Error("Error during user registration"); return(BadRequest()); } _logger.Info(string.Format("User {0} {1} has been added ", userCreateDTO.FirstName, userCreateDTO.LastName)); var user = await this._userManager.FindByNameAsync(userCreateDTO.Email); var userToken = new UserTokenDTO { Token = this._oAuthService.GetUserAuthToken(userCreateDTO.Email, user.Id.ToString()) }; return(StatusCode((int)HttpStatusCode.Created, userToken)); }
public static string GetEmailByToken(string token) { //Decrypts token key var jsonString = FTH.Extension.Encrypter.Decrypt(token, LoginUtility.PRIVATE_KEY); //Deserializes json string to get UserToken object UserTokenDTO loginUser = JsonConvert.DeserializeObject <UserTokenDTO>(jsonString); return(loginUser.email); }
public async Task Login(UserTokenDTO userTokenDTO) { await _js.SetInLocalStorage(TOKENKEY, userTokenDTO.Token); await _js.SetInLocalStorage(EXPIRATIONTOKENKEY, userTokenDTO.Expiration.ToString()); var authState = BuildAuthenticationState(userTokenDTO.Token); NotifyAuthenticationStateChanged(Task.FromResult(authState)); }
/// <summary> /// This method is use for login user /// </summary> /// <param name="loginDTO">Login DTOs pass</param> /// <returns></returns> public async Task <BaseResponse> ValidateUserAsync(LoginDTO loginDTO) { try { string ConnectionString = _config[_iStringConstants.MyConnectionString]; BaseResponse baseResponse = new BaseResponse(); UserTokenDTO userTokenAC = new UserTokenDTO(); using (DeepakdbContext deepakDBContext = new DeepakdbContext()) { /*var parameterOut=new SqlParameter * { * ParameterName= * }*/ var data = await deepakDBContext.UserDetail.FromSqlRaw("spGetUserDetailByEmail @Email=@p0", parameters : new[] { loginDTO.Email }).ToListAsync(); if (data != null) { data.ForEach(x => new UserTokenDTO() { Id = x.Id, FirstName = x.FirstName, LastName = x.LastName, ZipCode = x.ZipCode, Email = x.Email, MobileNumber = x.MobileNumber, Password = x.Password }); if (PasswordHashUtill.VerifyHashedPassword(userTokenAC.Password, loginDTO.Password)) { baseResponse.StatusCode = (int)EnumList.ResponseType.Success; baseResponse.Data = userTokenAC; } else { baseResponse.Message = _iStringConstants.InvalidPassword; baseResponse.StatusCode = (int)EnumList.ResponseType.Error; baseResponse.Data = null; } } else { baseResponse.Message = _iStringConstants.LoginCredentailWrong; baseResponse.StatusCode = (int)EnumList.ResponseType.Error; baseResponse.Data = null; } return(baseResponse); } } catch (Exception ex) { throw ex; } }
// Mark a user as Authenticated for program public async Task MarkUserAsAuthenticated(UserTokenDTO token) { await localStorageService.SetItemAsync("accessToken", token.AccessToken); var userProfile = await userServices.GetUserByAccessToken(token.AccessToken); var identity = GetClaimsIdentity(userProfile); var claimsPrincipal = new ClaimsPrincipal(identity); NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(claimsPrincipal))); }
public IActionResult RefreshToken() { string token = this.HttpContext.Request.Headers["Authorization"].ToString().Substring("Bearer ".Length); System.Collections.Generic.IDictionary <string, string> claims = this._oAuthService.GetClaims(token); var newToken = new UserTokenDTO { Token = this._oAuthService.GetUserAuthToken(claims["unique_name"], claims["UserId"]) }; return(Ok(newToken)); }
public async Task <ActionResult <UserTokenDTO> > LoginAsync(LoginDTO dto) { try { UserTokenDTO user = await _service.LoginAsync(dto.Name, dto.Password); return(user); } catch (UnauthorizedAccessException e) { return(Unauthorized(e.Message)); } }
public override void OnAuthorization(HttpActionContext actionContext) { //This is for Skipping auth if needed if (actionContext.ActionDescriptor.GetCustomAttributes <SkipAuthFilterAttribute>().Any()) { return; } if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request.CreateResponse <CustomResponse>(HttpStatusCode.Unauthorized, response); } else { UserTokenDTO loginUser = null; try { //Gets token key from header var tokenKey = actionContext.Request.Headers.Authorization.Parameter; //Decrypts token key var jsonString = FTH.Extension.Encrypter.Decrypt(tokenKey, LoginUtility.PRIVATE_KEY); //Deserializes json string to get UserToken object loginUser = JsonConvert.DeserializeObject <UserTokenDTO>(jsonString); #region - Old Basic Authorization - //Converting token key base64 to string and encode it as UTF8 //var emailPassword = Encoding.UTF8.GetString(Convert.FromBase64String(tokenKey)); //var userInfoArray = emailPassword.Split(':'); //var email = userInfoArray[0]; //var password = userInfoArray[1]; #endregion } catch { actionContext.Response = actionContext.Request.CreateResponse <CustomResponse>(HttpStatusCode.Unauthorized, response); return; } User user = LoginUtility.GetUserByEmailAndPassword(loginUser.email, loginUser.password); if (user != null && DateTime.Compare(DateTime.Now, loginUser.expireDate) < 0) { Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(loginUser.email), null); } else { actionContext.Response = actionContext.Request.CreateResponse <CustomResponse>(HttpStatusCode.Unauthorized, response); } } }
/// <summary> /// This method is use for new user signup /// </summary> /// <param name="userDetailDTO"></param> /// <returns></returns> public async Task <BaseResponse> SignUpAsync(UserDetailDTO userDetailDTO) { try { //string ConnectionString = _config[_iStringConstants.MyConnectionString]; BaseResponse baseResponse = new BaseResponse(); UserTokenDTO userTokenAC = new UserTokenDTO(); using (DeepakdbContext deepakDBContext = new DeepakdbContext()) { //deepakDBContext.Query<T>().AsTracking(). var data = await Task.Run(() => deepakDBContext .Database.ExecuteSqlRaw("spInsertUserDetail @FirstName=@p0, @LastName=@p1,@Email=@p2,@Password=@p3,@MobileNumber=@p4,@Address_Line1=@p5,@Address_Line2=@p6, @ZipCode=@p7, @CreatedBy=@p8", parameters: new [] { userDetailDTO.FirstName, userDetailDTO.LastName, userDetailDTO.Email, PasswordHashUtill.HashPassword(userDetailDTO.Password), userDetailDTO.MobileNumber, userDetailDTO.AddressLine1, userDetailDTO.AddressLine2, userDetailDTO.ZipCode.ToString(), userDetailDTO.CreatedBy } /*new SqlParameter("@FirstName", userDetailDTO.FirstName), * new SqlParameter("@LastName", userDetailDTO.FirstName), * new SqlParameter("@Email", userDetailDTO.Email), * new SqlParameter("@Password",PasswordHashUtill.HashPassword( userDetailDTO.Password)), * new SqlParameter("@MobileNumber", userDetailDTO.MobileNumber), * new SqlParameter("@Address_Line1", userDetailDTO.AddressLine1), * new SqlParameter("@Address_Line2", userDetailDTO.AddressLine2), * new SqlParameter("@ZipCode", userDetailDTO.ZipCode), * new SqlParameter("@CreatedBy", userDetailDTO.CreatedBy)*/ )); if (data != null) { baseResponse.StatusCode = 1; baseResponse.Message = _iStringConstants.AddedSuccessfully; // Need to ask how to get DBCONTEXT status code from store procedure } if (baseResponse.StatusCode == 1) { return(StatusBuilder.ResponseSuccessStatus(null, baseResponse.Message)); } return(StatusBuilder.ResponseFailStatus(null, baseResponse.Message)); } } catch (Exception ex) { throw ex; } }
public async Task <UserTokenDTO> RefreshToken(UserTokenDTO token) { string serializedToken = JsonConvert.SerializeObject(token); var requestMessage = new HttpRequestMessage(HttpMethod.Post, "RefreshToken"); requestMessage.Content = new StringContent(serializedToken); requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var response = await httpClient.SendAsync(requestMessage); var responseStatusCode = response.StatusCode; var responseBody = await response.Content.ReadAsStringAsync(); var returnedToken = JsonConvert.DeserializeObject <UserTokenDTO>(responseBody); return(returnedToken != null ? returnedToken : null); }
private void GetToken() { HttpClient client = InstanceClient(false); UserAuthDTO auth = new UserAuthDTO(); auth.Email = GetSettingsValue("EmailAuth"); auth.Password = GetSettingsValue("PasswordAuth"); HttpResponseMessage response = client.PostAsJsonAsync("api/UserAuth/login2", auth).Result; if (response.IsSuccessStatusCode) { var product = response.Content.ReadAsStringAsync(); UserTokenDTO tokenDTO = JsonConvert.DeserializeObject <UserTokenDTO>(product.Result); token = tokenDTO.Token; } }
public async Task <BaseResponse> UpdateProfileAsync(UserProfileDTO userProfileDTO, long longloggedInUserId) { try { BaseResponse baseResponse = new BaseResponse(); UserTokenDTO userTokenAC = new UserTokenDTO(); using (DeepakdbContext deepakDBContext = new DeepakdbContext()) { var data = await Task.Run(() => deepakDBContext .UserDetail.FromSqlRaw("spUpdateUserDetail", new SqlParameter("@Id", userProfileDTO.Id), new SqlParameter("@FirstName", userProfileDTO.FirstName), new SqlParameter("@LastName", userProfileDTO.LastName), new SqlParameter("@Email", userProfileDTO.Email), new SqlParameter("@MobileNumber", userProfileDTO.MobileNumber), new SqlParameter("@Address_Line1", userProfileDTO.AddressLine1), new SqlParameter("@Address_Line2", userProfileDTO.AddressLine2), new SqlParameter("@ZipCode", userProfileDTO.ZipCode), new SqlParameter("@@LoggedInUserId", longloggedInUserId) ) ); if (data != null) { baseResponse.StatusCode = 1; baseResponse.Message = _iStringConstants.AddedSuccessfully; // Need to ask how to get DBCONTEXT status code from store procedure } if (baseResponse.StatusCode == 1) { return(StatusBuilder.ResponseSuccessStatus(null, baseResponse.Message)); } return(StatusBuilder.ResponseFailStatus(null, baseResponse.Message)); } } catch (Exception ex) { throw ex; } }
public UserTokenDTO LoginUser(string username, string password) { UserTokenDTO response = null; using (var entities = new UCAInvestDBEntities()) { var dbResponse = entities.users.SingleOrDefault(t => t.username == username); if (dbResponse != null) { string salt = dbResponse.salt; if (dbResponse.password == CryptoServices.SHA256Encrypt(password, salt)) { response = GiveMeUniqueAvailableToken(dbResponse.user_id); } } } return(response); }
/// <inheritdoc /> public string BuildAccessToken(UserTokenDTO user, IList <string> roles) { var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()), new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Email, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()) }; var roleClaims = roles.Select(r => new Claim(ClaimTypes.Role, r)); claims.AddRange(roleClaims); var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConfigurations.Key)); var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); var tokenDescriptor = new JwtSecurityToken(_jwtConfigurations.Issuer, _jwtConfigurations.Issuer, claims, expires: DateTime.Now.AddMinutes(_jwtConfigurations.ExpirationInMinutes), signingCredentials: credentials); return(new JwtSecurityTokenHandler().WriteToken(tokenDescriptor)); }
public async Task <IActionResult> LoginUserAsync([Required] UserLoginDTO userLoginDto) { SignInResult result = await this._signInManager.PasswordSignInAsync(userLoginDto.Username, userLoginDto.Password, false, false); if (result.IsLockedOut) { return(Forbid("User Account is locked out!")); } if (!result.Succeeded) { return(BadRequest("Sign in failed!")); } User user = await this._userManager.FindByNameAsync(userLoginDto.Username); var userToken = new UserTokenDTO { Token = this._oAuthService.GetUserAuthToken(userLoginDto.Username, user.Id.ToString()) }; return(Ok(userToken)); }
public LoginMessageOutputDTO CheckLoginCredential(LoginMessageInputDTO loginMessageInput) { var person = _personRepository.GetWithUsernameAndPassword(loginMessageInput.Username, loginMessageInput.Password); if (person == null) { return(new LoginMessageOutputDTO(false, new PersonCredentialDTO(L("Wrong_UsernameOrPassword"), "", null))); } //If username and password are correct -> get user information #region Check the author token of user. If user already have token -> update token, else -> create a new token for this user PersonCredentialDTO personCredentialDto = new PersonCredentialDTO(); UserTokenDTO userTokenDto = _tokenAppService.CheckUserTokenByUsername(loginMessageInput.Username); personCredentialDto.Name = person.Name; personCredentialDto.AuthToken = userTokenDto.AuthToken; #endregion #region Get list activities that user have permission to act with system if (person.RoleId.HasValue) { personCredentialDto.Activities = new List <string>(); foreach (var roleDistribution in person.Role.RoleDistributions) { personCredentialDto.Activities.Add(roleDistribution.Activity.ActivityName); } } #endregion return(new LoginMessageOutputDTO(true, personCredentialDto)); }
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(context.Options.AuthenticationType); user = _account.CheckUser(context.UserName, context.Password); if (user.Id != null) { identity.AddClaim(new Claim(ClaimTypes.Role, user.Role)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); identity.AddClaim(new Claim(ClaimTypes.Name, user.Username)); AuthenticationTicket ticket = new AuthenticationTicket(identity, null); context.Validated(identity); } else { context.SetError("invalid_grant", "Provided username and password is incorrect"); //return; } return(Task.FromResult <object>(null)); }
public async Task <BaseTokenModel> LoginAsync([FromBody] LoginDTO loginDTO) { BaseTokenModel baseTokenModel = new BaseTokenModel(); try { if (loginDTO == null) { baseTokenModel.Message = _iStringConstant.InvalidRequest; baseTokenModel.StatusCode = (int)EnumList.ResponseType.Error; } else { BaseResponse responseModel = await _iAccountRepository.ValidateUserAsync(loginDTO); if (responseModel.StatusCode == (int)EnumList.ResponseType.Success) { UserTokenDTO userData = (UserTokenDTO)responseModel.Data; var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("KeyForSignInDeepakAPI@123")); var signingCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); //For calime which we get the data from accessToken var claims = new[] { new Claim("FirstName", userData.FirstName), new Claim("LastName", userData.LastName), new Claim("MobileNumber", userData.MobileNumber), new Claim(ClaimTypes.NameIdentifier, userData.Id.ToString()), new Claim("Email", userData.Email) }; //Create token based on our claims and signingCredentials var tokeOptions = new JwtSecurityToken( issuer: _config["Jwt:ValidIssuer"], audience: _config["Jwt:ValidIssuer"], claims: claims, expires: DateTime.Now.AddDays(1), signingCredentials: signingCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); baseTokenModel.Id = userData.Id.ToString(); baseTokenModel.FirstName = userData.FirstName; baseTokenModel.LastName = userData.LastName; baseTokenModel.Email = userData.Email; baseTokenModel.MobileNumber = userData.MobileNumber; baseTokenModel.AccessToken = tokenString; baseTokenModel.Message = _iStringConstant.LoginSuccessfull; baseTokenModel.StatusCode = Convert.ToInt32(EnumList.ResponseType.Success); } else { baseTokenModel.Message = responseModel.Message; baseTokenModel.StatusCode = responseModel.StatusCode; } } } catch (Exception ex) { _logger.LogError(ex.Message); baseTokenModel.Message = ex.Message; baseTokenModel.StatusCode = Convert.ToInt32(EnumList.ResponseType.Exception); } return(baseTokenModel); }
// GET: Login public ActionResult Index(string email, string senha, string erro) { string _erro = null; UserTokenDTO dadosUser = null; if (email != null && senha != null) { string ApiBaseUrl = "http://localhost:53387/"; // endereço da sua api string MetodoPath = "token"; //caminho do método a ser chamado string dataPost = ""; dataPost += "username="******"&" + "password="******"&" + "grant_type=password"; //AlunoDTO _aluno = null;//Verificar depois try { var url = ApiBaseUrl + MetodoPath; var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "application/x-www-form-urlencoded"; httpWebRequest.Method = "POST"; //Passando dados para o httpwebRequest. var dados = Encoding.UTF8.GetBytes(dataPost); httpWebRequest.ContentLength = dados.Length; //precisamos escrever os dados post para o stream. using (var stream = httpWebRequest.GetRequestStream()) { stream.Write(dados, 0, dados.Length); stream.Close(); } var teste = httpWebRequest.UserAgent; //ler e exibir a resposta. using (var resposta = httpWebRequest.GetResponse()) { var streamDados = resposta.GetResponseStream(); //Instãncia e para os dados para SreamReader. StreamReader reader = new StreamReader(streamDados); string objResposta = reader.ReadToEnd(); UserTokenDTO resultado = JsonConvert.DeserializeObject <UserTokenDTO>(objResposta); dadosUser = resultado; } } catch (Exception e) { switch (e.HResult) { case -2146233079: _erro = "Login ou senha estão incorretas!"; break; default: _erro = e.Message; break; } } } if (_erro != null) { ViewBag.erroVal = _erro; ModelState.AddModelError("ErroLogin", _erro); } if (dadosUser != null) { CrieSessao ses = new CrieSessao(); ses.access_token = dadosUser.access_token; ses.username = dadosUser.Username; return(RedirectToAction("Index", "Home")); } return(View()); }