public async T.Task OnGetAsync() { if (SearchId > 0) { var authenticationInfo = HttpContext.AuthenticateAsync()?.Result; if (authenticationInfo != null) { // could use "User.Claims", but still need AuthInfo to access Tokens... var webApiUrl = authenticationInfo.Principal.Claims.Where(c => c.Type.Contains("webapi", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); var clientSettings = _superOfficeOptions.Get(SuperOfficeAuthenticationDefaults.AuthenticationScheme); var callbackUri = $"{this.Request.Scheme}://{this.Request.Host}{clientSettings.CallbackPath}"; var authorization = new AuthorizationAccessToken( authenticationInfo.Properties.GetTokenValue(Constants.OAuth.AccessToken), authenticationInfo.Properties.GetTokenValue(Constants.OAuth.IdToken), authenticationInfo.Properties.GetTokenValue(Constants.OAuth.RefreshToken), clientSettings.ClientId, clientSettings.ClientSecret, callbackUri, GetEnvironment(clientSettings.Environment) ); var config = new WebApiOptions(webApiUrl.Value, authorization); ContactAgent ca = new ContactAgent(config); ContactEntity = await ca.GetContactEntityAsync(SearchId); } } }
private void btDoStuff_Click(object sender, EventArgs e) { _stuff.Text = "Running..."; var myContactId = _session.Principal.ContactId; var contact = new ContactAgent().GetContact(myContactId); var sb = new StringBuilder(); sb.AppendLine("Start: " + DateTime.Now.ToShortTimeString()); sb.AppendFormat("Company: '{0}', User: '******'{2}", contact.FullName, SoContext.CurrentPrincipal.FullName, Environment.NewLine); // Try to access restricted agents try { var userInfo = new UserAgent().GetUserInfo(_session.Principal.AssociateId); sb.AppendLine("Successfully accessed UserAgent ant retrieved information for associate: " + userInfo.UserName); } catch (SoServerException ex) { sb.AppendLine("Failed to access User Agent: " + ex.ExceptionInfo.Message); } catch (Exception ex) { sb.AppendLine("Failed to access User Agent: " + ex.Message); } sb.AppendLine("End: " + DateTime.Now.ToShortTimeString()); _stuff.Text = sb.ToString(); }
/// <summary> /// Use system user token to perform work /// </summary> /// <param name="token">Token returned from SuperId and validated</param> /// <returns>Contact entity created as the system user</returns> private static ContactEntity DoWorkAsSystemUser(SuperIdToken token) { // Enter database context for the customer (enter the right multi-tenant context) using (var context = SoDatabaseContext.EnterDatabaseContext(token.ContextIdentifier)) { // set appropriate url for the customer tenant // ConfigFile.WebServices.RemoteBaseURL = token.NetserverUrl; // Log in as the system user using (var session = SoSession.Authenticate(new SoCredentials(token.Ticket))) { // Do work as the system user var principal = SoContext.CurrentPrincipal; System.Diagnostics.Trace.WriteLine(principal.Associate); using (var agent = new ContactAgent()) { var timestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; var entity = agent.CreateDefaultContactEntity(); entity.Name = "SuperId-" + timestamp; return(agent.SaveContactEntity(entity)); } } } }
private async Task <ContactEntity> GetContactEntityAsync(int contactId, Tenant tenant) { // maybe the tenant canceled their subscription... // make sure the tenant is running (not off-line or in backup or maintenance mode) var tenantStatus = GetTenantStatus(tenant); if (tenantStatus.IsRunning) { var sysUserInfo = GetSystemUserInfo(); var sysUserTicket = await GetSystemUserTicket(sysUserInfo); var config = new WebApiOptions(tenant.WebApiUrl); config.Authorization = new AuthorizationSystemUserTicket(sysUserInfo, sysUserTicket); //config.LanguageCode = "en"; //config.CultureCode = "en"; //config.TimeZone = "UTC"; var contactAgent = new ContactAgent(config); return(await contactAgent.GetContactEntityAsync(contactId)); } return(null); }
public ActionResult Index(int id) { using (var agent = new ContactAgent()) { var contact = agent.GetContactEntity(id); return(View(contact)); } }
public ActionResult CreateContactEntity() { using (var agent = new ContactAgent()) { var timestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; var entity = agent.CreateDefaultContactEntity(); entity.Name = "SuperId-" + timestamp; var contact = agent.SaveContactEntity(entity); return(RedirectToAction("Index", new { id = contact.ContactId })); } }
protected void Page_Load(object sender, EventArgs e) { SuperOfficeAuthHelper.Authorize(); // First choose the correct installation: SuperOffice.Configuration.ConfigFile.WebServices.RemoteBaseURL = SuperOfficeAuthHelper.Context.NetServerUrl; var contPar = Request.QueryString["ContactId"]; int contId = Convert.ToInt32(contPar); using (var contAgent = new ContactAgent()) { var cont = contAgent.GetContactEntity(contId); var addr = cont.Address; string address = string.Empty; if (addr.LocalizedAddress != null && addr.LocalizedAddress.Length > 1) { if (addr.LocalizedAddress[0] != null) { address = addr.LocalizedAddress[0].Aggregate(address, (current, addrLine) => current.Add(addrLine.Value, ", ")); } if (addr.LocalizedAddress[1] != null) { address = addr.LocalizedAddress[1].Aggregate(address, (current, addrLine) => current.Add(addrLine.Value, ", ")); } address = address.Add(cont.Country.EnglishName, ", "); string lat, lng; GoogleMaps.GeocodeAddress(address, out lat, out lng ); var contactName = System.Web.HttpUtility.JavaScriptStringEncode(cont.Name); var script = "<script>\nfunction initializeMarkers() {\n"; script += string.Format("AddMarker(map, '{0}', '{1}', '{2}' );\n", contactName, lat, lng); script += "}\n</script>"; loadMarkersScript.Text = script; } } }
/// <summary> /// Does the actual authentication /// </summary> /// <param name="context"></param> /// <param name="errorReason"></param> /// <returns></returns> public static bool TryLogin(SuperOfficeContext context, out string errorReason) { Context = context; //If we are allready authorized, then logout first, before creating a cookie.... if (SuperOffice.SoContext.IsAuthenticated) { SuperOffice.SoContext.CloseCurrentSession(); SuperOfficeAuthHelper.Logout(); } // Use forms authentication - this is optional var soFormsTicket = new FormsAuthenticationTicket(context.Email, false, 3600); var soFormsTicketEncrypted = FormsAuthentication.Encrypt(soFormsTicket); var httpContext = HttpContext.Current; httpContext.Session[ConfigManager.SoAuthCookie] = soFormsTicketEncrypted; httpContext.Response.Cookies.Add(new HttpCookie(ConfigManager.SoAuthCookie, soFormsTicketEncrypted)); try { // If request is not authenticated, and a controller with the // SuperOfficeAuthorize attribute is accessed, the called controller // will continue to send the user to SuperID. If already authenticated there // this user will always return here and be stuck in an endless loop. // Therefore, it is important to authenticate with NetServer, and allow the // context provider to store the current session. Thus, the SuperOfficeAuthorize // attibute will be able to locate the session and proceed unimpeded //Authenticate with NetServer using web services if necessary. /* * // From Jens on DevNet: * // The SuperOffice.Configuration.ConfigFile.WebServices.RemoteBaseUrl is the value actually being used by the proxy to communicate with the server. * // This value is read from SuperOffice.Configuration.ConfigFile.Services.RemoteBaseUrl if it is not defined. * // The values of SuperOffice.Configuration.ConfigFile.Services are stored in a value that is static throughout the NetServer process, * // and shared between tenants in a multi-tenant configuration. * // The values SuperOffice.Configuration.ConfigFile.WebServices are tenant specific configuration values. * // */ //} SoSession session = null; if (string.IsNullOrEmpty(context.AccessToken)) { session = SoSession.Authenticate(new SoCredentials() { Ticket = context.Ticket }); } else { session = SoSession.Authenticate(new SoAccessTokenSecurityToken(context.AccessToken)); } var principal = SoContext.CurrentPrincipal; OverrideContextIdentifier(principal, context.ContextIdentifier); var contact = new ContactAgent().GetContact(principal.ContactId); context.Company = contact.FullName; context.Name = principal.FullName; context.Username = principal.Associate; context.AssociateId = principal.AssociateId; errorReason = String.Empty; return(true); } catch (Exception ex) { while (ex.InnerException != null) { ex = ex.InnerException; } errorReason = ex.Message; SuperOfficeAuthHelper.Logout(); return(false); } }
/// <summary> /// /// </summary> /// <param name="token">Saml or JWT token</param> public static bool TryLogin(string token, string tokenType) { var tokenHandler = new SuperIdTokenHandler(); var typedTokenType = (SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType) Enum.Parse(typeof(SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType), tokenType); var certificatePath = ConfigManager.SuperOfficeFederatedLogin; if (!String.IsNullOrWhiteSpace(certificatePath)) { if (!Path.IsPathRooted(certificatePath)) { certificatePath = Path.Combine(HostingEnvironment.MapPath(@"~"), certificatePath); } tokenHandler.JwtIssuerSigningCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificatePath); } else { tokenHandler.CertificateValidator = X509CertificateValidator.PeerTrust; } //tokenHandler.ValidateAudience = false; var superIdClaims = tokenHandler.ValidateToken(token, typedTokenType); var context = new SuperOfficeContext { Ticket = superIdClaims.Ticket, Email = superIdClaims.Email, ContextIdentifier = superIdClaims.ContextIdentifier, NetServerUrl = superIdClaims.NetserverUrl, SystemToken = superIdClaims.SystemToken, }; Context = context; // Use forms authentication - this is optional var soFormsTicket = new FormsAuthenticationTicket(superIdClaims.Email, false, 3600); var soFormsTicketEncrypted = FormsAuthentication.Encrypt(soFormsTicket); var httpContext = HttpContext.Current; httpContext.Session[ConfigManager.SoAuthCookie] = soFormsTicketEncrypted; httpContext.Response.Cookies.Add(new HttpCookie(ConfigManager.SoAuthCookie, soFormsTicketEncrypted)); try { // If request is not authenticated, and a controller with the // SuperOfficeAuthorize attribute is accessed, the called controller // will continue to send the user to SuperID. If already authenticated there // this user will always return here and be stuck in an endless loop. // Therefore, it is important to authenticate with NetServer, and allow the // context provider to store the current session. Thus, the SuperOfficeAuthorize // attibute will be able to locate the session and proceed unimpeded //Authenticate with NetServer using web services if necessary. SoSession session = SoSession.Authenticate(new SoCredentials() { Ticket = context.Ticket }); var principal = SoContext.CurrentPrincipal; var contact = new ContactAgent().GetContact(principal.ContactId); context.Company = contact.FullName; context.Name = principal.FullName; context.Username = principal.Associate; context.AssociateId = principal.AssociateId; return(true); } catch (Exception ex) { SuperOfficeAuthHelper.Logout(); return(false); } }