Esempio n. 1
0
        /// <summary>
        /// Get and validate claims for the system user from the SuperID web service
        /// </summary>
        /// <param name="userToken">System user token, not yet signed</param>
        /// <param name="contextIdentifier">Context identifier of the customer</param>
        /// <returns>Token with claims</returns>
        private static SuperIdToken GetSystemUserToken(string userToken, string contextIdentifier)
        {
            var systemToken = new SystemToken(userToken);

            // Get certificate
            var certificatePath = CertificatePath;

            // sign the system user token
            var signedSystemToken = systemToken.Sign(privateKey: File.ReadAllText(certificatePath));

            // Call the web service to exchange signed system user token with claims for the system user
            var federationGateway = ConfigurationManager.AppSettings["SoFederationGateway"];
            var returnedToken     = systemToken.AuthenticateWithSignedSystemToken(federationGateway, signedSystemToken,
                                                                                  ConfigFile.Services.ApplicationToken, contextIdentifier, TokenType.Saml);

            // Validate and return SuperId token for the system user
            var tokenHandler = new SuperIdTokenHandler();

            tokenHandler.IssuerTokenResolver =
                new SuperOffice.SuperID.Client.Tokens.CertificateFileCertificateStoreTokenResolver(
                    System.Web.HttpContext.Current.Server.MapPath("~/App_Data")
                    );

            tokenHandler.CertificateValidator = System.IdentityModel.Selectors.X509CertificateValidator.None;

            return(tokenHandler.ValidateToken(returnedToken, TokenType.Saml));
        }
Esempio n. 2
0
        private static SuperIdToken GetSystemUserToken(string systemTokenString, string contextIdentifier)
        {
            // Grab hold of the system user token
            var systemToken = new SystemToken(systemTokenString);

            // Get certificate
            var certificatePath = ConfigManager.ApplicationKeyFile;

            if (!Path.IsPathRooted(certificatePath))
            {
                certificatePath = Path.Combine(HostingEnvironment.MapPath(@"~"), certificatePath);
            }

            // sign the system user token
            var signedSystemToken = systemToken.Sign(privateKey: File.ReadAllText(certificatePath));

            // Call the web service to exchange signed system user token with claims for the system user
            var federationGateway = ConfigManager.SoFederationGateway;
            var returnedToken     = systemToken.AuthenticateWithSignedSystemToken(federationGateway, signedSystemToken,
                                                                                  ConfigFile.Services.ApplicationToken, contextIdentifier, TokenType.Jwt);

            // Validate SuperId token for the system user
            var systemUserTokenHandler = new SuperIdTokenHandler();
            var systemUserToken        = systemUserTokenHandler.ValidateToken(returnedToken, TokenType.Jwt);

            return(systemUserToken);
        }
