public void IdentityProviderDictionary_Add() { var subject = new IdentityProviderDictionary(); var entityId = new EntityId("http://idp.example.com"); var idp = new IdentityProvider(entityId, StubFactory.CreateSPOptions()); subject.Add(idp); subject[entityId].Should().BeSameAs(idp); }
public void IdentityProvider_CreateAuthenticateRequest_Destination() { string idpUri = "http://idp.example.com/"; var ip = new IdentityProvider(new Uri(idpUri)); var r = ip.CreateAuthenticateRequest(null); r.ToXElement().Attribute("Destination").Should().NotBeNull() .And.Subject.Value.Should().Be(idpUri); }
/// <summary> /// Add an identity provider to the collection.. /// </summary> /// <param name="idp">Identity provider to add.</param> public void Add(IdentityProvider idp) { if(idp == null) { throw new ArgumentNullException("idp"); } lock(dictionary) { dictionary.Add(idp.EntityId, idp); } }
public void IdentityProvider_SingleSignOnService_DoesntReloadMetadataIfStillValid() { var subject = new IdentityProvider( new EntityId("http://localhost:13428/idpMetadata"), StubFactory.CreateSPOptions()) { LoadMetadata = true }; subject.SingleSignOnServiceUrl.Port.Should().Be(13428); StubServer.IdpMetadataSsoPort = 147; // Metadata shouldn't be reloaded so port shouldn't be changed. subject.SingleSignOnServiceUrl.Port.Should().Be(13428); }
public void GetInvalidLinkTypeTest(string linkUri, bool isReceiver) { // Arrange var messageConverter = Mock.Of <IMessageConverter <AmqpMessage> >(); var twinMessageConverter = Mock.Of <IMessageConverter <AmqpMessage> >(); var methodMessageConverter = Mock.Of <IMessageConverter <AmqpMessage> >(); var identityProvider = new IdentityProvider("foo.bar"); var linkHandlerProvider = new LinkHandlerProvider(messageConverter, twinMessageConverter, methodMessageConverter, identityProvider); var amqpLink = Mock.Of <IAmqpLink>(l => l.IsReceiver == isReceiver); var uri = new Uri(linkUri); // Act / Assert Assert.Throws <InvalidOperationException>(() => linkHandlerProvider.GetLinkType(amqpLink, uri)); }
public Taker(TestFairCallQueue _enclosing, BlockingQueue <Schedulable> aCq, int maxCalls , string tag, CountDownLatch latch) { this._enclosing = _enclosing; // if >= 0 means we will only take the matching tag, and put back // anything else // total calls taken, accurate if we aren't interrupted // the last thing we took // maximum calls to take this.maxCalls = maxCalls; this.cq = aCq; this.tag = tag; this.uip = new UserIdentityProvider(); this.latch = latch; }
/// <summary> /// Obtain the AuthenticationCredentials based on AuthenticationProviderType. /// </summary> /// <param name="service">A service management object.</param> /// <param name="endpointType">An AuthenticationProviderType of the CRM environment.</param> /// <returns>Get filled credentials.</returns> public static AuthenticationCredentials GetCredentials <TService>(IServiceManagement <TService> service, AuthenticationProviderType endpointType) { AuthenticationCredentials authCredentials = new AuthenticationCredentials(); switch (endpointType) { case AuthenticationProviderType.ActiveDirectory: authCredentials.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(OrganizationName.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmServiceUser, OrganizationName.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmServicePassword, OrganizationName.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmServiceDomain); break; case AuthenticationProviderType.LiveId: authCredentials.ClientCredentials.UserName.UserName = OrganizationName.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmServiceUser + "@" + OrganizationName.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmServiceDomain; authCredentials.ClientCredentials.UserName.Password = OrganizationName.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmServicePassword; authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = DeviceIdManager.LoadOrRegisterDevice(); break; // For Federated and OnlineFederated environments- default: authCredentials.ClientCredentials.UserName.UserName = OrganizationName.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmServiceUser + "@" + OrganizationName.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmServiceDomain; authCredentials.ClientCredentials.UserName.Password = OrganizationName.PluginRegistration.Security.Configuration.ConfigurationSingleton.Section.XrmServicePassword; // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password. // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName; // Windows Kerberos // The service is configured for User Id authentication, but the user might provide Microsoft // account credentials. If so, the supporting credentials must contain the device credentials. if (endpointType == AuthenticationProviderType.OnlineFederation) { IdentityProvider provider = service.GetIdentityProvider(authCredentials.ClientCredentials.UserName.UserName); if (provider != null && provider.IdentityProviderType == IdentityProviderType.LiveId) { authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = DeviceIdManager.LoadOrRegisterDevice(); } } break; } return(authCredentials); }
/// <summary> /// Builds a <see cref="IdentityProvider"/> based on the current builder properties. /// </summary> /// <returns>A <see cref="IdentityProvider"/>.</returns> public IdentityProvider Build() { var config = new IdentityProvider(); config.AllowUnsolicitedResponses = _allowUnsolicitedResponses; config.Default = _isDefault; config.ForceAuth = _forceAuth; config.Id = _id; config.IsPassive = _isPassive; config.Name = _name; config.OmitAssertionSignatureCheck = _omitAssertionSignatureCheck; config.QuirksMode = _enableQuirksMode; config.ResponseEncoding = _responseEncoding; if (_attributeQuery != null) { config.AttributeQuery = _attributeQuery; } if (_attributeResolution != null) { config.ArtifactResolution = _attributeResolution; } if (!string.IsNullOrEmpty(_persistentPseudonymMapper)) { config.PersistentPseudonym = new PersistentPseudonym { Mapper = _persistentPseudonymMapper }; } foreach (var certificateValidation in _certificateValidations) { config.CertificateValidations.Add(certificateValidation); } foreach (var key in _commonDomainCookies.Keys) { config.CommonDomainCookie.Add(key, _commonDomainCookies[key]); } foreach (var endpoint in _endpoints) { config.Endpoints.Add(endpoint); } return(config); }
public ActionResult SpidRequest(string idpName) { try { // Create the SPID request id string spidAuthnRequestId = Guid.NewGuid().ToString(); // Select the Identity Provider IdentityProvider idp = IdentityProvidersList.GetIdpFromIdPName(idpName); // Retrieve the signing certificate var certificate = X509Helper.GetCertificateFromStore( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, ConfigurationManager.AppSettings["SPID_CERTIFICATE_NAME"], validOnly: false); // Create the signed SAML request var spidAuthnRequest = SamlHelper.BuildAuthnPostRequest( uuid: spidAuthnRequestId, destination: idp.EntityID, consumerServiceURL: ConfigurationManager.AppSettings["SPID_DOMAIN_VALUE"], securityLevel: 1, certificate: certificate, identityProvider: idp, enviroment: ConfigurationManager.AppSettings["ENVIROMENT"] == "dev" ? 1 : 0); ViewData["data"] = spidAuthnRequest; ViewData["action"] = idp.SingleSignOnServiceUrl; // Save the IdP label and SPID request id as a cookie HttpCookie cookie = Request.Cookies.Get(SPID_COOKIE) ?? new HttpCookie(SPID_COOKIE); cookie.Values["IdPName"] = idpName; cookie.Values["SpidAuthnRequestId"] = spidAuthnRequestId; cookie.Expires = DateTime.Now.AddMinutes(20); Response.Cookies.Add(cookie); // Send the request to the Identity Provider return(View("PostData")); } catch (Exception ex) { log.Error("Error on HomeController SpidRequest", ex); ViewData["Message"] = "Errore nella preparazione della richiesta di autenticazione da inviare al provider."; ViewData["ErrorMessage"] = ex.Message; return(View("Error")); } }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddUIComponents() .AddUIComponent <ClientUIComponent>() .AddUIComponent <LoadingUIComponent>() .AddUIComponent <MarkdownUIComponent>() .AddUIComponent <SlidesUIComponent>() .AddUIComponent <ModalUIComponent>() .AddUIComponent <ToastUIComponent>(); services.AddRazorPages(); services.AddControllers(); services.AddHttpClient(); services.AddSingleton(new RenderStatus { IsPrerender = true }); ServerSettings server = new ServerSettings(); Configuration.Bind("Server", server); services.AddSingleton(server); { BuildStatus bs = new BuildStatus(); Configuration.Bind("build", bs); services.AddSingleton(bs); } { var blogSettings = new BlogSettings(); Configuration.Bind("Blog", blogSettings); services.AddSingleton(blogSettings); } { var identity = new IdentityProvider(); Configuration.Bind("IdentityProvider", identity); services.AddSingleton(identity); } services.AddScoped <AuthenticationStateProvider, ServerAuthenticationStateProvider>(); services.AddScoped <SignOutSessionStateManager>(); services.AddBlogService(server, Configuration.GetBaseAddress()); }
public void IdentityProvider_CreateAuthenticateRequest_DestinationInXml() { string idpUri = "http://idp.example.com/"; var subject = new IdentityProvider( new EntityId(idpUri), Options.FromConfiguration.SPOptions) { SingleSignOnServiceUrl = new Uri(idpUri) }; var r = subject.CreateAuthenticateRequest(null, StubFactory.CreateAuthServicesUrls()); r.ToXElement().Attribute("Destination").Should().NotBeNull() .And.Subject.Value.Should().Be(idpUri); }
public void SetClaimSucceeds() { var contract = new IdentityProvider(this.mockContractState.Object); this.mockState.Setup(x => x.GetAddress("Owner")).Returns(this.owner); this.mockState.Setup(x => x.GetBytes(It.IsAny <string>())).Returns((byte[])null); this.mockMessage.Setup(x => x.Sender).Returns(this.owner); contract.AddClaim(this.claimReceiver, Topic, ClaimData); this.mockState.Verify(x => x.SetBytes($"Claim[{this.claimReceiver}][{Topic}]", ClaimData)); this.mockContractLogger.Verify(x => x.Log(It.IsAny <ISmartContractState>(), It.Is <IdentityProvider.ClaimChanged>(y => y.Topic == Topic && y.Data == ClaimData && y.IssuedTo == this.claimReceiver))); }
private IdentityProvider ExtractEditFormData(ProviderEditModel formData) { var myIdetity = new IdentityProvider(); myIdetity.Id = formData.Id; myIdetity.Name = formData.Name; myIdetity.Code = formData.Code; myIdetity.Phone = formData.Phone; myIdetity.Email = formData.Email; myIdetity.Address = formData.Address; myIdetity.Status = formData.Status; myIdetity.Email = formData.Email; return(myIdetity); }
private void ValidateSignature(IOptions options, IdentityProvider idp) { var idpKeys = idp.SigningKeys; var minAlgorithm = options.SPOptions.MinIncomingSigningAlgorithm; if (!xmlElement.IsSignedByAny(idpKeys, options.SPOptions.ValidateCertificates, minAlgorithm) && GetAllAssertionElementNodes(options) .Any(a => !a.IsSignedByAny(idpKeys, options.SPOptions.ValidateCertificates, minAlgorithm))) { throw new Saml2ResponseFailedValidationException( "The SAML Response is not signed and contains unsigned Assertions. Response cannot be trusted."); } options.SPOptions.Logger.WriteVerbose("Signature validation passed for Saml Response " + Id); }
public (User user, bool succeed, string error) TryRegister(string user, string psd, Gender gender = Gender.Male, string avatar = null) { var usrr = this.users.Find(i => i.UserName == user).FirstOrDefault(); if (usrr != null) { return(null, false, Errors.UserExist); } usrr = IdentityProvider.CreateUser(user, psd, gender, avatar); try { this.users.InsertOne(usrr); return(usrr, true, null); } catch (Exception e) { return(null, false, Errors.SaveUserInfosFailed + $" : ${e.Message}"); } }
private ProviderEditModel RenderEditModel(IdentityProvider identity) { var editModel = new ProviderEditModel(); editModel.Id = identity.Id; editModel.Name = identity.Name; editModel.Code = identity.Code; editModel.Phone = identity.Phone; editModel.Email = identity.Email; editModel.Address = identity.Address; editModel.Status = identity.Status; editModel.Email = identity.Email; return(editModel); }
public void IdentityProvider_CreateAuthenticateRequest_DestinationInXml() { string idpUri = "https://idp.example.com:443/"; var subject = new IdentityProvider( new EntityId(idpUri), Options.FromConfiguration.SPOptions) { SingleSignOnServiceUrl = new Uri(idpUri) }; var r = subject.CreateAuthenticateRequest(StubFactory.CreateAuthServicesUrls()); r.ToXElement().Attribute("Destination").Should().NotBeNull() .And.Subject.Value.Should().Be(idpUri); }
// Send the SAML response to the SP. private void SendSAMLResponse(SAMLResponse samlResponse, string relayState) { Trace.Write("IdP", "Sending SAML response"); // Serialize the SAML response for transmission. XmlElement samlResponseXml = samlResponse.ToXml(); // Sign the SAML response. X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.IdPX509Certificate]; SAMLMessageSignature.Generate(samlResponseXml, x509Certificate.PrivateKey, x509Certificate); IdentityProvider.SendSAMLResponseByHTTPPost(Response, Configuration.AssertionConsumerServiceURL, samlResponseXml, relayState); Trace.Write("IdP", "Sent SAML response"); }
protected override string CreateUniqueUserName(Microsoft.AspNet.Identity.UserManager <ApplicationUser> userManager, Microsoft.AspNet.Identity.Owin.ExternalLoginInfo externalLoginInfo) { Assert.ArgumentNotNull((object)userManager, nameof(userManager)); Assert.ArgumentNotNull((object)externalLoginInfo, nameof(externalLoginInfo)); IdentityProvider identityProvider = this.FederatedAuthenticationConfiguration.GetIdentityProvider(externalLoginInfo.ExternalIdentity); if (identityProvider == null) { throw new InvalidOperationException("Unable to retrieve identity provider for given identity"); } string domain = identityProvider.Domain; string email = externalLoginInfo.DefaultUserName; // return email and domain return($"{domain}\\\\\\\\{email}"); }
private void lbInstitutions_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (lbInstitutions.SelectedIndex == -1) { IdProviderId = null; mainWindow.btnNext.IsEnabled = false; } else { // select provider ID from selected provider IdentityProvider selectedProvider = (IdentityProvider)lbInstitutions.SelectedItem; IdProviderId = selectedProvider.Id; mainWindow.btnNext.IsEnabled = selectedProvider.Id != null; } }
private static KentorAuthServicesAuthenticationOptions CreateAuthServicesOptions() { //Retrieve settings var commonLoginUrl = RetrieveAppSetting("CommonLoginUrl"); var singleSignOnIssuerUrl = RetrieveAppSetting("SingleSignOnIssuerUrl"); var singleSignOnTargetUrl = RetrieveAppSetting("SingleSignOnTargetUrl"); var singleLogoutTargetUrl = WebConfigurationManager.AppSettings["SingleLogoutTargetUrl"]; //Configure service provider var serviceProvider = new SPOptions { EntityId = new EntityId(commonLoginUrl), ReturnUrl = new Uri(commonLoginUrl + "/Account/ExternalLoginCallback"), }; //Configure identity provider var identityProvider = new IdentityProvider(new EntityId(singleSignOnIssuerUrl), serviceProvider) { AllowUnsolicitedAuthnResponse = true, Binding = Saml2BindingType.HttpRedirect, SingleSignOnServiceUrl = new Uri(singleSignOnTargetUrl) }; //Set single logout if it has been specified if (!string.IsNullOrEmpty(singleLogoutTargetUrl)) { identityProvider.SingleLogoutServiceUrl = new Uri(singleLogoutTargetUrl); } //Load certificate var certificatePath = HostingEnvironment.MapPath("~/App_Data/IdentityProviderCertificate.cer"); if (string.IsNullOrEmpty(certificatePath)) { throw new Exception($"Could not find the identity provider certificate path. Value given was: {certificatePath}."); } identityProvider.SigningKeys.AddConfiguredKey(new X509Certificate2(certificatePath)); //Return authenticaton options var authenticationOptions = new KentorAuthServicesAuthenticationOptions(false) { SPOptions = serviceProvider }; authenticationOptions.IdentityProviders.Add(identityProvider); return(authenticationOptions); }
/// <summary> /// Obtain the AuthenticationCredentials based on AuthenticationProviderType. /// </summary> /// <param name="service">A service management object.</param> /// <param name="endpointType">An AuthenticationProviderType of the CRM environment.</param> /// <returns>Get filled credentials.</returns> private AuthenticationCredentials GetCredentials <TService>(IServiceManagement <TService> service, AuthenticationProviderType endpointType) { AuthenticationCredentials authCredentials = new AuthenticationCredentials(); _userName = username.Text; _password = txtPassword.Text; switch (endpointType) { case AuthenticationProviderType.ActiveDirectory: authCredentials.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(_userName, _password, _domain); break; case AuthenticationProviderType.LiveId: authCredentials.ClientCredentials.UserName.UserName = _userName; authCredentials.ClientCredentials.UserName.Password = _password; authCredentials.SupportingCredentials = new AuthenticationCredentials(); //authCredentials.SupportingCredentials.ClientCredentials = Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice(); break; default: // For Federated and OnlineFederated environments. authCredentials.ClientCredentials.UserName.UserName = _userName; authCredentials.ClientCredentials.UserName.Password = _password; // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password. // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName; // Windows Kerberos // The service is configured for User Id authentication, but the user might provide Microsoft // account credentials. If so, the supporting credentials must contain the device credentials. if (endpointType == AuthenticationProviderType.OnlineFederation) { IdentityProvider provider = service.GetIdentityProvider(authCredentials.ClientCredentials.UserName.UserName); if (provider != null && provider.IdentityProviderType == IdentityProviderType.LiveId) { authCredentials.SupportingCredentials = new AuthenticationCredentials(); //authCredentials.SupportingCredentials.ClientCredentials = Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice(); authCredentials.SupportingCredentials.ClientCredentials = DeviceIdManager.LoadOrRegisterDevice(); } } break; } return(authCredentials); }
/// <summary> /// Configures the ACS service namespace with the proper objects for this sample. /// </summary> /// <remarks> /// Existing objects that are needed for this sample will be deleted and recreated. /// </remarks> static void Main(string[] args) { const string rpName = "ASPNET Simple Forms Sample"; const string rpRealm = "http://localhost:62000/"; const string ruleGroupName = "Default rule group for ASPNET Simple Forms Sample"; const string googleIdpName = "Google"; const string yahooIdpName = "Yahoo!"; ManagementService svc = ManagementServiceHelper.CreateManagementServiceClient(); svc.DeleteRelyingPartyByRealmIfExists(rpRealm); svc.DeleteRuleGroupByNameIfExists(ruleGroupName); svc.DeleteIdentityProviderIfExists(googleIdpName); svc.DeleteIdentityProviderIfExists(yahooIdpName); svc.SaveChangesBatch(); IdentityProvider live = svc.GetIdentityProviderByName("uri:WindowsLiveID"); IdentityProvider google = svc.CreateOpenIdIdentityProvider(googleIdpName, "https://www.google.com/accounts/o8/ud"); IdentityProvider yahoo = svc.CreateOpenIdIdentityProvider(yahooIdpName, "https://open.login.yahooapis.com/openid/op/auth"); IdentityProvider[] associatedProviders = new[] { live, google, yahoo }; // // Create the relying party. In this case, the Realm and the ReplyTo are the same address. // RelyingParty relyingParty = svc.CreateRelyingParty(rpName, rpRealm, rpRealm, RelyingPartyTokenType.SAML_2_0, false); svc.AssociateIdentityProvidersWithRelyingParties(associatedProviders, new[] { relyingParty }); RuleGroup ruleGroup = svc.CreateRuleGroup(ruleGroupName); svc.AssignRuleGroupToRelyingParty(ruleGroup, relyingParty); // // Create simple rules to pass through all claims from each issuer. // foreach (IdentityProvider identityProvider in associatedProviders) { string ruleDescription = String.Format(CultureInfo.InvariantCulture, "Pass through all claims from '{0}'", identityProvider.Issuer.Name); svc.CreateRule(identityProvider.Issuer, null, null, null, null, ruleGroup, ruleDescription); } svc.SaveChangesBatch(); Console.WriteLine("Sample successfully configured. Press ENTER to continue ..."); Console.ReadLine(); }
/// <summary> /// Obtain the AuthenticationCredentials based on AuthenticationProviderType. /// </summary> /// <see href="https://docs.microsoft.com/en-us/dynamics365/customer-engagement/developer/sample-authenticate-users-web-services"/> /// <typeparam name="TService"></typeparam> /// <param name="service">A service management object.</param> /// <param name="endpointType">An <code>AuthenticationProviderType</code> of the CRM environment.</param> /// <param name="userid"></param> /// <param name="userpw"></param> /// <param name="domain"></param> /// <returns>Get filled <code>AuthenticationCredentials</code>.</returns> public AuthenticationCredentials GetCredentials <TService>(IServiceManagement <TService> service, AuthenticationProviderType endpointType, string userid, string userpw, string domain) { AuthenticationCredentials authCredentials = new AuthenticationCredentials(); switch (endpointType) { case AuthenticationProviderType.ActiveDirectory: authCredentials.ClientCredentials.Windows.ClientCredential = new NetworkCredential(userid, userpw, domain); break; case AuthenticationProviderType.LiveId: authCredentials.ClientCredentials.UserName.UserName = userid; authCredentials.ClientCredentials.UserName.Password = userpw; authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = DeviceIdManager.LoadOrRegisterDevice(); break; case AuthenticationProviderType.Federation: case AuthenticationProviderType.None: break; case AuthenticationProviderType.OnlineFederation: // For Federated and OnlineFederated environments. authCredentials.ClientCredentials.UserName.UserName = userid; authCredentials.ClientCredentials.UserName.Password = userpw; // For OnlineFederated single-sign on, you could just use current UserPrincipalName instead of passing user name and password. // authCredentials.UserPrincipalName = UserPrincipal.Current.UserPrincipalName; // Windows Kerberos // The service is configured for User Id authentication, but the user might provide Microsoft // account credentials. If so, the supporting credentials must contain the device credentials. IdentityProvider provider = service.GetIdentityProvider(authCredentials.ClientCredentials.UserName.UserName); if (provider != null && provider.IdentityProviderType == IdentityProviderType.LiveId) { authCredentials.SupportingCredentials = new AuthenticationCredentials(); authCredentials.SupportingCredentials.ClientCredentials = DeviceIdManager.LoadOrRegisterDevice(); } break; default: throw new ArgumentOutOfRangeException(nameof(endpointType), endpointType, null); } return(authCredentials); }
protected override void ProcessCore(IdentityProvidersArgs args) { Assert.ArgumentNotNull(args, "args"); IdentityProvider identityProvider = this.GetIdentityProvider(); string authenticationType = this.GetAuthenticationType(); var clientId = Sitecore.Configuration.Settings.GetSetting("FedAuth.Auth0.ClientId"); var clientSecret = Sitecore.Configuration.Settings.GetSetting("FedAuth.Auth0.ClientSecret"); var domain = Sitecore.Configuration.Settings.GetSetting("FedAuth.Auth0.Domain"); var provider = new Auth0.Owin.Auth0AuthenticationProvider { OnAuthenticated = (context) => { // transform all claims ClaimsIdentity identity = context.Identity; foreach (Transformation current in identityProvider.Transformations) { current.Transform(identity, new TransformationContext(FederatedAuthenticationConfiguration, identityProvider)); } return(System.Threading.Tasks.Task.FromResult(0)); }, OnReturnEndpoint = (context) => { // xsrf validation if (context.Request.Query["state"] != null && context.Request.Query["state"].Contains("xsrf=")) { var state = HttpUtility.ParseQueryString(context.Request.Query["state"]); //todo: do something with it. } return(System.Threading.Tasks.Task.FromResult(0)); } }; // not needed yet. //Auth0AuthenticationOptions options = new Auth0AuthenticationOptions(); // need to change these into settngs args.App.UseAuth0Authentication( clientId: clientId, clientSecret: clientSecret, domain: domain, provider: provider); }
/// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services"></param> public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddScoped(_ => IdentityProvider.GetUserIdentity(IdentityProvider.UserIdentityType.AutoDetect)); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddDbContext <GTPSContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:GtpsConnectionString"])); services.AddTransient <IDataAccess, DataAccess>(); //services.AddCors(options => //{ // options.AddPolicy("AllowSpecificOrigin", // builder => builder // .WithOrigins(this.Configuration.GetValue<string>("AllowAddressList")) // .AllowAnyHeader() // .AllowAnyMethod() // .SetPreflightMaxAge(new TimeSpan(1, 0, 0, 0)) // .AllowCredentials()); //}); // IISDefaults requires the following import: // using Microsoft.AspNetCore.Server.IISIntegration; services.AddAuthentication(IISDefaults.AuthenticationScheme); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "Front Office Entity API - " + this.CurrentEnvironment.EnvironmentName.ToUpper(), Description = "Front Office FOA Entity API -Swagger Documentation", TermsOfService = "None", Contact = new Contact() { Name = "Support", Email = "*****@*****.**", Url = "www.GAM.com" } }); }); services.AddSwaggerGen(c => { c.IncludeXmlComments(GetXmlCommentsPath()); }); }
private void CheckIfUnsolicitedIsAllowed(IOptions options, IdentityProvider idp) { if (InResponseTo == null) { if (idp.AllowUnsolicitedAuthnResponse) { options.SPOptions.Logger.WriteVerbose("Received unsolicited Saml Response " + Id + " which is allowed for idp " + idp.EntityId.Id); return; } string msg = string.Format(CultureInfo.InvariantCulture, "Unsolicited responses are not allowed for idp \"{0}\".", Issuer.Id); throw new Saml2ResponseFailedValidationException(msg); } }
private static void CheckSignature(HttpRequestData request, IdentityProvider idp, IOptions options) { // Can't use the query string params as found in HttpReqeustData // because they are already unescaped and we need the exact format // of the original data. var rawQueryStringParams = request.Url.Query.TrimStart('?').Split('&').Select(qp => qp.Split('=')).ToDictionary(kv => kv[0], kv => kv[1]); var msgParam = ""; string msg; if (rawQueryStringParams.TryGetValue("SAMLRequest", out msg)) { msgParam = "SAMLRequest=" + msg; } else { msgParam = "SAMLResponse=" + rawQueryStringParams["SAMLResponse"]; } var relayStateParam = ""; string relayState; if (rawQueryStringParams.TryGetValue("RelayState", out relayState)) { relayStateParam = "&RelayState=" + relayState; } var signedString = string.Format(CultureInfo.InvariantCulture, "{0}{1}&SigAlg={2}", msgParam, relayStateParam, rawQueryStringParams["SigAlg"]); var sigAlg = request.QueryString["SigAlg"].Single(); XmlHelpers.ValidateSignatureMethodStrength(options.SPOptions.MinIncomingSigningAlgorithm, sigAlg); var signatureDescription = (SignatureDescription)CryptoConfig.CreateFromName(sigAlg); var hashAlg = signatureDescription.CreateDigest(); hashAlg.ComputeHash(Encoding.UTF8.GetBytes(signedString)); var signature = Convert.FromBase64String(request.QueryString["Signature"].Single()); if (!idp.SigningKeys.Any(kic => signatureDescription.CreateDeformatter(((AsymmetricSecurityKey)kic.CreateKey()).GetAsymmetricAlgorithm(sigAlg, false)).VerifySignature(hashAlg, signature))) { throw new InvalidSignatureException(string.Format(CultureInfo.InvariantCulture, "Message from {0} failed signature verification", idp.EntityId.Id)); } }
public void IdentityProvider_CreateAuthenticateRequest_DestinationInXml() { // %41 is A, which doesn't need to be encoded. Ensure it is kept in original format. string idpUri = "http://idp.example.com/x=%41"; var subject = new IdentityProvider( new EntityId(idpUri), Options.FromConfiguration.SPOptions) { SingleSignOnServiceUrl = new Uri(idpUri) }; var r = subject.CreateAuthenticateRequest(StubFactory.CreateSaml2Urls()); r.ToXElement().Attribute("Destination").Should().NotBeNull() .And.Subject.Value.Should().Be(idpUri); }
/// <summary> /// This method converts the received SAML assertion into an <see cref="IPrincipal"/>. /// </summary> /// <param name="assertion">The assertion.</param> /// <param name="point">The point.</param> /// <returns>The <see cref="IPrincipal"/>.</returns> internal static IPrincipal InitSaml20Identity(Saml20Assertion assertion, IdentityProvider point) { var isPersistentPseudonym = assertion.Subject.Format == Saml20Constants.NameIdentifierFormats.Persistent; // Protocol-level support for persistent pseudonyms: If a mapper has been configured, use it here before constructing the principal. var subjectIdentifier = assertion.Subject.Value; if (isPersistentPseudonym && point.PersistentPseudonym != null) { subjectIdentifier = point.PersistentPseudonym.GetMapper().MapIdentity(assertion.Subject); } // Create identity var identity = new Saml20Identity(subjectIdentifier, assertion.Attributes, isPersistentPseudonym ? assertion.Subject.Value : null); return(new GenericPrincipal(identity, new string[] { })); }
private static CommandResult InitiateLoginToIdp(IOptions options, IDictionary <string, string> relayData, Saml2Urls urls, IdentityProvider idp, Uri returnUrl) { var authnRequest = idp.CreateAuthenticateRequest(urls); options.Notifications.AuthenticationRequestCreated(authnRequest, idp, relayData); var commandResult = idp.Bind(authnRequest); commandResult.RequestState = new StoredRequestState( idp.EntityId, returnUrl, authnRequest.Id, relayData); commandResult.SetCookieName = StoredRequestState.CookieNameBase + authnRequest.RelayState; options.Notifications.SignInCommandResultCreated(commandResult, relayData); return(commandResult); }
public RbacServiceTests() { _identityProvider = GetIdentityProvider("aad", "test", "https://microsoft.onmicrosoft.com/common/"); _controlPlaneDataStore = Substitute.For <IControlPlaneDataStore>(); _controlPlaneDataStore.GetIdentityProviderAsync(_identityProvider.Name, Arg.Any <CancellationToken>()).Returns(_identityProvider); _controlPlaneDataStore.UpsertIdentityProviderAsync(_identityProvider, Arg.Any <string>(), Arg.Any <CancellationToken>()).Returns(new UpsertResponse <IdentityProvider>(_identityProvider, UpsertOutcome.Updated, "testEtag")); IList <ResourcePermission> resourcePermissions = new List <ResourcePermission>(); _role = GetRole("clinician", resourcePermissions); _controlPlaneDataStore.GetRoleAsync(_role.Name, Arg.Any <CancellationToken>()).Returns(_role); _controlPlaneDataStore.UpsertRoleAsync(_role, Arg.Any <string>(), Arg.Any <CancellationToken>()).Returns(new UpsertResponse <Role>(_role, UpsertOutcome.Updated, "testEtag")); _controlPlaneDataStore.DeleteRoleAsync(_role.Name, Arg.Any <string>(), Arg.Any <CancellationToken>()); _rbacService = new RbacService(_controlPlaneDataStore); }
public ActionResult Index(ManageProviderModel model) { int currentPage = 1; int pageSize = SystemSettings.DefaultPageSize; if (string.IsNullOrEmpty(model.SearchExec)) { model.SearchExec = "Y"; if (!ModelState.IsValid) { ModelState.Clear(); } } if (Request["Page"] != null) { currentPage = Utils.ConvertToInt32(Request["Page"], 1); } var filter = new IdentityProvider { Keyword = !string.IsNullOrEmpty(model.Keyword) ? model.Keyword.Trim() : null, Status = model.Status == null ? -1 : (int)model.Status }; try { model.SearchResults = _mainStore.GetByPage(filter, currentPage, SystemSettings.DefaultPageSize); if (model.SearchResults != null && model.SearchResults.Count > 0) { model.TotalCount = model.SearchResults[0].TotalCount; model.CurrentPage = currentPage; model.PageSize = pageSize; } } catch (Exception ex) { this.AddNotification(NotifSettings.Error_SystemBusy, NotificationType.ERROR); logger.Error("Failed to display Index page because: " + ex.ToString()); return(View(model)); } return(View(model)); }
public void CreateAccountFailToLoginWithoutMailConfirmed() { var hashMock = new Mock <IHasher>(); hashMock.Setup(h => h.HashText(It.Is <string>(pas => pas.Equals(password)))); db.Users.Remove(db.Users.Single()); sut = new IdentityProvider(db, hashMock.Object, mailMock.Object); ExpectMail(); var result = sut.RegisterUser(accName, password, receiver); Assert.Equal(AccountCreate.OkMessage, result); VerifyMailSent(); Assert.False(sut.LogIn(accName, "not")); Assert.False(sut.LogIn(accName, password)); }
public void IdentityProvider_Ctor_ChoosesSupportedBindingFromMetadata() { var config = CreateConfig(); config.LoadMetadata = true; config.EntityId = "http://localhost:13428/idpMetadataWithArtifactBinding"; var subject = new IdentityProvider(config, Options.FromConfiguration.SPOptions); subject.Binding.Should().Be(Saml2BindingType.HttpPost); subject.SingleSignOnServiceUrl.Should().Be("http://idpArtifact.example.com/POST"); }
public void IdentityProvider_ReadMetadata_Nullcheck() { var subject = new IdentityProvider( new EntityId("http://idp.example.com"), StubFactory.CreateSPOptions()); Action a = () => subject.ReadMetadata(null); a.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("metadata"); }
/// <summary> /// Try to get the value of an idp with a given entity id. /// </summary> /// <param name="idpEntityId">Entity id to search for.</param> /// <param name="idp">The idp, if found.</param> /// <returns>True if an idp with the given entity id was found.</returns> public bool TryGetValue(EntityId idpEntityId, out IdentityProvider idp) { lock (dictionary) { return dictionary.TryGetValue(idpEntityId, out idp); } }
public void IdentityProvider_Ctor_UseMetadataLocationUrl() { var config = CreateConfig(); config.LoadMetadata = true; config.MetadataLocation = "http://localhost:13428/idpMetadataDifferentEntityId"; config.EntityId = "some-idp"; var subject = new IdentityProvider(config, Options.FromConfiguration.SPOptions); subject.Binding.Should().Be(Saml2BindingType.HttpRedirect); subject.SingleSignOnServiceUrl.Should().Be("http://idp.example.com/SsoService"); }
public void IdentityProvider_Ctor_LogoutBindingDefaultsToBinding() { var config = CreateConfig(); var subject = new IdentityProvider(config, StubFactory.CreateSPOptions()); subject.Binding.Should().Be(Saml2BindingType.HttpPost); subject.SingleLogoutServiceBinding.Should().Be(Saml2BindingType.HttpPost); }
public IAsyncResult Begin_requestAccountPasswordReset(AsyncCallback callback, object state, IdentityProvider provider, string identifier, string locale) { return send_requestAccountPasswordReset(callback, state, provider, identifier, locale); }
public void requestAccountPasswordReset(IdentityProvider provider, string identifier, string locale) { #if !SILVERLIGHT send_requestAccountPasswordReset(provider, identifier, locale); recv_requestAccountPasswordReset(); #else var asyncResult = Begin_requestAccountPasswordReset(null, null, provider, identifier, locale); End_requestAccountPasswordReset(asyncResult); #endif }
public void send_requestAccountPasswordReset(IdentityProvider provider, string identifier, string locale) #endif { oprot_.WriteMessageBegin(new TMessage("requestAccountPasswordReset", TMessageType.Call, seqid_)); requestAccountPasswordReset_args args = new requestAccountPasswordReset_args(); args.Provider = provider; args.Identifier = identifier; args.Locale = locale; args.Write(oprot_); oprot_.WriteMessageEnd(); #if SILVERLIGHT return oprot_.Transport.BeginFlush(callback, state); #else oprot_.Transport.Flush(); #endif }
public void IdentityProvider_Ctor_DisableOutboundLogoutRequest() { var config = CreateConfig(); config.DisableOutboundLogoutRequests = true; var subject = new IdentityProvider(config, StubFactory.CreateSPOptions()); subject.DisableOutboundLogoutRequests.Should().BeTrue(); }
public void IdentityProvider_MetadataLocation_ThrowsWhenEntitiesDescriptorFoundAndNotAllowedByConfig() { var spOptions = StubFactory.CreateSPOptions(); spOptions.Compatibility.UnpackEntitiesDescriptorInIdentityProviderMetadata.Should().BeFalse(); var subject = new IdentityProvider( new EntityId("http://idp.example.com"), spOptions); Action a = () => subject.MetadataLocation = "~/Metadata/SingleIdpInEntitiesDescriptor.xml"; a.ShouldThrow<InvalidOperationException>(); }
public void IdentityProvider_Ctor_HandlesConfiguredCertificateWhenReadingMetadata() { var config = CreateConfig(); config.LoadMetadata = true; config.EntityId = "http://localhost:13428/idpMetadataNoCertificate"; var subject = new IdentityProvider(config, Options.FromConfiguration.SPOptions); // Check that metadata was read and overrides configured values. subject.Binding.Should().Be(Saml2BindingType.HttpRedirect); subject.SigningKeys.Single().ShouldBeEquivalentTo( new X509RawDataKeyIdentifierClause(SignedXmlHelper.TestCert)); }
public void IdentityProvider_MetadataValidUntil_CalculatedFromCacheDuration() { var config = CreateConfig(); config.LoadMetadata = true; config.EntityId = "http://localhost:13428/idpMetadataNoCertificate"; var subject = new IdentityProvider(config, Options.FromConfiguration.SPOptions); var expectedValidUntil = DateTime.UtcNow.AddMinutes(15); // Comparison on the second is more than enough if we're adding 15 minutes. subject.MetadataValidUntil.Should().BeCloseTo(expectedValidUntil, 1000); }
public void IdentityProvider_Ctor_PrefersRedirectBindingFromMetadata() { var config = CreateConfig(); config.LoadMetadata = true; config.EntityId = "http://localhost:13428/idpMetadataWithMultipleBindings"; var subject = new IdentityProvider(config, Options.FromConfiguration.SPOptions); subject.Binding.Should().Be(Saml2BindingType.HttpRedirect); subject.SingleSignOnServiceUrl.Should().Be("http://idp2Bindings.example.com/Redirect"); }
public void IdentityProvider_MetadataValidUntil_NullOnConfigured() { string idpUri = "http://idp.example.com/"; var subject = new IdentityProvider( new EntityId(idpUri), Options.FromConfiguration.SPOptions); subject.MetadataValidUntil.Should().NotHaveValue(); }
public void IdentityProvider_MetadataLoadedConfiguredFromCode() { var spOptions = StubFactory.CreateSPOptions(); spOptions.ServiceCertificates.Add(new ServiceCertificate() { Certificate = SignedXmlHelper.TestCert }); var subject = new IdentityProvider( new EntityId("http://other.entityid.example.com"), spOptions) { MetadataLocation = "http://localhost:13428/idpMetadataOtherEntityId", AllowUnsolicitedAuthnResponse = true }; subject.AllowUnsolicitedAuthnResponse.Should().BeTrue(); subject.Binding.Should().Be(Saml2BindingType.HttpRedirect); subject.EntityId.Id.Should().Be("http://other.entityid.example.com"); // If a metadatalocation is set, metadata loading is automatically enabled. subject.LoadMetadata.Should().BeTrue(); subject.MetadataLocation.Should().Be("http://localhost:13428/idpMetadataOtherEntityId"); subject.MetadataValidUntil.Should().BeCloseTo( DateTime.UtcNow.Add(MetadataRefreshScheduler.DefaultMetadataCacheDuration), precision: 100); subject.SingleSignOnServiceUrl.Should().Be("http://wrong.entityid.example.com/acs"); subject.WantAuthnRequestsSigned.Should().Be(true, "WantAuthnRequestsSigned should have been loaded from metadata"); Action a = () => subject.CreateAuthenticateRequest(StubFactory.CreateAuthServicesUrls()); a.ShouldNotThrow(); }
public IAsyncResult send_requestAccountPasswordReset(AsyncCallback callback, object state, IdentityProvider provider, string identifier, string locale)
public void IdentityProvider_MetadataLocation_UnpacksEntitiesDescriptor_if_configured() { var spOptions = StubFactory.CreateSPOptions(); spOptions.Compatibility.UnpackEntitiesDescriptorInIdentityProviderMetadata = true; var subject = new IdentityProvider( new EntityId("http://idp.federation.example.com/metadata"), spOptions); Action a = () => subject.MetadataLocation = "~/Metadata/SingleIdpInEntitiesDescriptor.xml"; a.ShouldNotThrow(); }
public void IdentityProvider_ConfigFromMetadata() { var entityId = new EntityId("http://localhost:13428/idpMetadata"); var subject = new IdentityProvider(entityId, StubFactory.CreateSPOptions()); // Add one that will be removed by loading. subject.ArtifactResolutionServiceUrls.Add(234, new Uri("http://example.com")); subject.LoadMetadata = true; subject.EntityId.Id.Should().Be(entityId.Id); subject.Binding.Should().Be(Saml2BindingType.HttpPost); subject.SingleSignOnServiceUrl.Should().Be(new Uri("http://localhost:13428/acs")); subject.SigningKeys.Single().ShouldBeEquivalentTo(new X509RawDataKeyIdentifierClause(SignedXmlHelper.TestCert)); subject.ArtifactResolutionServiceUrls.Count.Should().Be(2); subject.ArtifactResolutionServiceUrls[0x1234].OriginalString .Should().Be("http://localhost:13428/ars"); subject.ArtifactResolutionServiceUrls[117].OriginalString .Should().Be("http://localhost:13428/ars2"); subject.SingleLogoutServiceUrl.OriginalString.Should().Be("http://localhost:13428/logout"); subject.SingleLogoutServiceResponseUrl.OriginalString.Should().Be("http://localhost:13428/logoutResponse"); subject.SingleLogoutServiceBinding.Should().Be(Saml2BindingType.HttpRedirect); }
public void IdentityProvider_MetadataValidUntil_Loaded() { var config = CreateConfig(); config.LoadMetadata = true; config.EntityId = "http://localhost:13428/idpMetadata"; var subject = new IdentityProvider(config, Options.FromConfiguration.SPOptions); subject.MetadataValidUntil.Should().Be(new DateTime(2100, 01, 02, 14, 42, 43, DateTimeKind.Utc)); }
public void IdentityProvider_ConfigFromMetadata_LogoutResponse_DefaultsToSingleLogoutServiceUrl() { var entityId = new EntityId("http://localhost:13428/idpMetadataNoCertificate"); var subject = new IdentityProvider(entityId, StubFactory.CreateSPOptions()); subject.SigningKeys.AddConfiguredKey(SignedXmlHelper.TestCert); subject.LoadMetadata = true; subject.SingleLogoutServiceResponseUrl.OriginalString.Should().Be("http://localhost:13428/logout"); subject.SingleLogoutServiceBinding.Should().Be(Saml2BindingType.HttpRedirect); }
public void IdentityProvider_NoMetadataLoadConfiguredFromCode() { var subject = new IdentityProvider( new EntityId("http://idp.example.com"), StubFactory.CreateSPOptions()) { AllowUnsolicitedAuthnResponse = true, Binding = Saml2BindingType.HttpPost, SingleSignOnServiceUrl = new Uri("http://idp.example.com/sso") }; subject.SigningKeys.AddConfiguredKey(SignedXmlHelper.TestKey); subject.AllowUnsolicitedAuthnResponse.Should().BeTrue(); subject.Binding.Should().Be(Saml2BindingType.HttpPost); subject.EntityId.Id.Should().Be("http://idp.example.com"); subject.LoadMetadata.Should().BeFalse(); subject.MetadataLocation.Should().Be("http://idp.example.com"); subject.MetadataValidUntil.Should().NotHaveValue(); var subjectKeyParams = subject.SigningKeys.Single().CreateKey() .As<RsaSecurityKey>().GetAsymmetricAlgorithm(SecurityAlgorithms.RsaSha1Signature, false).As<RSA>() .ExportParameters(false); var expectedKeyParams = SignedXmlHelper.TestCert.PublicKey.Key.As<RSA>() .ExportParameters(false); subjectKeyParams.Modulus.ShouldBeEquivalentTo(expectedKeyParams.Modulus); subjectKeyParams.Exponent.ShouldBeEquivalentTo(expectedKeyParams.Exponent); subject.SingleSignOnServiceUrl.AbsoluteUri.Should().Be("http://idp.example.com/sso"); }
public void IdentityProvider_ConstructedFromEntityDescriptor_DoesntReloadMetadataWhenDisabled() { var ed = new ExtendedEntityDescriptor { ValidUntil = DateTime.UtcNow.AddYears(-1), EntityId = new EntityId("someEntityId") }; var idpSsoDescriptor = new IdentityProviderSingleSignOnDescriptor(); idpSsoDescriptor.ProtocolsSupported.Add(new Uri("urn:oasis:names:tc:SAML:2.0:protocol")); ed.RoleDescriptors.Add(idpSsoDescriptor); idpSsoDescriptor.SingleSignOnServices.Add(new ProtocolEndpoint() { Binding = Saml2Binding.HttpRedirectUri, Location = new Uri("http://idp.example.com/sso") }); idpSsoDescriptor.Keys.Add(SignedXmlHelper.TestKeyDescriptor); var subject = new IdentityProvider(ed.EntityId, StubFactory.CreateSPOptions()); Action a = () => { var b = subject.Binding; }; subject.LoadMetadata.Should().BeFalse(); // Will throw invalid Uri if it tries to use EntityId as metadata url. a.ShouldNotThrow(); }
public void IdentityProvider_ConstructedFromEntityDescriptor_DoesntScheduleMedataRefresh() { MetadataRefreshScheduler.minInterval = new TimeSpan(0, 0, 0, 0, 1); var ed = new ExtendedEntityDescriptor { ValidUntil = DateTime.UtcNow.AddYears(-1), EntityId = new EntityId("http://localhost:13428/idpMetadata") }; var idpSsoDescriptor = new IdentityProviderSingleSignOnDescriptor(); idpSsoDescriptor.ProtocolsSupported.Add(new Uri("urn:oasis:names:tc:SAML:2.0:protocol")); ed.RoleDescriptors.Add(idpSsoDescriptor); var pe = new ProtocolEndpoint() { Binding = Saml2Binding.HttpRedirectUri, Location = new Uri("http://idp.example.com/sso") }; idpSsoDescriptor.SingleSignOnServices.Add(pe); idpSsoDescriptor.Keys.Add(SignedXmlHelper.TestKeyDescriptor); var subject = new IdentityProvider(ed.EntityId, StubFactory.CreateSPOptions()); subject.ReadMetadata(ed); // Ugly, but have to wait and see that nothing happened. Have tried // some different timeouts but need 100 to ensure fail before bug // is fixed :-( Thread.Sleep(100); // Would be changed if metadata was reloaded. subject.SingleSignOnServiceUrl.Should().Be(pe.Location); }
public void IdentityProvider_CreateAuthenticateRequest_SigningBehaviorNever_OverridesIdpWantsRequestsSigned() { var options = StubFactory.CreateOptions(); var spOptions = options.SPOptions; spOptions.AuthenticateRequestSigningBehavior = SigningBehavior.Never; spOptions.ServiceCertificates.Add(new ServiceCertificate { Certificate = SignedXmlHelper.TestCert }); var subject = new IdentityProvider(new EntityId("http://idp.example.com"), spOptions) { WantAuthnRequestsSigned = true }; var urls = StubFactory.CreateAuthServicesUrls(); var actual = subject.CreateAuthenticateRequest(urls).SigningCertificate; actual.Should().BeNull(); }
public void Saml2Response_GetClaims_CorrectSignedResponseMessageSecondaryKey() { var response = @"<?xml version=""1.0"" encoding=""UTF-8""?> <saml2p:Response xmlns:saml2p=""urn:oasis:names:tc:SAML:2.0:protocol"" xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion"" ID = """ + MethodBase.GetCurrentMethod().Name + @""" Version=""2.0"" IssueInstant=""2013-01-01T00:00:00Z""> <saml2:Issuer>https://twokeys.example.com</saml2:Issuer> <saml2p:Status> <saml2p:StatusCode Value=""urn:oasis:names:tc:SAML:2.0:status:Success"" /> </saml2p:Status> <saml2:Assertion xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion"" Version=""2.0"" ID=""" + MethodBase.GetCurrentMethod().Name + @"_Assertion1"" IssueInstant=""2013-09-25T00:00:00Z""> <saml2:Issuer>https://twokeys.example.com</saml2:Issuer> <saml2:Subject> <saml2:NameID>SomeUser</saml2:NameID> <saml2:SubjectConfirmation Method=""urn:oasis:names:tc:SAML:2.0:cm:bearer"" /> </saml2:Subject> <saml2:Conditions NotOnOrAfter=""2100-01-01T00:00:00Z"" /> </saml2:Assertion> </saml2p:Response>"; var signedResponse = SignedXmlHelper.SignXml(response); var options = StubFactory.CreateOptions(); var idp = new IdentityProvider( new EntityId("https://twokeys.example.com"), options.SPOptions) { AllowUnsolicitedAuthnResponse = true }; idp.SigningKeys.AddConfiguredKey(SignedXmlHelper.TestKey2); idp.SigningKeys.AddConfiguredKey(SignedXmlHelper.TestKey); options.IdentityProviders.Add(idp); Action a = () => Saml2Response.Read(signedResponse).GetClaims(options); a.ShouldNotThrow(); }