public ActionResult <string> GetIzendaAccessToken(string message) { var userInfo = IzendaTokenAuthorization.DecryptIzendaAuthenticationMessage(message); var token = IzendaTokenAuthorization.GetToken(userInfo); return(Ok(new { Token = token })); }
public string GenerateToken() { string username = User.Identity.Name; string tenantName = ""; try { string nameIdentifierType = @"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"; tenantName = ((ClaimsIdentity)User.Identity).FindFirst(nameIdentifierType).Value; foreach (Claim cl in ((ClaimsIdentity)User.Identity).Claims) { if (cl.Type.Contains("nameidentifier")) { tenantName = cl.Value; } } } catch { } UserInfo user = new UserInfo { UserName = username, TenantUniqueName = tenantName }; string token = IzendaTokenAuthorization.GetToken(user); return("\"" + token + "\""); // believe it or not, otherwise our FE service takes it as errored out. }
public void OnGet() { var izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken(); var tenants = _tenantManager.GetAllTenants().Select(t => new { t.Name, t.Id }).ToList(); TenantSelectList = new SelectList(tenants, "Id", "Name"); }
public UserInfo ValidateIzendaAuthToken(string access_token) { var userInfo = IzendaTokenAuthorization.GetUserInfo(access_token); Console.WriteLine(userInfo); return(userInfo); }
public UserInfo ValidateIzendaAuthToken(string access_token) { try { UserInfo userInfo = IzendaTokenAuthorization.GetUserInfo(access_token); return(userInfo); } catch { return(null); } }
private static string GetToken() { var user = new UserInfo { TenantUniqueName = ConfigurationManager.AppSettings["SystemTenant"], UserName = ConfigurationManager.AppSettings["IzendaAdminUser"] }; var token = IzendaTokenAuthorization.GetToken(user); return(token); }
public async Task <IActionResult> OnPostListAsync(string selectedTenant) { var adminToken = IzendaTokenAuthorization.GetIzendaAdminToken(); var izendaTenant = await IzendaUtilities.GetIzendaTenantByName(selectedTenant, adminToken); var roleDetailsByTenant = await IzendaUtilities.GetAllIzendaRoleByTenant(izendaTenant?.Id ?? null, adminToken); var roles = roleDetailsByTenant.Select(r => new { r.Id, r.Name }).ToList(); RoleSelectList = new SelectList(roles, "Id", "Name"); return(new JsonResult(RoleSelectList)); }
/// <summary> /// Get user/pwd and tenant info from web config file to authorize with Izenda Api /// In all (backend and front end) are integrated mode, authentication information will get from hosting web and send to izenda to authenticate. /// In standalone mode, hosting app will need to send user/pwd to izenda to authenticate. /// </summary> /// <returns></returns> private string GetToken() { var username = System.Configuration.ConfigurationManager.AppSettings["izusername"]; var tenantUniqueName = System.Configuration.ConfigurationManager.AppSettings["iztenantuniquename"]; if (string.IsNullOrEmpty(tenantUniqueName)) { tenantUniqueName = "System"; } var token = IzendaTokenAuthorization.GetToken(new UserInfo { UserName = username, TenantUniqueName = tenantUniqueName }); return(token); }
public async Task <JsonResult> GetRoleListByTenant(string selectedTenant) { var selectList = new List <string>(); var adminToken = IzendaTokenAuthorization.GetIzendaAdminToken(); var izendaTenant = await IzendaUtilities.GetIzendaTenantByName(selectedTenant, adminToken); var roleDetailsByTenant = await IzendaUtilities.GetAllIzendaRoleByTenant(izendaTenant?.Id ?? null, adminToken); roleDetailsByTenant.ForEach(r => selectList.Add(r.Name)); var itemList = selectList.Select(i => new SelectListItem { Text = i }).ToList(); return(Json(new SelectList(itemList, "Value", "Text"))); }
private async Task PopulateRoleList() { RoleList.Items.Clear(); var selectList = new List <string>(); var selectedTenant = TenantList.SelectedValue; var adminToken = IzendaTokenAuthorization.GetIzendaAdminToken(); var izendaTenant = await IzendaUtilities.GetIzendaTenantByName(selectedTenant, adminToken); var roleDetailsByTenant = await IzendaUtilities.GetAllIzendaRoleByTenant(izendaTenant?.Id ?? null, adminToken); roleDetailsByTenant.ForEach(r => selectList.Add(r.Name)); RoleList.DataSource = selectList; RoleList.DataBind(); RoleList.SelectedValue = selectList.FirstOrDefault(); }
private bool CreateIzendaUser(CreateUserBindingModel model) { bool ret = false; try { //check if the tenant name provided if (!string.IsNullOrWhiteSpace(model.Tenant)) { //check if the tenant exists / create new if not Tenant tn = TenantHandler.GetTenantByName(model.Tenant); if (tn == null) { CreateTenantBindingModel tm = new CreateTenantBindingModel() { TenantName = model.Tenant, TenantId = model.Tenant }; TenantHandler th = new TenantHandler(); if (!string.IsNullOrEmpty(th.CreateTenant(tm))) { return(false); } } } string adminToken = IzendaTokenAuthorization.GetIzendaAdminToken(); string assignedRole = String.IsNullOrEmpty(model.SelectedRole) ? "Employee" : model.SelectedRole; Task <bool> createdUser = IzendaUtilities.CreateIzendaUser( model.Tenant, model.UserID, model.LastName, model.FirstName, model.IsAdmin, assignedRole, adminToken); // launch the task async and wait for the result. ret = createdUser.Result; } catch (Exception ex) { throw ex; } return(ret); }
public async Task <IHttpActionResult> CreateTenant(CreateTenantBindingModel model) { if (ModelState.IsValid) { var izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken(); var tenantName = model.TenantName; // check user DB first var isTenantExist = IzendaUtilities.GetTenantByName(tenantName); if (isTenantExist == null) { // try to create a new tenant at izenda config DB var success = await IzendaUtilities.CreateTenant(tenantName, model.TenantId, izendaAdminAuthToken); if (success) { // save a new tenant at user DB var newTenant = new Tenant() { Name = model.TenantId }; await IzendaUtilities.SaveTenantAsync(newTenant); return(Ok("success")); } else { // Izenda config DB has the same tenant name. return(BadRequest()); } } else { // user DB has the same tenant name. return(BadRequest()); } } // If we got this far, something failed return(BadRequest(ModelState)); }
public ActionResult ReportPart(Guid id, string token) { //can we validate the token here //validates token var user = IzendaTokenAuthorization.GetUserInfo(token); if (user != null) { ViewBag.Id = id; ViewBag.Token = token; } else { return(HttpNotFound()); // is invalid user roles } return(View()); }
public async Task <ActionResult> CreateTenant(CreateTenantViewModel model, string returnUrl) { if (ModelState.IsValid) { var izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken(); var tenantName = model.TenantName; var isTenantExist = IzendaUtilities.GetTenantByName(tenantName); // check user DB first if (isTenantExist == null) { // try to create a new tenant at izenda DB var success = await IzendaUtilities.CreateTenant(tenantName, model.TenantID, izendaAdminAuthToken); if (success) { // save a new tenant at user DB var newTenant = new Tenant() { Name = model.TenantID }; await IzendaUtilities.SaveTenantAsync(newTenant); return(RedirectToAction(returnUrl)); } else { // Izenda DB has the same tenant name. Display Message at CreateTenant.cshtml return(FailedTenantCreateAction(_defaultTenantFailureMessage)); } } else { // user DB has the same tenant name. Display Message at CreateTenant.cshtml return(FailedTenantCreateAction(_defaultTenantFailureMessage)); } } // If we got this far, something failed return(FailedTenantCreateAction(_unknownFailureMessage)); }
public ActionResult GenerateToken() { var tenantName = ((ClaimsIdentity)User.Identity).FindFirstValue("tenantName"); var username = ((ClaimsIdentity)User.Identity).FindFirstValue("UserName"); var claimsIdentity = ((ClaimsIdentity)User.Identity); username = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value; var simpleClaims = claimsIdentity.Claims.Select(c => new{ c.Type, c.Value }); var user = new UserInfo { UserName = username, TenantUniqueName = tenantName }; var token = IzendaTokenAuthorization.GetToken(user); return(Json(new { token, username, tenantName, simpleClaims }, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Create a custom route to intercept login requests for the Izenda API. This is needed for the /// Izenda Copy Console as it will only authenticate against "api/user/login". /// </summary> /// <param name="username">the username</param> /// <param name="password">the password</param> /// <returns>a json result indicating success or failure</returns> public ActionResult CustomAuth(string username, string password) { OperationResult authResult; var serializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; var jsonResult = ""; //validate login (more complex logic can be added here) #warning CAUTION!! Update this method to use your authentication scheme or remove it entirely if the copy console will not be used. if (username == "*****@*****.**" && password == "Izenda@123") { var user = new UserInfo { UserName = username, TenantUniqueName = "System" }; var token = IzendaTokenAuthorization.GetToken(user); var accessToken = new IzendaFramework.AccessToken { CultureName = "en-US", Tenant = null, IsExpired = false, NotifyDuringDay = null, DateFormat = "DD/MM/YYYY", Token = token }; authResult = new OperationResult { Success = true, Messages = null, Data = accessToken }; jsonResult = JsonConvert.SerializeObject(authResult, serializerSettings); return(Content(jsonResult, "application/json")); } authResult = new OperationResult { Success = false, Messages = null, Data = null }; jsonResult = JsonConvert.SerializeObject(authResult, serializerSettings); return(Content(jsonResult, "application/json")); }
public bool ValidateLogin(string username, string password, string tenant) { var users = GetUserList(username); // invalid user input if (!users.Any()) { return(false); } // find specific user by tenant var currentUser = users.FirstOrDefault(u => u.TenantUniqueName == tenant); // no matching user + tenant found if (currentUser == null) { return(false); } // check if password matches return(password?.Equals(IzendaTokenAuthorization.GetPassword(currentUser.Password)) ?? false); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { var izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken(); var tenantName = Input.TenantName; var isTenantExist = _tenantManager.GetTenantByName(tenantName); // check user DB first if (isTenantExist == null) { // try to create a new tenant at izenda DB var success = await IzendaUtilities.CreateTenant(tenantName, Input.TenantID, izendaAdminAuthToken); if (success) { // save a new tenant at user DB var newTenant = new Tenant() { Name = Input.TenantID }; await _tenantManager.SaveTenantAsync(newTenant); return(LocalRedirect(returnUrl)); } else { ModelState.AddModelError(string.Empty, "Failed to create a tenant. Tenant already exists in Izenda Config DB."); return(Page()); } } } // If we got this far, something failed, redisplay form ModelState.AddModelError(string.Empty, "Failed to create a tenant. Tenant aleady exists in application DB."); return(Page()); }
public string CreateTenant(CreateTenantBindingModel model) { string ret = ""; try { string izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken(); Tenant tenant = GetTenantByName(model.TenantName); if (tenant == null) { // try to create a new tenant at izenda config DB bool isCreated = CreateIzendaTenant(model, izendaAdminAuthToken); // save a new tenant at user DB Tenant tn = new Tenant() { Name = model.TenantId }; if (isCreated) { isCreated = CreateCustomTenant(tn); } if (!isCreated) { ret = "Create tenant failed."; } } else { // user DB has the same tenant name. return(string.Format("the database already containd the tenant {0}.", model.TenantName)); } } catch (Exception ex) { return(string.Format("Error occured on tenant creation:\n {0}.", ex.Message)); } return(ret); }
public static void RegisterLoginLogic() { //This is used for exporting only UserIntegrationConfig.GetAccessToken = (args) => { return(IzendaTokenAuthorization.GetToken(new UserInfo() { UserName = args.UserName, TenantUniqueName = args.TenantId })); }; UserIntegrationConfig.ValidateToken = (ValidateTokenArgs args) => { var token = args.AccessToken; var user = IzendaTokenAuthorization.GetUserInfo(token); // TenantUniqueName corresponds to the 'TenantID' field in the IzendaTenant table return(new ValidateTokenResult { UserName = user.UserName, TenantUniqueName = user.TenantUniqueName }); }; }
protected async void Submit(object sender, EventArgs e) { if (IsValid) { var izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken(); var isTenantExist = IzendaUtilities.GetTenantByName(TenantName.Text); if (isTenantExist == null) { var success = await IzendaUtilities.CreateTenant(TenantName.Text, TenantID.Text, izendaAdminAuthToken); if (success) { var newTenant = new Tenant() { Name = TenantID.Text }; await IzendaUtilities.SaveTenantAsync(newTenant); RedirectResultPage(true); } else // failed at server level { RedirectResultPage(false); } } else { RedirectResultPage(false); } } else { RedirectResultPage(false); } }
public async Task <ActionResult> CreateUser(CreateUserViewModel model, string returnUrl) { var izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken(); model.Tenants = IzendaUtilities.GetAllTenants(); // prevent null exception when redirected if (ModelState.IsValid) { int?tenantId = null; if (model.SelectedTenant != null) { tenantId = IzendaUtilities.GetTenantByName(model.SelectedTenant).Id; model.IsAdmin = false; } var user = new ApplicationUser { UserName = model.UserID, Email = model.UserID, Tenant_Id = tenantId, }; var result = await UserManager.CreateAsync(user); // Save new user into client DB if (result.Succeeded) // if successful, then start creating a user at Izenda DB { var assignedRole = !string.IsNullOrEmpty(model.SelectedRole) ? model.SelectedRole : "Employee"; // set default role if required. As an example, Employee is set by default if (!RoleManager.RoleExists(assignedRole)) // check assigned role exist in client DB. if not, assigned role is null { try { await RoleManager.CreateAsync(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(assignedRole)); result = await UserManager.AddToRoleAsync(user.Id, assignedRole); } catch (Exception e) { Debug.WriteLine(e); } } if (result.Succeeded) { user.Tenant = IzendaUtilities.GetTenantByName(model.SelectedTenant); // set client DB application user's tenant // Create a new user at Izenda DB var success = await IzendaUtilities.CreateIzendaUser( model.SelectedTenant, model.UserID, model.LastName, model.FirstName, model.IsAdmin, assignedRole, izendaAdminAuthToken); if (success) { return(RedirectToAction(returnUrl)); } else { FailedUserCreateAction(_unknownFailureMessage); } } } else { FailedUserCreateAction(_defaultUserFailureMessage); } AddErrors(result); } return(FailedUserCreateAction(_defaultUserFailureMessage)); }
protected async void Submit(object sender, EventArgs e) { if (IsValid) { int? tenantId = null; bool isAdmin = IsAdminCheckBox.Checked; var selectedTenant = TenantList.SelectedValue; var userManager = Context.GetOwinContext().GetUserManager <ApplicationUserManager>(); var roleManager = Context.GetOwinContext().Get <ApplicationRoleManager>(); var izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken(); if (!string.IsNullOrEmpty(selectedTenant)) { tenantId = IzendaUtilities.GetTenantByName(selectedTenant)?.Id; isAdmin = false; if (tenantId == null) { return; } } var appUser = new ApplicationUser { UserName = UserID.Text, Email = UserID.Text, Tenant_Id = tenantId, }; var result = await userManager.CreateAsync(appUser); // attempt to create a new user in client DB if (result.Succeeded) // if successful, then start creating a user at Izenda DB { var assignedRole = !string.IsNullOrEmpty(RoleList.SelectedValue) ? RoleList.SelectedValue : "Employee"; // set default role if required. As an example, Employee is set by default if (!roleManager.RoleExists(assignedRole)) // check assigned role exist in client DB. if not, assigned role is null { try { await roleManager.CreateAsync(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(assignedRole)); result = await userManager.AddToRoleAsync(appUser.Id, assignedRole); } catch (Exception ex) { Debug.WriteLine(ex); } } if (result.Succeeded) { appUser.Tenant = IzendaUtilities.GetTenantByName(selectedTenant); // set client DB application user's tenant // Create a new user at Izenda DB var success = await IzendaUtilities.CreateIzendaUser( selectedTenant, UserID.Text, LastName.Text, FirstName.Text, isAdmin, assignedRole, izendaAdminAuthToken); if (success) { RedirectResultPage(true); } else { RedirectResultPage(false); } } else { RedirectResultPage(false); } } else { RedirectResultPage(false); } } }
public IList <IzendaBoundary.Models.TenantDetail> GetTenants() { var izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken(); return(IzendaUtilities.GetIzendaTenants(izendaAdminAuthToken).Result); }
public string Authenticate(AuthenticateModel authData) { string ret = ""; if (string.IsNullOrEmpty(authData.username) || string.IsNullOrEmpty(authData.password)) { return(string.Format("The {0} can not be empty", string.IsNullOrEmpty(authData.username)?"user name":"password")); } Tenant tn = null; if (!string.IsNullOrEmpty(authData.tenant)) { tn = dbCtx.Tenants.SingleOrDefault(t => t.Name.ToLower().Equals(authData.tenant.ToLower())); if (tn == null) // nonexisting tenant name provided { return(string.Format("Tenant {0} not found", authData.tenant)); } } // in this example application, we do not use the full ActiveDirectory identity features. // That, plus synchronizing the users in Izenda configuration DB and in the // authorization application DB, allows just to validate the user against the Active Directory. // In case you dont want to synchronize the users and/or not using the authorization DB // while still want to use the Active Directory - you need to implement // the full - featured identity mechanizm with ActiveDirectory support. // // So, here we just validate the active directory user if we set to use the active directory. ADUser adUser = null; ADConfig adCfg = Utilities.ADSettings(); if (adCfg.UseActiveDirectory) { adUser = ADUtilities.ValidateADUser(authData.username, authData.password, adCfg); } if (adCfg.UseActiveDirectory && !adUser.IsValid) { return(string.Format("The user {0} is invalid or not found in the Active Directory.\nError:{1}", authData.username, adUser.Reserved)); } // Check if the user exists in the authentication database. // For the Active Directory, we still will verify this too, even in case the user is valid on A.D. int?tnId = null; if (tn != null) { tnId = tn.Id; } AspNetUser user = dbCtx.AspNetUsers.SingleOrDefault( u => u.UserName.ToLower().Equals(authData.username.ToLower()) && u.TenantId == tnId); // Tip. // At this point, if the AD user exists/valid (adUser.IsValid == true), it is possible to automatically // create the AD user in Izenda DB, if you'd like to. You can implement something like the following: // if ((adCfg.UseActiveDirectory && adUser.IsValid) && user == null) { // user = (cast/retrieve to the AspNetUser)CreateUser(new CreateUserBindingModel { FirstName = "", LastName = "", Tenant = authData.tenant, Password = authData.password, IsAdmin = false }); // } // See the article "Few aspects of Active Directory authentication" at Izenda Confluence board for details // as of now, we expect the A.D. user to exist in the database. if (user == null) { return(string.Format("User {0} not found {1}", authData.username, tn == null ? "":"for the tenant " + tn.Name)); } if (!VerifyPassword(authData.password, user)) { return("The password is incorrect"); } // our sample (custom authenticacion) database does not have the user status flag. // we will use Izenda to find out if the user is active or not. string adminToken = IzendaTokenAuthorization.GetIzendaAdminToken(); Task <IzendaBoundary.Models.UserDetail> getUser = IzendaUtilities.GetIzendaUserByTenantAndName(user.UserName, tn == null?null:tn.Name, adminToken); IzendaBoundary.Models.UserDetail userDetails = getUser.Result; if (userDetails == null) { return(string.Format("The user {0} not found in [Izenda database]. Contact your administrator please", user.UserName)); } else if (!userDetails.Active) { return(string.Format("The user {0} was found but it is not active. Contact your administrator please", user.UserName)); } return(ret); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsValid) { int?tenantId = null; if (Input.SelectedTenantId != null) { tenantId = Input.SelectedTenantId; Input.IsAdmin = false; } var user = new IzendaUser { UserName = Input.UserID, Email = Input.UserID, TenantId = tenantId, }; var result = await _userManager.CreateAsync(user); // Save new user into client DB if (result.Succeeded) // if successful, then start creating a user at Izenda DB { var assignedRole = !string.IsNullOrEmpty(Input.SelectedRole) ? Input.SelectedRole : "Employee"; // set default role if required. As an example, Employee is set by default var isRoleExisting = _roleManager.FindByNameAsync(assignedRole); // check assigned role exist in client DB. if not, assigned role is null if (isRoleExisting == null) { try { await _roleManager.CreateAsync(new Microsoft.AspNetCore.Identity.IdentityRole(assignedRole)); result = await _userManager.AddToRoleAsync(user, assignedRole); } catch (Exception e) { Debug.WriteLine(e); } } else { result = await _userManager.AddToRoleAsync(user, assignedRole); } if (result.Succeeded) { var izendaAdminAuthToken = IzendaTokenAuthorization.GetIzendaAdminToken(); user.Tenant = _tenantManager.GetTenantById(Input.SelectedTenantId); // set client DB application user's tenant var tenantName = user.Tenant?.Name ?? null; // Create a new user at Izenda DB var success = await IzendaUtilities.CreateIzendaUser( tenantName, Input.UserID, Input.LastName, Input.FirstName, Input.IsAdmin, assignedRole, izendaAdminAuthToken); if (success) { return(LocalRedirect(returnUrl)); } } ModelState.AddModelError(string.Empty, "Failed to create a new user. User already exists in DB."); return(Page()); } } ModelState.AddModelError(string.Empty, "Failed to create a new user. Invalid model."); return(Page()); }