public async Task OpenSecureChannelAsync(string username, string password, bool forceTokenUpdate = true) { Tuple <string, string> keys = await GetRSAKeys(); // Sends public key and get server's public key in return var serverRsaKey = await ExchangeRsaKeyAsync(keys.Item1); // Generates a 3DES key var tripleDesKey = await _cryptoService.GenerateTripleDESKeyAsync(); // Encrypt the 3DES key with server RSA public key var encryptedTripleDesKey = await _cryptoService.EncryptRSAAsync(Convert.ToBase64String(tripleDesKey), serverRsaKey.Key); // Sends the encrypted key to the server and gets an 3DES key in return var serverTripleDesMessage = await ExchangeTripleDesKeyAsync(Convert.ToBase64String(encryptedTripleDesKey), keys.Item2); // Merges both 3DES key to generate a new key used by both sides var mergedKey = _cryptoService.GenerateCombinedTripleDesKey(tripleDesKey, Convert.FromBase64String(serverTripleDesMessage.Key)); _cryptoService.RegisterMergedKey(serverRsaKey.Id, mergedKey); var userData = new UserAuthenticationModel() { Username = username, Password = password }; await RequestJwtAsync(userData, forceTokenUpdate); authenticatedUser = userData; }
public async Task <HubConnection?> ConnectAsync(string username, string password) { await CloseConnectionAsync(); HttpResponseMessage response; if (_jwt?.IsExpired ?? false) { Console.WriteLine("token expired"); var refreshContent = new StringContent(Convert.ToBase64String(Encoding.UTF8.GetBytes(_jwt.RefreshToken)), Encoding.UTF8, "application/json"); response = await _httpClient.PostAsync($"{_baseUrl}/{_jwt.RefreshUrl}", refreshContent); if (response.IsSuccessStatusCode) { var serializedJwt = await response.Content.ReadAsStringAsync(); var jwt = JsonSerializer.Deserialize <SecureJwtModel>(serializedJwt); _jwt = jwt.TokenModel; } } else { var userModel = new UserAuthenticationModel { Username = username, Password = password }; var content = new StringContent(JsonSerializer.Serialize(userModel), Encoding.UTF8, "application/json"); response = await _httpClient.PostAsync($"{_baseUrl}/jwt/requestjwt", content); if (response.IsSuccessStatusCode) { var serializedJwt = await response.Content.ReadAsStringAsync(); var jwt = JsonSerializer.Deserialize <SecureJwtModel>(serializedJwt); _jwt = jwt.TokenModel; _connection = new HubConnectionBuilder() .WithUrl($"{_baseUrl}/blazorhub?access_token={_jwt.Token}", opt => { opt.SkipNegotiation = true; opt.Transports = HttpTransportType.WebSockets; }) .Build(); _connection.On <string>("GuestEntered", id => { _notificationManager.ShowNotificationMessage($"User {id} just entered", "New User"); return(Task.CompletedTask); }); _connection.On <string>("GuestLeft", id => { _notificationManager.ShowNotificationMessage($"User {id} just left", "New User"); return(Task.CompletedTask); }); await _connection.StartAsync(); } } return(_connection); }
public UserAuthenticationModel Get(string userName, string password) { var user = new UserAuthenticationModel(); user = _userRepository .Find(n => n.UserName.Equals(userName) && n.Password.Equals(password)) .Select(n => new UserAuthenticationModel { Id = n.Id, Name = n.FirstName + " " + n.LastName, RoleId = n.RoleId, IsAuthenticated = true }).FirstOrDefault(); if (user != null && user.IsAuthenticated) { return(user); } else { return new UserAuthenticationModel { IsAuthenticated = false } }; }
/// <inheritdoc /> public async Task <UserAuthenticationModel> DecryptTicket(string encryptedTicket) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UserAuthenticationModel)); Uri endpointUrl = new Uri($"{_generalSettings.BridgeAuthnApiEndpoint}tickets"); string userData = JsonSerializer.Serialize(new UserAuthenticationModel { EncryptedTicket = encryptedTicket }); HttpResponseMessage response = await _client.PostAsync(endpointUrl, new StringContent(userData, Encoding.UTF8, "application/json")); if (response.StatusCode == HttpStatusCode.OK) { Stream stream = await response.Content.ReadAsStreamAsync(); UserAuthenticationModel userAuthentication = serializer.ReadObject(stream) as UserAuthenticationModel; return(userAuthentication); } if (response.StatusCode == HttpStatusCode.ServiceUnavailable) { throw new SblBridgeResponseException(response, "SBL Bridge replied with status: ServiceUnavailable."); } _logger.LogError("Getting the authenticated user failed with status code {StatusCode}", response.StatusCode); return(null); }
public async Task <IActionResult> LoginAsync([FromBody] UserAuthenticationModel userModel) { if (ModelState.IsValid) { // get the user, if the password matches then we can continue on. var user = _userManager.Users.SingleOrDefault(u => u.NormalizedEmail == userModel.Email.ToUpper()); if (await _userManager.CheckPasswordAsync(user, userModel.Password)) { var userRolesClaim = (await _userManager.GetRolesAsync(user)).Select(r => new Claim(ClaimTypes.Role, r)); var claimsIdentity = new ClaimsIdentity( CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role); claimsIdentity.AddClaim(new Claim("UserId", user.Id.ToString())); claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); claimsIdentity.AddClaims(userRolesClaim); var authProperties = new AuthenticationProperties(); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); _logger.LogInformation(1, "User logged in."); return(Ok()); } } // If we got this far, something failed return(BadRequest()); }
public ActionResult Index() { UserAuthenticationModel userModel = new UserAuthenticationModel(); ViewBag.ListUser = new SelectList(serviceObj.GetAllUsers().ToList(), "UserID", "UserName"); return(View(userModel)); }
public PartialViewResult Select(string Email, string UserId) { LocationBL.UserAuthentication = "UserAuthentication"; UserAuthenticationModel = AuthenticationBL.SelectUserAuthentication(UserId, Email); LocationBL.UserAuthentication = string.Empty; return(PartialView("~/Views/UserAuthentication/Partial/UserLocations.cshtml", UserAuthenticationModel)); }
public async System.Threading.Tasks.Task <PartialViewResult> SaveUser(UserAuthenticationModel UserAuthenticationModel) { List <tbl_LocationAuthentication> LocationAuth = AuthenticationBL.LocationAuthenticationGetByEmail(User.Identity.Name); if (LocationAuth.Count > 0) { tbl_ManagerUserAuthentication ManagerUserAuthentication = new tbl_ManagerUserAuthentication(); ManagerUserAuthentication.Manager_EmailID = User.Identity.Name; ManagerUserAuthentication.User_EmailID = UserAuthenticationModel.User_EmailID; ManagerUserAuthentication.MID = LocationAuth.FirstOrDefault().Id; if (UserAuthenticationModel.UserName != string.Empty && UserAuthenticationModel.User_EmailID != string.Empty) { var user = new ApplicationUser { UserName = UserAuthenticationModel.User_EmailID, Email = UserAuthenticationModel.User_EmailID }; var result = await UserManager.CreateAsync(user, UserAuthenticationModel.Password); if (result.Succeeded) { string resultInsert = AuthenticationBL.AspNetManagerInsert(ManagerUserAuthentication); return(PartialView("~/Views/AddUsers/Partial/Users.cshtml", UserAuthenticationModel)); } else { AddErrors(result); } } } return(PartialView("~/Views/AddUsers/Partial/Users.cshtml", UserAuthenticationModel)); }
public bool ValidateUserNamePassword(UserAuthenticationModel userAuthentication) { var result = userData.GetAllUser() .FirstOrDefault(x => x.UserName == userAuthentication.UserName && x.Password == userAuthentication.Password); return(result != null); }
public async Task <Response> Authenticate([FromBody] LoginViewModel userModel) { var user = await _userOperations.AuthenticateAsync(userModel.Username, userModel.Password); if (user == null) { return new Response { ErrorMessage = "Username or password is incorrect", Status = ResponseStatus.Error, } } ; var userToken = GenerateUserToken(user); var result = new UserAuthenticationModel { Id = user.Id, Username = user.UserName, FirstName = user.FirstName, LastName = user.LastName, Token = userToken }; return(new Response { Result = result, Status = ResponseStatus.Ok, }); }
/// <inheritdoc /> public async Task <UserAuthenticationModel> DecryptTicket(string encryptedTicket) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UserAuthenticationModel)); Uri endpointUrl = new Uri($"{_generalSettings.BridgeAuthnApiEndpoint}tickets"); _logger.LogInformation($"Authentication - Before getting userdata"); string userData = JsonConvert.SerializeObject(new UserAuthenticationModel { EncryptedTicket = encryptedTicket }); _logger.LogInformation($"Authentication - endpoint {endpointUrl}"); HttpResponseMessage response = await _client.PostAsync(endpointUrl, new StringContent(userData, Encoding.UTF8, "application/json")); _logger.LogInformation($"Authentication - response {response.StatusCode}"); if (response.StatusCode == HttpStatusCode.OK) { Stream stream = await response.Content.ReadAsStreamAsync(); UserAuthenticationModel userAuthentication = serializer.ReadObject(stream) as UserAuthenticationModel; return(userAuthentication); } // If user is not authenticated redirect to login _logger.LogInformation($"UserNotAuthenticated"); _logger.LogError($"Getting the authenticated user failed with statuscode {response.StatusCode}"); return(null); }
async Task <Result> IAuthenticationPort.Login(UserAuthenticationModel userAuthenticationModel) { var userAuthentication = _mapper.Map <UserAuthenticationDto>(userAuthenticationModel); var result = await Result.Ok() .And(async() => await _authenticationApplicationService.Login(userAuthentication)) .Map <AuthenticationDto, AuthenticationModel>((data) => _mapper.Map <AuthenticationModel>(data)); return(result); }
// [ValidateAccountStatus] public ActionResult Authenticate(UserAuthenticationModel model) { if (_usersRepo.Authenticate(model)) { return(RedirectToAction("Index", "Home")); } ViewBag.Message = "Email si / sau parola incorecte."; return(View()); }
public ActionResult Authenticate() { if (ApplicationHelper.LoggedUser != null) { return(RedirectToAction("Index", "Home")); } var model = new UserAuthenticationModel(); return(View(model)); }
public void GetMaskedIdentity_EmptyString_ReturnsEmptyPlaceholder() { var auth = new UserAuthenticationModel() { Identity = String.Empty }; var result = auth.GetMaskedIdentity(); Assert.AreEqual(UserAuthenticationModel.EMPTY_MASKED_VALUE, result); }
public IActionResult Authenticate([FromBody] UserAuthenticationModel model) { var user = _userService.Authenticate(model.Username, model.Password); if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } return(Ok(user)); }
public async Task <IActionResult> SignUp(UserAuthenticationModel userToCreate) { bool result = await _accountRepository.RegisterAsync(StaticDetails.AuthAPIPath + "signUp/", userToCreate); if (result == false) { return(View()); } return(RedirectToAction("SignIn")); }
public static bool CheckUserCredentials(UserAuthenticationModel model) { if (model == null) { return(false); } if (model.Password != null && model.Username != null) { return(true); } return(false); }
public void GetMaskedIdentity_MultipleLengths_AlwaysMasksPartOfString(string identity, string expectedHash) { var auth = new UserAuthenticationModel() { Identity = identity }; var result = auth.GetMaskedIdentity(); Assert.IsTrue(result.EndsWith("X")); Assert.AreEqual(expectedHash, result); }
public async Task <ActionResult> AuthenticateUser(string goTo) { if (!IsValidRedirectUri(new Uri(goTo).Host)) { return(Redirect($"{_generalSettings.GetBaseUrl}")); } string encodedGoToUrl = HttpUtility.UrlEncode($"{_generalSettings.PlatformEndpoint}authentication/api/v1/authentication?goto={goTo}"); if (Request.Cookies[_generalSettings.SblAuthCookieName] == null) { return(Redirect($"{_generalSettings.GetSBLRedirectEndpoint}?goTo={encodedGoToUrl}")); } string encryptedTicket = Request.Cookies[_generalSettings.SblAuthCookieName]; UserAuthenticationModel userAuthentication = await _cookieDecryptionService.DecryptTicket(encryptedTicket); if (userAuthentication != null && userAuthentication.IsAuthenticated) { List <Claim> claims = new List <Claim>(); string issuer = _generalSettings.PlatformEndpoint; claims.Add(new Claim(ClaimTypes.NameIdentifier, userAuthentication.UserID.ToString(), ClaimValueTypes.String, issuer)); claims.Add(new Claim(AltinnCoreClaimTypes.UserId, userAuthentication.UserID.ToString(), ClaimValueTypes.String, issuer)); claims.Add(new Claim(AltinnCoreClaimTypes.UserName, userAuthentication.Username, ClaimValueTypes.String, issuer)); claims.Add(new Claim(AltinnCoreClaimTypes.PartyID, userAuthentication.PartyID.ToString(), ClaimValueTypes.Integer32, issuer)); claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticateMethod, userAuthentication.AuthenticationMethod.ToString(), ClaimValueTypes.String, issuer)); claims.Add(new Claim(AltinnCoreClaimTypes.AuthenticationLevel, ((int)userAuthentication.AuthenticationLevel).ToString(), ClaimValueTypes.Integer32, issuer)); ClaimsIdentity identity = new ClaimsIdentity(_generalSettings.GetClaimsIdentity); identity.AddClaims(claims); ClaimsPrincipal principal = new ClaimsPrincipal(identity); _logger.LogInformation("Platform Authentication before creating JwtCookie"); string serializedToken = await GenerateToken(principal); CreateJwtCookieAndAppendToResponse(serializedToken); _logger.LogInformation("Platform Authentication after creating JwtCookie"); _logger.LogInformation($"TicketUpdated: {userAuthentication.TicketUpdated}"); if (userAuthentication.TicketUpdated) { Response.Cookies.Append(_generalSettings.SblAuthCookieName, userAuthentication.EncryptedTicket); } return(Redirect(goTo)); } return(Redirect($"{_generalSettings.GetSBLRedirectEndpoint}?goTo={encodedGoToUrl}")); }
public ActionResult Login(FormCollection form) { UserAuthenticationModel user = new UserAuthenticationModel(); var id = user.Login(form["username"], form["pass"]); if (id == -1) { return(View("Index")); } else { return(RedirectToAction("Index", "Home")); } }
protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); var user = User as ClaimsPrincipal; if (user != null) { var claims = user.Claims.ToList(); var sessionClaim = claims.FirstOrDefault(o => o.Type == Constants.UserSession); if (sessionClaim != null) { UserAuthModel = sessionClaim.Value.ToObject <UserAuthenticationModel>(); } } }
public async Task <IActionResult> Authenticate([FromBody] UserAuthenticationModel user) { var canLogin = await _userService.IsCorrectPassword(user.Username, user.Password); if (canLogin) { return(BadRequest(new { message = "Username or password is incorrect" })); } var userdata = await _userService.Get(user.Username); var result = userdata.GenerateToken(); return(Ok(result)); }
internal static List <Claim> CreateClaim(UserAuthenticationModel userAuthModel, params string[] roles) { var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, userAuthModel.UserId.ToString()), new Claim(ClaimTypes.Name, userAuthModel.DisplayName), new Claim(Constants.UserSession, userAuthModel.ToJson()) }; //for multiple roles foreach (var role in roles) { claims.Add(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, Constants.Issuer)); } return(claims); }
public string AuthentificateUserFromPhone([FromBody] UserAuthenticationModel value) { if (DataChecker.CheckUserCredentials(value)) { string connectionString = ConfigurationManager.ConnectionStrings["SilentConnection"].ConnectionString; if (SqlHelper.LogInUser(connectionString, Base64Helper.Decode(value.Username), Base64Helper.Decode(value.Password))) { return(Base64Helper.Encode("success")); } else { return(Base64Helper.Encode("fail")); } } else { return(Base64Helper.Encode("fail")); } }
private string BuildRefreshJwt(UserAuthenticationModel userModel) { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("SomeSecureRandomKey")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, userModel.Username), new Claim(JwtRegisteredClaimNames.Nbf, new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds().ToString()), new Claim(JwtRegisteredClaimNames.Exp, new DateTimeOffset(DateTime.Now.AddDays(5)).ToUnixTimeSeconds().ToString()), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var token = new JwtSecurityToken( new JwtHeader(creds), new JwtPayload(claims) ); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public async Task <IActionResult> GetJwt( [FromBody] UserAuthenticationModel model, [FromServices] IUserRepository userRepository, [FromServices] IUrlHelper urlHelper) { if (ModelState.IsValid) { var user = await userRepository.GetUserAsync(model.Username); if (user == null) { user = new Shared.Domain.User { Username = model.Username, Password = model.Password }; await userRepository.AddUserAsync(user); } if (user != null && user.Password == model.Password) { var refresh = BuildRefreshJwt(model); refreshTokens[refresh] = model.Username; return(Json(new SecureJwtModel { OriginId = 0, TokenModel = new TokenModel { Token = BuildJwt(model), RefreshToken = refresh, RefreshUrl = urlHelper.Action("RefreshJwt").ToLower(), Expires = DateTime.Now.AddMinutes(1) } })); } else { return(Unauthorized()); } } else { return(BadRequest(ModelState.ValidationState)); } }
public ActionResult Save(FormCollection FormCollection, UserAuthenticationModel UserAuthenticationModel) { string result = string.Empty; LocationBL.UserAuthentication = "UserAuthentication"; LocationBL.EmailID = User.Identity.Name; UserAuthenticationModel.lstLocations = LocationBL.GetAll(); string ULLocationIDs = string.Empty; string MLLocationIDs = string.Empty;; for (int i = 0; i < UserAuthenticationModel.lstLocations.Count; i++) { string ULLocId = UserAuthenticationModel.lstLocations[i].LocationID + "UL" + i; string MLLocId = UserAuthenticationModel.lstLocations[i].LocationID + "ML" + i; var ULColl = FormCollection[ULLocId].Split(','); var MLColl = FormCollection[MLLocId].Split(','); if (ULColl.Length > 0) { bool ULChecked = ULColl[0].Contains("true"); if (ULChecked) { ULLocationIDs = (UserAuthenticationModel.lstLocations[i].LocationID.Trim()) + "," + ULLocationIDs; } } if (MLColl.Length > 0) { bool MLChecked = MLColl[0].Contains("true"); if (MLChecked) { MLLocationIDs = (UserAuthenticationModel.lstLocations[i].LocationID.Trim()) + "," + MLLocationIDs; } } } AuthenticationBL.SaveAuthentication(UserAuthenticationModel, ULLocationIDs, MLLocationIDs); LocationBL.UserAuthentication = string.Empty; UserAuthenticationModel.lstUseridsbyManager = AuthenticationBL.SelectUserId(User.Identity.Name); UserAuthenticationModel.lstAspNetRole = AuthenticationBL.AspNetRoleGetAll(); result = "Success"; return(View("Index", UserAuthenticationModel)); }
public async Task DecryptTicket_SblBridgeResponseIsBadRequest_ReturnsNull() { // Arrange HttpResponseMessage httpResponseMessage = new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = "Service Unavailable" }; InitializeMocks(httpResponseMessage); HttpClient httpClient = new HttpClient(_handlerMock.Object); SblCookieDecryptionService target = new SblCookieDecryptionService(httpClient, _generalSettingsOptions.Object, _logger.Object); // Act UserAuthenticationModel actual = await target.DecryptTicket("random and irrelevant bytes"); // Assert _handlerMock.VerifyAll(); Assert.Null(actual); }
public bool Authenticate(UserAuthenticationModel model) { var userInDb = _db.Users.Include(u => u.Role).Where(u => u.Email == model.Email).FirstOrDefault(); if (userInDb != null && EncryptPassword(model.Password) == userInDb.Password) { if (userInDb.IsDeleted) { userInDb.IsDeleted = false; _db.SaveChanges(); } HttpContext.Current.Session.Add("LoggedUser", new LoggedUser() { Id = userInDb.Id, Email = userInDb.Email, Name = string.Concat(userInDb.LastName, " ", userInDb.FirstName), RoleId = userInDb.RoleId }); return(true); } return(false); }