public async Task <IActionResult> Login(LDAPLogin record) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("Index", "Report")); } var user = userService.Authenticate(config["LDAP:Url"], record); if (user != null) { user.Role = roleService.GetRole(user.RoleId); var expiredDateTime = DateTime.Now.AddMinutes(90); var claims = new List <Claim> { new Claim(ClaimTypes.Sid, Guid.NewGuid().ToString() + "5T14nHTu12GTh1tCh0D3pTr4i"), new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()), new Claim(ClaimTypes.Name, user.Account), new Claim(ClaimTypes.Role, user.Role.Name), new Claim(ClaimTypes.Expired, expiredDateTime.Ticks.ToString()) }; ClaimsIdentity userIdentity = new ClaimsIdentity(claims, "Authorization"); ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity); await HttpContext.SignInAsync(principal); return(RedirectToAction("Index", "Report")); } ViewData["LoginErrorMessage"] = "Login error! Please verify your LDAP account."; return(View()); }
// Call LDAP + Create New User for first login public User Authenticate(string loginUrl, LDAPLogin loginInfo) { try { using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(loginUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); var authen = new { application = "che", username = loginInfo.Username, password = loginInfo.Password }; var content = new StringContent(JsonConvert.SerializeObject(authen), Encoding.UTF8, "application/json"); var response = client.PostAsync("api/authen", content).Result; if (response.IsSuccessStatusCode) { var responseString = response.Content.ReadAsStringAsync(); responseString.Wait(); var authenRecord = JsonConvert.DeserializeObject <LDAPInfo>(responseString.Result); var user = GetUser(loginInfo.Username); if (user == null) { user = new User() { Account = loginInfo.Username, Status = 1, RoleId = 1, SchoolId = 1, DepartmentId = 1, TitleId = 1, EducationBackgroundId = 1, DateCreated = DateTime.Now, DateModified = DateTime.Now }; userRepository.Add(user); SaveUser(); } return(user); } else { System.Console.WriteLine(response); return(null); } } } catch (Exception ex) { System.Console.WriteLine(ex.ToString()); return(null); } }
public ActionResult Index(Client client) { string[] keys = Request.Form.AllKeys; if (!keys.Contains("user")) { ModelState.AddModelError("user", "Username is a required field"); } if (!keys.Contains("password")) { ModelState.AddModelError("password", "Password is a required field"); } if (keys.Contains("user") && keys.Contains("password")) { string user = Request.Form["user"]; string password = Request.Form["password"]; if (!LDAPLogin.TryLDAPLogin(user, password)) { ModelState.AddModelError("user", "Invalid username/password"); } ModelState.SetModelValue("user", new ValueProviderResult(user, user, CultureInfo.CurrentCulture)); } ITransaction transaction = null; try { transaction = SQLProviderFactory.GenerateTransaction(); if (!client.Save(transaction)) { foreach (Error error in client.Errors) { ModelState.AddModelError(error.FieldName, error.Message); } } if (!ModelState.IsValid) { transaction.Rollback(); return(View(client)); } transaction.Commit(); return(View("Success")); } finally { if (transaction != null && transaction.IsActive) { transaction.Rollback(); } } }
public LDAPLogin ParseLogin(string login) { if (string.IsNullOrEmpty(login)) { return(null); } string username; string domain = null; if (login.Contains("\\")) { var splited = login.Split('\\'); if (!splited.Any() || splited.Length != 2) { return(null); } domain = splited[0]; username = splited[1]; } else if (login.Contains("@")) { var splited = login.Split('@'); if (!splited.Any() || splited.Length != 2) { return(null); } username = splited[0]; domain = splited[1]; } else { username = login; } var result = new LDAPLogin(username, domain); return(result); }
public List <KeyValuePair <UserInfo, LDAPObject> > FindLdapUsers(LDAPLogin ldapLogin) { var settings = Settings; var listResults = new List <KeyValuePair <UserInfo, LDAPObject> >(); var ldapHelper = WorkContext.IsMono ? new NovellLdapHelper() : new SystemLdapHelper() as LdapHelper; var fullLogin = ldapLogin.ToString(); var searchTerm = ldapLogin.Username.Equals(fullLogin) ? string.Format("({0}={1})", settings.LoginAttribute, ldapLogin.Username) : string.Format("(|({0}={1})({0}={2}))", settings.LoginAttribute, ldapLogin.Username, fullLogin); var users = ldapHelper.GetUsersByAttributesAndFilter( settings, searchTerm) .Where(user => user != null) .ToList(); if (!users.Any()) { return(listResults); } var loginString = ldapLogin.ToString(); foreach (var ldapObject in users) { var currentUser = CreateUserInfo(ldapObject); if (Equals(currentUser, Core.Users.Constants.LostUser)) { continue; } if (string.IsNullOrEmpty(ldapLogin.Domain)) { listResults.Add(new KeyValuePair <UserInfo, LDAPObject>(currentUser, ldapObject)); continue; } string accessableLogin = null; var dotIndex = currentUser.Email.LastIndexOf(".", StringComparison.Ordinal); if (dotIndex > -1) { accessableLogin = currentUser.Email.Remove(dotIndex); } if (!currentUser.Email.Equals(loginString, StringComparison.InvariantCultureIgnoreCase) && (accessableLogin == null || !accessableLogin.Equals(loginString, StringComparison.InvariantCultureIgnoreCase))) { continue; } listResults.Add(new KeyValuePair <UserInfo, LDAPObject>(currentUser, ldapObject)); } return(listResults); }
public ActionResult Index(FormCollection collection) { string[] keys = collection.AllKeys; List <string> missingParameters = new List <string>(); if (!keys.Contains("client_id") || string.IsNullOrEmpty(collection["client_id"])) { missingParameters.Add("client_id"); } if (!keys.Contains("redirect_uri") || string.IsNullOrEmpty(collection["redirect_uri"])) { missingParameters.Add("redirect_uri"); } if (!keys.Contains("state") || string.IsNullOrEmpty(collection["state"])) { missingParameters.Add("state"); } if (missingParameters.Any()) { StringBuilder builder = new StringBuilder(); foreach (string missingParameter in missingParameters) { if (builder.Length > 0) { builder.Append(", "); } builder.Append(missingParameter); } return(OAuthError("invalid_request", "The following parameters were not specified: " + builder.ToString())); } string clientID = collection["client_id"]; string redirectUri = collection["redirect_uri"]; string state = collection["state"]; Search <Client> clientSearch = new Search <Client>(new StringSearchCondition <Client>() { Field = "ClientIdentifier", SearchConditionType = SearchCondition.SearchConditionTypes.Equals, Value = clientID }); Client client = clientSearch.GetReadOnly(null, new List <string>() { "RedirectionURI" }); if (client == null) { return(OAuthError("unauthorized_client", "The client is not authorized to request an authorization code using this method.")); } if (!client.ContainsRedirectURI(redirectUri)) { return(OAuthError("invalid_request", "The Redirect URI is not valid")); } if (!keys.Contains("user")) { ModelState.AddModelError("user", "Username is a required field"); } if (!keys.Contains("password")) { ModelState.AddModelError("password", "Password is a required field"); } if (!ModelState.IsValid) { ModelState.SetModelValue("client_id", new ValueProviderResult(clientID, clientID, CultureInfo.CurrentCulture)); ModelState.SetModelValue("redirect_uri", new ValueProviderResult(redirectUri, redirectUri, CultureInfo.CurrentCulture)); ModelState.SetModelValue("state", new ValueProviderResult(state, state, CultureInfo.CurrentCulture)); if (keys.Contains("user")) { ModelState.SetModelValue("user", new ValueProviderResult(collection["user"], collection["user"], CultureInfo.CurrentCulture)); } return(View(collection)); } string user = collection["user"]; string password = collection["password"]; if (!LDAPLogin.TryLDAPLogin(user, password)) { ModelState.SetModelValue("client_id", new ValueProviderResult(clientID, clientID, CultureInfo.CurrentCulture)); ModelState.SetModelValue("redirect_uri", new ValueProviderResult(redirectUri, redirectUri, CultureInfo.CurrentCulture)); ModelState.SetModelValue("state", new ValueProviderResult(state, state, CultureInfo.CurrentCulture)); ModelState.SetModelValue("user", new ValueProviderResult(collection["user"], collection["user"], CultureInfo.CurrentCulture)); ModelState.AddModelError("user", "Incorrect username/password"); return(View(collection)); } Search <User> userSearch = new Search <User>(new StringSearchCondition <User>() { Field = "Username", SearchConditionType = SearchCondition.SearchConditionTypes.Equals, Value = user }); User dbUser = userSearch.GetReadOnly(null, new string[] { "UserID" }); if (dbUser == null) { dbUser = new User(); dbUser.Username = user.Contains("@") ? user.Substring(0, user.IndexOf('@')) : user; if (!dbUser.Save()) { return(OAuthErrorRedirect("server_error", "An unexpected error occurred on the server.", state, redirectUri)); } } Code code = new Code(); code.ClientIdentifier = Guid.Parse(clientID); code.AuthCode = Guid.NewGuid(); code.RedirectURI = redirectUri; code.Expiration = DateTime.Now.AddMinutes(5); code.UserID = dbUser.UserID; if (!code.Save()) { return(OAuthErrorRedirect("server_error", "An unexpected error occurred on the server.", state, redirectUri)); } return(new RedirectResult(redirectUri + $"?code={code.AuthCode.ToString()}&state={state}", false)); }
private void testLDAPCxnButton_Click(object sender, EventArgs e) { if (!(((infoFlag & (uint)REQINFOFLAGS.LOGIN) > 0) && ((infoFlag & (uint)REQINFOFLAGS.PASSPOLICY) > 0) && ((infoFlag & (uint)REQINFOFLAGS.PASSWORD) > 0) && ((infoFlag & (uint)REQINFOFLAGS.PORT) > 0) && ((infoFlag & (uint)REQINFOFLAGS.SERVER) > 0) && ((infoFlag & (uint)REQINFOFLAGS.USERDN) > 0) && (infoFlag & (uint)REQINFOFLAGS.USERIDKEY) > 0)) { MessageBox.Show("Please enter all required data for LDAP connection.", "PawnStoreSetup Alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } //Ensure LDAP login field is properly //formatted string login = LDAPLogin; if (LDAPLogin.IndexOf("cn=", StringComparison.OrdinalIgnoreCase) == -1) { login = "******" + LDAPLogin; } //Call LDAP connection class if (PawnLDAPAccessor.Instance.State == PawnLDAPAccessor.LDAPState.DISCONNECTED) { PawnLDAPAccessor.Instance.InitializeConnection( this.LDAPServer, this.LDAPPort, login, LDAPPassword, LDAPPassPolicyDN, LDAPUserDN, LDAPUserIdKey); } LDAPCxnSuccess = false; if (PawnLDAPAccessor.Instance.State == PawnLDAPAccessor.LDAPState.CONNECTED) { this.LDAPPwdPolicy = PawnLDAPAccessor.Instance.PasswordPolicy; LDAPCxnSuccess = true; } if (!LDAPCxnSuccess) { MessageBox.Show( "LDAP Connection Failed. Please change the field values and try again."); return; } //Show message box that LDAP is now connected MessageBox.Show("LDAP Connection Successful", "PawnStoreSetup Alert"); //Enable test user search and done button this.testSearchButton.Enabled = false; this.testSearchUserTextBox.Enabled = true; this.testPasswordSearchTextBox.Enabled = true; this.doneButton.Enabled = true; //Disable test connection button this.testLDAPCxnButton.Enabled = false; }