Esempio n. 3
0
        public static SuperIdToken GetSystemUserToken(string userToken, string contextIdentifier,
                                                      string privateKey, string federationGateway, string applicationToken, string certificateString)
        {
            var tokenType = SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType.Jwt;

            var systemToken = new SystemToken(userToken);

            // Get certificate

            // sign the system user ticket
            var signedSystemToken = systemToken.Sign(privateKey);

            // Call the web service to exchange signed system user ticket with claims for the system user
            var returnedToken = systemToken.AuthenticateWithSignedSystemToken(federationGateway, signedSystemToken,
                                                                              applicationToken, contextIdentifier, tokenType);

            if (returnedToken != null)
            {
                // Validate and return SuperId ticket for the system user
                var tokenHandler = new SuperIdTokenHandler();

                var certificateResolverPath = AppDomain.CurrentDomain.BaseDirectory + "Certificates";

                if (tokenType == SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType.Saml)
                {
                    tokenHandler.CertificateValidator = System.IdentityModel.Selectors.X509CertificateValidator.None;
                    tokenHandler.IssuerTokenResolver  = new CertificateFileCertificateStoreTokenResolver(certificateResolverPath);
                }
                else
                {
                    // byte[] bytes = System.Convert.FromBase64String(certificateString);
                    byte[] bytes = Encoding.ASCII.GetBytes(certificateString);
                    tokenHandler.JwtIssuerSigningCertificate =
                        new System.Security.Cryptography.X509Certificates.X509Certificate2(bytes);
                }

                tokenHandler.ValidateAudience = false;

                SuperIdToken superToken = null;

                try
                {
                    superToken = tokenHandler.ValidateToken(returnedToken, tokenType);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                return(superToken);
            }

            return(null);
        }
Esempio n. 4
0
    public static SuperIdToken ValidateToken(string token)
    {
        var path         = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/") + "SOD_SuperOfficeFederatedLogin.crt";
        var tokenHandler = new SuperIdTokenHandler();

        tokenHandler.JwtIssuerSigningCertificate = new X509Certificate2(path);
        tokenHandler.CertificateValidator        = X509CertificateValidator.ChainTrust;
        tokenHandler.ValidIssuer = "https://sod.superoffice.com";

        return(tokenHandler.ValidateToken(token, TokenType.Jwt));
    }
        public static SuperIdToken ValidateToken(HttpServerUtilityBase server, string token)
        {
            var path = server.MapPath("~/App_Data/") + "SOD_SuperOfficeFederatedLogin.crt";

            var tokenHandler = new SuperIdTokenHandler();

            tokenHandler.JwtIssuerSigningCertificate = new X509Certificate2(path);
            tokenHandler.CertificateValidator        = X509CertificateValidator.ChainTrust;
            tokenHandler.ValidIssuer = "https://sod.superoffice.com";

            return(tokenHandler.ValidateToken(token, TokenType.Jwt));
        }
Esempio n. 6
0
        private void btLogin_Click(object sender, EventArgs e)
        {
            btDoStuff.Enabled = false;

            _netServerUrl.Text = string.Empty;
            _claims.Items.Clear();

            SuperOffice.Configuration.ConfigFile.Services.ApplicationToken = _applicationToken.Text;

            var login    = new LoginHelper();
            var uri      = new UriBuilder(_environmentLogin.Text).Uri;
            var response = login.TryFederatedLogin(uri, new AuthenticationRequest()
            {
                ApplicationId    = _applicationId.Text,
                ApplicationTitle = "Testing win-forms login in demo app",
                CustomerContext  = string.Empty,     // don't cara about which customer in this context
            });

            if (response.IsSuccessful)
            {
                var saml = GetClaim(response, "saml");
                //var jwt = GetClaim(response, "jwt");

                // Validate and parse saml with user authentication
                var userTokenHandler = new SuperIdTokenHandler();
                _userToken = userTokenHandler.ValidateToken(saml, SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType.Saml);


                foreach (var claim in _userToken.Claims)
                {
                    var lvi = new ListViewItem(claim.ClaimType);
                    lvi.SubItems.Add(claim.Resource as string);
                    _claims.Items.Add(lvi);
                }

                _netServerUrl.Text = _userToken.NetserverUrl;
                ConfigFile.WebServices.RemoteBaseURL = _userToken.NetserverUrl;

                try
                {
                    _session = SoSession.Authenticate(new SoCredentials()
                    {
                        Ticket = _userToken.Ticket
                    });
                }
                catch (Exception)
                {
                }
            }

            btDoStuff.Enabled = _session != null;
        }
        /// <summary>
        /// Used by Online
        /// </summary>
        /// <param name="token">Saml or JWT token</param>
        public static bool TryLogin(string token, string tokenType, OidcModel oidcModel, out string errorReason)
        {
            errorReason = String.Empty;
            var tokenHandler = new SuperIdTokenHandler();

            tokenHandler.ValidIssuer = oidcModel == null ? "SuperOffice AS" : "https://sod.superoffice.com"; // required for OIDC vs. Old Federated Auth...

            var useAppData = Convert.ToBoolean(ConfigurationManager.AppSettings["CertificatesInAppDataFolder"]);

            var typedTokenType = (SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType)
                                 Enum.Parse(typeof(SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType), tokenType);

            if (useAppData && typedTokenType == SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType.Saml)
            {
                tokenHandler.IssuerTokenResolver =
                    new CertificateFileCertificateStoreTokenResolver(
                        HttpContext.Current.Server.MapPath("~/App_Data"));
                tokenHandler.CertificateValidator = X509CertificateValidator.None;
            }
            else if (useAppData && typedTokenType == SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType.Jwt)
            {
                tokenHandler.JwtIssuerSigningCertificate =
                    new System.Security.Cryptography.X509Certificates.X509Certificate2(
                        HttpContext.Current.Server.MapPath("~/App_Data/") + "SuperOfficeFederatedLogin.crt");
            }
            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,
                CustomerKey       = String.Empty,
                IsOnSiteCustomer  = false,
                AccessToken       = oidcModel?.AccessToken,
                IdToken           = oidcModel?.IdToken,
                RefreshToken      = oidcModel?.RefreshToken
            };

            return(TryLogin(context, out errorReason));
        }
        /// <summary>
        /// Get and validate claims for the system user from the SuperID web service
        /// </summary>
        /// <param name="userToken">System user token, not yet signed</param>
        /// <param name="contextIdentifier">Context identifier of the customer</param>
        /// <returns>Token with claims</returns>
        private static SuperIdToken GetSystemUserToken(string userToken, string contextIdentifier)
        {
            var tokenType = SuperOffice.SuperID.Contracts.SystemUser.V1.TokenType.Jwt;

            var systemToken = new SystemToken(userToken);

            // Get certificate
            var certificatePath = ConfigurationManager.AppSettings["SystemTokenCertificatePath"];

            // sign the system user token
            var signedSystemToken = systemToken.Sign(File.ReadAllText(certificatePath));

            // Call the web service to exchange signed system user token with claims for the system user
            var federationGateway = ConfigurationManager.AppSettings["SoFederationGateway"];
            var returnedToken     = systemToken.AuthenticateWithSignedSystemToken(federationGateway, signedSystemToken,
                                                                                  ConfigFile.Services.ApplicationToken, contextIdentifier, tokenType);

            if (returnedToken != null)
            {
                // Validate and return SuperId token for the system user
                var tokenHandler = new SuperIdTokenHandler();

                var certificateResolverPath = AppDomain.CurrentDomain.BaseDirectory + "Certificates";

                if (tokenType == SuperID.Contracts.SystemUser.V1.TokenType.Saml)
                {
                    tokenHandler.CertificateValidator = System.IdentityModel.Selectors.X509CertificateValidator.None;
                    tokenHandler.IssuerTokenResolver  = new SuperOffice.SuperID.Client.Tokens.CertificateFileCertificateStoreTokenResolver(certificateResolverPath);
                }
                else
                {
                    tokenHandler.JwtIssuerSigningCertificate =
                        new System.Security.Cryptography.X509Certificates.X509Certificate2(
                            certificateResolverPath + "\\SODSuperOfficeFederatedLogin.crt");
                }

                tokenHandler.ValidateAudience = false;

                return(tokenHandler.ValidateToken(returnedToken, tokenType));
            }

            return(null);
        }
        /// <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);
            }
        }