public void RoundTripWsMetadata(EnvelopedSignatureTheoryData theoryData) { var context = TestUtilities.WriteHeader($"{this}.RoundTripWsMetadata", theoryData); try { var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(false) }; var buffer = new MemoryStream(); var esw = new EnvelopedSignatureWriter(XmlWriter.Create(buffer, settings), theoryData.SigningCredentials, theoryData.ReferenceId); theoryData.Action.DynamicInvoke(esw); var metadata = Encoding.UTF8.GetString(buffer.ToArray()); var configuration = new WsFederationConfiguration(); var reader = XmlReader.Create(new StringReader(metadata)); configuration = new WsFederationMetadataSerializer().ReadMetadata(reader); configuration.Signature.Verify(theoryData.SigningCredentials.Key, theoryData.SigningCredentials.Key.CryptoProviderFactory); theoryData.ExpectedException.ProcessNoException(context); } catch (Exception ex) { theoryData.ExpectedException.ProcessException(ex, context); } TestUtilities.AssertFailIfErrors(context); }
public static void PreAppStart() { FederatedAuthentication.FederationConfigurationCreated += (sender, args) => { // Load config var audience = ConfigurationManager.AppSettings["Auth.AudienceUrl"]; var realm = ConfigurationManager.AppSettings["Auth.AuthenticationRealm"]; var issuer = ConfigurationManager.AppSettings["Auth.AuthenticationIssuer"]; var thumbprint = ConfigurationManager.AppSettings["Auth.AuthenticationIssuerThumbprint"]; var idconfig = new IdentityConfiguration(); idconfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audience)); var registry = new ConfigurationBasedIssuerNameRegistry(); registry.AddTrustedIssuer(thumbprint, issuer); idconfig.IssuerNameRegistry = registry; var sessionTransforms = new List <CookieTransform>() { new DeflateCookieTransform(), new MachineKeyTransform() }; idconfig.SecurityTokenHandlers.AddOrReplace(new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly())); var wsfedconfig = new WsFederationConfiguration(issuer, realm); wsfedconfig.PersistentCookiesOnPassiveRedirects = true; wsfedconfig.PassiveRedirectEnabled = true; args.FederationConfiguration.IdentityConfiguration = idconfig; args.FederationConfiguration.WsFederationConfiguration = wsfedconfig; args.FederationConfiguration.CookieHandler = new ChunkedCookieHandler(); }; }
private void SetupFederatedLogin() { FederatedAuthentication.FederationConfigurationCreated += (sender, args) => { var config = Kernel.Get <IConfigurationService>(); var idconfig = new IdentityConfiguration(); idconfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(config.Auth.AudienceUrl)); var registry = new ConfigurationBasedIssuerNameRegistry(); registry.AddTrustedIssuer(config.Auth.TokenCertificateThumbprint, config.Auth.AuthenticationIssuer); idconfig.IssuerNameRegistry = registry; idconfig.CertificateValidationMode = X509CertificateValidationMode.None; var sessionTransforms = new List <CookieTransform>() { new DeflateCookieTransform(), new MachineKeyTransform() }; idconfig.SecurityTokenHandlers.AddOrReplace(new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly())); var wsfedconfig = new WsFederationConfiguration(config.Auth.AuthenticationIssuer, config.Auth.AuthenticationRealm); wsfedconfig.PersistentCookiesOnPassiveRedirects = true; args.FederationConfiguration.IdentityConfiguration = idconfig; args.FederationConfiguration.WsFederationConfiguration = wsfedconfig; args.FederationConfiguration.CookieHandler = new ChunkedCookieHandler(); }; }
public static void PreAppStart() { FederatedAuthentication.FederationConfigurationCreated += (sender, args) => { // Load config var audience = ConfigurationManager.AppSettings["Auth.AudienceUrl"]; var realm = ConfigurationManager.AppSettings["Auth.AuthenticationRealm"]; var issuer = ConfigurationManager.AppSettings["Auth.AuthenticationIssuer"]; var thumbprint = ConfigurationManager.AppSettings["Auth.AuthenticationIssuerThumbprint"]; var idconfig = new IdentityConfiguration(); idconfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(audience)); var registry = new ConfigurationBasedIssuerNameRegistry(); registry.AddTrustedIssuer(thumbprint, issuer); idconfig.IssuerNameRegistry = registry; var sessionTransforms = new List<CookieTransform>() { new DeflateCookieTransform(), new MachineKeyTransform() }; idconfig.SecurityTokenHandlers.AddOrReplace(new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly())); var wsfedconfig = new WsFederationConfiguration(issuer, realm); wsfedconfig.PersistentCookiesOnPassiveRedirects = true; wsfedconfig.PassiveRedirectEnabled = true; args.FederationConfiguration.IdentityConfiguration = idconfig; args.FederationConfiguration.WsFederationConfiguration = wsfedconfig; args.FederationConfiguration.CookieHandler = new ChunkedCookieHandler(); }; }
// Code adapted from // https://github.com/aspnet/Security/blob/rel/2.0.0-ws-rtm/src/Microsoft.AspNetCore.Authentication.WsFederation/WsFederationHandler.cs // HandleRemoteAuthenticateAsync() private async Task <ClaimsPrincipal> Validate(string token) { if (_configuration == null) { _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted); } // Copy and augment to avoid cross request race conditions for updated configurations. var tvp = Options.TokenValidationParameters.Clone(); var issuers = new[] { _configuration.Issuer }; tvp.ValidIssuers = (tvp.ValidIssuers == null ? issuers : tvp.ValidIssuers.Concat(issuers)); tvp.IssuerSigningKeys = (tvp.IssuerSigningKeys == null ? _configuration.SigningKeys : tvp.IssuerSigningKeys.Concat(_configuration.SigningKeys)); ClaimsPrincipal principal = null; SecurityToken parsedToken = null; foreach (var validator in Options.SecurityTokenHandlers) { if (validator.CanReadToken(token)) { principal = validator.ValidateToken(token, tvp, out parsedToken); break; } } if (principal == null) { throw new SecurityTokenException("NoTokenValidatorFound"); } return(principal); }
public void ReadMetadata(WsFederationMetadataTheoryData theoryData) { var context = TestUtilities.WriteHeader($"{this}.ReadMetadata", theoryData); try { var config = ReferenceMetadata.AADCommonEndpoint; var configuration = new WsFederationConfiguration(); if (!string.IsNullOrEmpty(theoryData.Metadata)) { var reader = XmlReader.Create(new StringReader(theoryData.Metadata)); configuration = theoryData.Serializer.ReadMetadata(reader); } else { var reader = XmlReader.Create(theoryData.MetadataPath); configuration = theoryData.Serializer.ReadMetadata(reader); } if (theoryData.SigingKey != null) { configuration.Signature.Verify(theoryData.SigingKey, theoryData.SigingKey.CryptoProviderFactory); } theoryData.ExpectedException.ProcessNoException(context); IdentityComparer.AreWsFederationConfigurationsEqual(configuration, theoryData.Configuration, context); } catch (Exception ex) { theoryData.ExpectedException.ProcessException(ex, context); } TestUtilities.AssertFailIfErrors(context); }
/// <summary> /// Handles Challenge /// </summary> /// <returns></returns> protected override async Task HandleChallengeAsync(AuthenticationProperties properties) { if (_configuration == null) { _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted); } // Save the original challenge URI so we can redirect back to it when we're done. if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = OriginalPathBase + OriginalPath + Request.QueryString; } var wsFederationMessage = new WsFederationMessage() { IssuerAddress = _configuration.TokenEndpoint ?? string.Empty, Wtrealm = Options.Wtrealm, Wa = WsFederationConstants.WsFederationActions.SignIn, }; if (!string.IsNullOrEmpty(Options.Wreply)) { wsFederationMessage.Wreply = Options.Wreply; } else { wsFederationMessage.Wreply = BuildRedirectUri(Options.CallbackPath); } GenerateCorrelationId(properties); var redirectContext = new RedirectContext(Context, Scheme, Options, properties) { ProtocolMessage = wsFederationMessage }; await Events.RedirectToIdentityProvider(redirectContext); if (redirectContext.Handled) { return; } wsFederationMessage = redirectContext.ProtocolMessage; if (!string.IsNullOrEmpty(wsFederationMessage.Wctx)) { properties.Items[WsFederationDefaults.UserstatePropertiesKey] = wsFederationMessage.Wctx; } wsFederationMessage.Wctx = Uri.EscapeDataString(Options.StateDataFormat.Protect(properties)); var redirectUri = wsFederationMessage.CreateSignInUrl(); if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute)) { Logger.MalformedRedirectUri(redirectUri); } Response.Redirect(redirectUri); }
/// <summary> /// Handles Signout /// </summary> /// <returns></returns> protected override async Task ApplyResponseGrantAsync() { AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode); if (signout == null) { return; } if (_configuration == null) { _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled); } WsFederationMessage wsFederationMessage = new WsFederationMessage() { IssuerAddress = _configuration.TokenEndpoint ?? string.Empty, Wtrealm = Options.Wtrealm, Wa = WsFederationActions.SignOut, }; // Set Wreply in order: // 1. properties.Redirect // 2. Options.SignOutWreply // 3. Options.Wreply AuthenticationProperties properties = signout.Properties; if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri)) { wsFederationMessage.Wreply = properties.RedirectUri; } else if (!string.IsNullOrWhiteSpace(Options.SignOutWreply)) { wsFederationMessage.Wreply = Options.SignOutWreply; } else if (!string.IsNullOrWhiteSpace(Options.Wreply)) { wsFederationMessage.Wreply = Options.Wreply; } var notification = new RedirectToIdentityProviderNotification <WsFederationMessage, WsFederationAuthenticationOptions>(Context, Options) { ProtocolMessage = wsFederationMessage }; await Options.Notifications.RedirectToIdentityProvider(notification); if (!notification.HandledResponse) { string redirectUri = notification.ProtocolMessage.CreateSignOutUrl(); if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute)) { _logger.WriteWarning("The sign-out redirect URI is malformed: " + redirectUri); } Response.Redirect(redirectUri); } }
/// <summary> /// Handles Signout /// </summary> /// <returns></returns> public async virtual Task SignOutAsync(AuthenticationProperties properties) { var target = ResolveTarget(Options.ForwardSignOut); if (target != null) { await Context.SignOutAsync(target, properties); return; } if (_configuration == null) { _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted); } var wsFederationMessage = new WsFederationMessage() { IssuerAddress = _configuration.TokenEndpoint ?? string.Empty, Wtrealm = Options.Wtrealm, Wa = WsFederationConstants.WsFederationActions.SignOut, }; // Set Wreply in order: // 1. properties.Redirect // 2. Options.SignOutWreply // 3. Options.Wreply if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri)) { wsFederationMessage.Wreply = BuildRedirectUriIfRelative(properties.RedirectUri); } else if (!string.IsNullOrEmpty(Options.SignOutWreply)) { wsFederationMessage.Wreply = BuildRedirectUriIfRelative(Options.SignOutWreply); } else if (!string.IsNullOrEmpty(Options.Wreply)) { wsFederationMessage.Wreply = BuildRedirectUriIfRelative(Options.Wreply); } var redirectContext = new RedirectContext(Context, Scheme, Options, properties) { ProtocolMessage = wsFederationMessage }; await Events.RedirectToIdentityProvider(redirectContext); if (!redirectContext.Handled) { var redirectUri = redirectContext.ProtocolMessage.CreateSignOutUrl(); if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute)) { Logger.MalformedRedirectUri(redirectUri); } Response.Redirect(redirectUri); } }
public static bool AreWsFederationConfigurationsEqual(WsFederationConfiguration configuration1, WsFederationConfiguration configuration2, CompareContext context) { var localContext = new CompareContext(context); if (ContinueCheckingEquality(configuration1, configuration2, localContext)) { CompareAllPublicProperties(configuration1, configuration2, localContext); } return(context.Merge(localContext)); }
public ActionResult SignIn() { WsFederationConfiguration config = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration; string callbackUrl = Url.Action("Index", "Home", routeValues: null, protocol: Request.Url.Scheme); SignInRequestMessage signinMessage = new SignInRequestMessage(new Uri(config.Issuer), callbackUrl); signinMessage.SetParameter("wtrealm", IdentityConfig.Realm ?? config.Realm); return(new RedirectResult(signinMessage.WriteQueryString())); }
protected void Page_Load(object sender, EventArgs e) { if (Request.IsAuthenticated) { WsFederationConfiguration config = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration; string callbackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Response.ApplyAppPathModifier("~/"); SignOutRequestMessage signoutMessage = new SignOutRequestMessage(new Uri(config.Issuer), callbackUrl); signoutMessage.SetParameter("wtrealm", IdentityConfig.Realm ?? config.Realm); FederatedAuthentication.SessionAuthenticationModule.SignOut(); Response.Redirect(signoutMessage.WriteQueryString()); } }
/// <summary> /// Handles Challenge /// </summary> /// <returns></returns> protected override async Task HandleChallengeAsync(AuthenticationProperties properties) { if (_configuration == null) { _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted); } string baseUri = Request.Scheme + Uri.SchemeDelimiter + Request.Host + Request.PathBase; string currentUri = baseUri + Request.Path + Request.QueryString; // Save the original challenge URI so we can redirect back to it when we're done. if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = currentUri; } WsFederationMessage wsFederationMessage = new WsFederationMessage() { IssuerAddress = _configuration.TokenEndpoint ?? string.Empty, Wtrealm = Options.Wtrealm, Wctx = WsFederationDefaults.WctxKey + "=" + Uri.EscapeDataString(Options.StateDataFormat.Protect(properties)), Wa = WsFederationConstants.WsFederationActions.SignIn, }; if (!string.IsNullOrWhiteSpace(Options.Wreply)) { wsFederationMessage.Wreply = Options.Wreply; } var redirectContext = new RedirectContext(Context, Scheme, Options, properties) { ProtocolMessage = wsFederationMessage }; await Options.Events.RedirectToIdentityProvider(redirectContext); if (!redirectContext.Handled) { string redirectUri = redirectContext.ProtocolMessage.CreateSignInUrl(); if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute)) { Logger.LogWarning("The sign-in redirect URI is malformed: " + redirectUri); } Response.Redirect(redirectUri); } }
public ActionResult SignOut() { WsFederationConfiguration config = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration; // Redirect to SignOutCallback after signing out. string callbackUrl = Url.Action("SignOutCallback", "Account", routeValues: null, protocol: Request.Url.Scheme); SignOutRequestMessage signoutMessage = new SignOutRequestMessage(new Uri(config.Issuer), callbackUrl); signoutMessage.SetParameter("wtrealm", IdentityConfig.Realm ?? config.Realm); FederatedAuthentication.SessionAuthenticationModule.SignOut(); return(new RedirectResult(signoutMessage.WriteQueryString())); }
// // GET: /Admin/SignOut public void SignOut() { WsFederationConfiguration fc = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration; string wreply = System.Web.HttpContext.Current.Request.UrlReferrer.ToString(); SignOutRequestMessage soMessage = new SignOutRequestMessage(new Uri(fc.Issuer), wreply); soMessage.SetParameter("wtrealm", fc.Realm); FederatedAuthentication.SessionAuthenticationModule.SignOut(); Response.Redirect(soMessage.WriteQueryString()); }
protected void AuthenticateUser() { //Redirect to Home page after SignIn WsFederationConfiguration config = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration; string callbackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Response.ApplyAppPathModifier("~/"); SignInRequestMessage signInRequest = FederatedAuthentication.WSFederationAuthenticationModule.CreateSignInRequest( uniqueId: String.Empty, returnUrl: callbackUrl, rememberMeSet: false); signInRequest.SetParameter("wtrealm", IdentityConfig.Realm ?? config.Realm); Response.Redirect(signInRequest.RequestUrl.ToString()); }
protected virtual async Task ApplyResponseLogoutAsync() { var options = Options as Saml2AuthenticationOptions; if (options == null) { return; } if (_configuration == null) { _configuration = await options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled); } var request = Context.Get <HttpContextBase>(typeof(HttpContextBase).FullName).Request; foreach (var signingKey in _configuration.SigningKeys.OfType <X509SecurityKey>()) { var binding = new Saml2PostBinding(); Saml2LogoutResponse response = null; try { response = binding.Unbind(request, new Saml2LogoutResponse(), signingKey.Certificate) as Saml2LogoutResponse; } catch (Saml2ResponseException) { } if (response == null || response.Status != Saml2StatusCodes.Success) { continue; } var relayState = binding.GetRelayStateQuery(); var properties = relayState.ContainsKey(_relayStateWctx) ? Options.StateDataFormat.Unprotect(relayState[_relayStateWctx]) : new AuthenticationProperties(); if (string.IsNullOrWhiteSpace(properties.RedirectUri)) { properties.RedirectUri = GetRedirectUri(binding, options); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("RedirectUri={0}", properties.RedirectUri)); Response.Redirect(properties.RedirectUri); return; } }
public void CompareWsFederationConfiguration() { TestUtilities.WriteHeader($"{this}.CompareWsFederationConfiguration", true); var context = new CompareContext($"{this}.CompareWsFederationConfiguration"); var config1 = new WsFederationConfiguration { TokenEndpoint = Guid.NewGuid().ToString() }; var config2 = new WsFederationConfiguration { TokenEndpoint = Guid.NewGuid().ToString() }; IdentityComparer.AreEqual(config1, config2, context); Assert.True(context.Diffs.Count(s => s == "TokenEndpoint:") == 1); }
private static void WriteKeyDescriptorForSigning(WsFederationConfiguration configuration, XmlWriter writer) { // <KeyDescriptor> writer.WriteStartElement(Elements.KeyDescriptor, WsFederationConstants.MetadataNamespace); writer.WriteAttributeString(Attributes.Use, WsFederationConstants.KeyUse.Signing); var dsigSerializer = new DSigSerializer(); foreach (var keyInfo in configuration.KeyInfos) { dsigSerializer.WriteKeyInfo(writer, keyInfo); } // </KeyDescriptor> writer.WriteEndElement(); }
/// <summary> /// Handles Signout /// </summary> /// <returns></returns> public async virtual Task SignOutAsync(AuthenticationProperties properties) { if (_configuration == null) { _configuration = await Options.ConfigurationManager.GetConfigurationAsync(Context.RequestAborted); } var wsFederationMessage = new WsFederationMessage() { IssuerAddress = _configuration.TokenEndpoint ?? string.Empty, Wtrealm = Options.Wtrealm, Wa = WsFederationConstants.WsFederationActions.SignOut, }; // Set Wreply in order: // 1. properties.Redirect // 2. Options.SignOutWreply // 3. Options.Wreply if (properties != null && !string.IsNullOrEmpty(properties.RedirectUri)) { wsFederationMessage.Wreply = properties.RedirectUri; } else if (!string.IsNullOrWhiteSpace(Options.SignOutWreply)) { wsFederationMessage.Wreply = Options.SignOutWreply; } else if (!string.IsNullOrWhiteSpace(Options.Wreply)) { wsFederationMessage.Wreply = Options.Wreply; } var redirectContext = new RedirectContext(Context, Scheme, Options, properties) { ProtocolMessage = wsFederationMessage }; await Options.Events.RedirectToIdentityProvider(redirectContext); if (!redirectContext.Handled) { string redirectUri = redirectContext.ProtocolMessage.CreateSignOutUrl(); if (!Uri.IsWellFormedUriString(redirectUri, UriKind.Absolute)) { Logger.LogWarning("The sign-out redirect URI is malformed: " + redirectUri); } Response.Redirect(redirectUri); } }
public ActionResult SignIn() { if (Request.IsAuthenticated) { // Redirect to home page if the user is already signed in. return RedirectToAction("Index", "Home"); } // Redirect to home page after signing in. WsFederationConfiguration config = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration; string callbackUrl = Url.Action("Index", "Home", routeValues: null, protocol: Request.Url.Scheme); SignInRequestMessage signInRequest = FederatedAuthentication.WSFederationAuthenticationModule.CreateSignInRequest( uniqueId: String.Empty, returnUrl: callbackUrl, rememberMeSet: false); signInRequest.SetParameter("wtrealm", IdentityConfig.Realm ?? config.Realm); return new RedirectResult(signInRequest.RequestUrl.ToString()); }
public async Task <WsFederationConfiguration> GenerateAsync(string wsfedEndpoint) { var signingKey = (await _keys.GetSigningCredentialsAsync()).Key as X509SecurityKey; var cert = signingKey.Certificate; var issuer = _contextAccessor.HttpContext.GetIdentityServerIssuerUri(); var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); var config = new WsFederationConfiguration() { Issuer = issuer, TokenEndpoint = wsfedEndpoint, SigningCredentials = signingCredentials, }; config.SigningKeys.Add(signingKey); config.KeyInfos.Add(new KeyInfo(cert)); return(config); }
protected void Page_Load(object sender, EventArgs e) { if (!Request.IsAuthenticated) { AuthenticateUser(); DisplayCalendar(); } else { DisplayCalendar(); } string tenantId = System.Security.Claims.ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; WsFederationConfiguration config = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration; string callbackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Response.ApplyAppPathModifier("~/"); string authUrl = string.Format("https://login.windows.net/{0}/adminconsent?client_id={1}&state={2}&redirect_uri={3}", tenantId, ConfigurationManager.AppSettings["ida:ClientId"], "12345", callbackUrl); authLink.NavigateUrl = authUrl; }
private static void WriteSecurityTokenServiceTypeRoleDescriptor(WsFederationConfiguration configuration, XmlWriter writer) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } // <RoleDescriptorr> writer.WriteStartElement(Elements.RoleDescriptor); writer.WriteAttributeString(IdentityServer4.WsFederation.WsFederationConstants.Xmlns, IdentityServer4.WsFederation.WsFederationConstants.Prefixes.Xsi, null, XmlSignatureConstants.XmlSchemaNamespace); writer.WriteAttributeString(IdentityServer4.WsFederation.WsFederationConstants.Xmlns, WsFederationConstants.PreferredPrefix, null, WsFederationConstants.Namespace); writer.WriteAttributeString(IdentityServer4.WsFederation.WsFederationConstants.Attributes.ProtocolSupportEnumeration, WsFederationConstants.Namespace); writer.WriteStartAttribute(Attributes.Type, XmlSignatureConstants.XmlSchemaNamespace); writer.WriteQualifiedName(Types.SecurityTokenServiceType, WsFederationConstants.Namespace); writer.WriteEndAttribute(); WriteKeyDescriptorForSigning(configuration, writer); //TODO: rewrite to not using static values, use values from config instead var supportedTokenTypeUris = new[] { "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1", "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" }; writer.WriteStartElement(IdentityServer4.WsFederation.WsFederationConstants.Attributes.TokenTypesOffered, WsFederationConstants.Namespace); foreach (string tokenTypeUri in supportedTokenTypeUris) { // <TokenType> writer.WriteStartElement(IdentityServer4.WsFederation.WsFederationConstants.Attributes.TokenType, WsFederationConstants.Namespace); writer.WriteAttributeString(IdentityServer4.WsFederation.WsFederationConstants.Attributes.Uri, tokenTypeUri); // </TokenType> writer.WriteEndElement(); } // </TokenTypesOffered> writer.WriteEndElement(); WriteSecurityTokenEndpoint(configuration, writer); WritePassiveRequestorEndpoint(configuration, writer); // </RoleDescriptorr> writer.WriteEndElement(); }
private static void WritePassiveRequestorEndpoint(WsFederationConfiguration configuration, XmlWriter writer) { // <PassiveRequestorEndpoint> writer.WriteStartElement(IdentityServer4.WsFederation.WsFederationConstants.Elements.PassiveRequestorEndpoint, WsFederationConstants.Namespace); // <EndpointReference> writer.WriteStartElement(WsAddressing.PreferredPrefix, WsAddressing.Elements.EndpointReference, WsAddressing.Namespace); // <Address> writer.WriteStartElement(WsAddressing.Elements.Address, WsAddressing.Namespace); writer.WriteString(configuration.TokenEndpoint); // </Address> writer.WriteEndElement(); // </EndpointReference> writer.WriteEndElement(); // </PassiveRequestorEndpoint> writer.WriteEndElement(); }
public ActionResult LogOff() { if (this.AuthenticationManager.User.Identity.AuthenticationType == "Federation") { WsFederationConfiguration config = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration; // Redirect to home page after signing out. string callbackUrl = Url.Action("Index", "Home", routeValues: null, protocol: Request.Url.Scheme); SignOutRequestMessage signoutMessage = new SignOutRequestMessage(new Uri(config.Issuer), callbackUrl); signoutMessage.SetParameter("wtrealm", IdentityConfig.Realm ?? config.Realm); FederatedAuthentication.SessionAuthenticationModule.SignOut(); return(new RedirectResult(signoutMessage.WriteQueryString())); } else { this.AuthenticationManager.SignOut(); return(this.RedirectToAction("Index", "Home")); } }
public async Task <string> GetMetadata(HttpContext context) { var configuration = new WsFederationConfiguration { Issuer = _options.IssuerUri, SigningCredentials = await _keys.GetSigningCredentialsAsync(), TokenEndpoint = context.GetIdentityServerOrigin() + "/wsfederation" }; //For whatever reason, the Digest method isn't specified in the builder extensions for identity server. //Not a good solution to force the user to use the overload that takes SigningCredentials //IdentityServer4/Configuration/DependencyInjection/BuilderExtensions/Crypto.cs //Instead, it should be supported in: // The overload that takes a X509Certificate2 // The overload that looks it up in a cert store // The overload that takes an RsaSecurityKey // AddDeveloperSigningCredential //For now, this is a workaround. if (configuration.SigningCredentials.Digest == null) { _logger.LogInformation($"SigningCredentials does not have a digest specified. Using default digest algorithm of {SecurityAlgorithms.Sha256Digest}"); configuration.SigningCredentials = new SigningCredentials(configuration.SigningCredentials.Key, configuration.SigningCredentials.Algorithm ?? SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); } configuration.KeyInfos.Add(new KeyInfo(configuration.SigningCredentials.Key)); var serializer = new WsFederationMetadataSerializer(); var sb = new StringBuilder(); var settings = new XmlWriterSettings { OmitXmlDeclaration = true }; using (var writer = XmlWriter.Create(sb, settings)) { serializer.WriteMetadata(writer, configuration); } var metadata = sb.ToString(); return(metadata); }
/// <summary> /// Generates the asynchronous. /// </summary> /// <param name="wsfedEndpoint">The wsfed endpoint.</param> /// <returns></returns> public async Task <WsFederationConfiguration> GenerateAsync(string wsfedEndpoint) { var credentials = await _keys.GetSigningCredentialsAsync().ConfigureAwait(false); var key = credentials.Key; var keyInfo = new KeyInfo(key.GetX509Certificate(_keys)); #if DUENDE var issuer = await _issuerNameService.GetCurrentAsync().ConfigureAwait(false); #else var issuer = _contextAccessor.HttpContext.GetIdentityServerIssuerUri(); #endif var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); var config = new WsFederationConfiguration() { Issuer = issuer, TokenEndpoint = wsfedEndpoint, SigningCredentials = signingCredentials, }; config.SigningKeys.Add(key); config.KeyInfos.Add(keyInfo); return(config); }
public async Task <ActionResult> ExternalLogin(string provider, string returnUrl) { // Request a redirect to the external this.login provider ClaimsIdentity identity = await this.AuthenticationManager.GetExternalIdentityAsync("Azure"); if (provider == "Azure" && identity != null) { return(this.RedirectToAction("ExternalLoginCallBack", "Account", new { loginProvider = "Azure", ReturnUrl = returnUrl })); } if (provider == "Azure") { WsFederationConfiguration config = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration; string callbackUrl = Url.Action("Index", "Home", routeValues: null, protocol: Request.Url.Scheme); SignInRequestMessage signInRequest = FederatedAuthentication.WSFederationAuthenticationModule.CreateSignInRequest( uniqueId: string.Empty, returnUrl: callbackUrl, rememberMeSet: false); signInRequest.SetParameter("wtrealm", IdentityConfig.Realm ?? config.Realm); return(new RedirectResult(signInRequest.RequestUrl)); } return(new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }))); }
protected override async Task ApplyResponseGrantAsync() { var options = Options as Saml2AuthenticationOptions; if (options == null) { return; } // handle sign-out response if (options.SingleLogoutServiceResponsePath.HasValue && options.SingleLogoutServiceResponsePath == (Request.PathBase + Request.Path)) { await ApplyResponseLogoutAsync(); return; } // handle sign-out request if (options.SingleLogoutServiceRequestPath.HasValue && options.SingleLogoutServiceRequestPath == (Request.PathBase + Request.Path)) { await ApplyRequestLogoutAsync(); return; } var signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode); if (signout == null) { return; } if (_configuration == null) { _configuration = await options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled); } // reusing the SingleSignOnService location from the configuration to determine the destination var issuer = options.Wtrealm; var destination = _configuration.TokenEndpoint ?? string.Empty; ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("issuer={0}", "destination={1}", issuer, destination)); var properties = signout.Properties; if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = options.SignOutWreply ?? GetCurrentUri(); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("RedirectUri={0}", properties.RedirectUri)); var state = new Dictionary <string, string> { { _relayStateWctx, Options.StateDataFormat.Protect(properties) } }; var binding = new Saml2RedirectBinding(); binding.SetRelayStateQuery(state); var redirectBinding = binding.Bind(new Saml2LogoutRequest { Issuer = new EndpointReference(issuer), Destination = new EndpointAddress(destination) }, options.SigningCertificate); var redirectLocation = redirectBinding.RedirectLocation.AbsoluteUri; if (!Uri.IsWellFormedUriString(redirectLocation, UriKind.Absolute)) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("The sign-out redirect URI is malformed: {0}", redirectLocation)); } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("redirectLocation={0}", redirectLocation)); Response.Redirect(redirectLocation); }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { var options = Options as Saml2AuthenticationOptions; if (options == null) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, "AuthenticateCoreAsync:options == null"); return(null); } if (options.CallbackPath.HasValue && options.CallbackPath != (Request.PathBase + Request.Path)) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format( "AuthenticateCoreAsync:options.CallbackPath.HasValue && options.CallbackPath != (Request.PathBase: {0} + Request.Path: {1})", Request.PathBase, Request.Path)); return(null); } if (_configuration == null) { _configuration = await options.ConfigurationManager.GetConfigurationAsync(Context.Request.CallCancelled); } if (string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(Request.ContentType) && Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && Request.Body.CanRead) { var request = GetHttpRequestBase(); var signingKeys = _configuration.SigningKeys.OfType <X509SecurityKey>().ToList(); var totalKeys = signingKeys.Count; var keyIndex = 0; foreach (var signingKey in signingKeys) { keyIndex++; var binding = new Saml2PostBinding(); Saml2AuthnResponse response = null; try { response = binding.Unbind(request, GetSaml2AuthnResponse(options), signingKey.Certificate) as Saml2AuthnResponse; } catch (Saml2ResponseException saml2ResponseException) { WebEventSource.Log.GenericWarningException(saml2ResponseException); } if (response == null || response.Status != Saml2StatusCodes.Success) { continue; } ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Received the response for signing key with index:{0} out of:{1}", keyIndex, totalKeys)); var relayState = binding.GetRelayStateQuery(); var properties = relayState.ContainsKey(_relayStateWctx) ? Options.StateDataFormat.Unprotect(relayState[_relayStateWctx]) ?? new AuthenticationProperties() : new AuthenticationProperties(); if (string.IsNullOrWhiteSpace(properties.RedirectUri)) { properties.RedirectUri = GetRedirectUri(binding, options); } var claimsIdentity = new ClaimsIdentity(response.ClaimsIdentity.Claims, options.TokenValidationParameters.AuthenticationType, response.ClaimsIdentity.NameClaimType, response.ClaimsIdentity.RoleClaimType); var ticket = new AuthenticationTicket(claimsIdentity, properties); ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Identity={0}", ticket.Identity.Name)); ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("RedirectUri={0}", ticket.Properties.RedirectUri)); if (options.UseTokenLifetime) { var issued = response.Saml2SecurityToken.ValidFrom; if (issued != DateTime.MinValue) { ticket.Properties.IssuedUtc = issued.ToUniversalTime(); } var expires = response.Saml2SecurityToken.ValidTo; if (expires != DateTime.MinValue) { ticket.Properties.ExpiresUtc = expires.ToUniversalTime(); } ticket.Properties.AllowRefresh = false; } return(ticket); } ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("No response received for any signing keys. totalKeys found:{0}", totalKeys)); } return(null); }
private void SetupFederatedLogin() { FederatedAuthentication.FederationConfigurationCreated += (sender, args) => { var config = Kernel.Get<IConfigurationService>(); var idconfig = new IdentityConfiguration(); idconfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(config.Auth.AudienceUrl)); var registry = new ConfigurationBasedIssuerNameRegistry(); registry.AddTrustedIssuer(config.Auth.TokenCertificateThumbprint, config.Auth.AuthenticationIssuer); idconfig.IssuerNameRegistry = registry; idconfig.CertificateValidationMode = X509CertificateValidationMode.None; var sessionTransforms = new List<CookieTransform>() { new DeflateCookieTransform(), new MachineKeyTransform() }; idconfig.SecurityTokenHandlers.AddOrReplace(new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly())); var wsfedconfig = new WsFederationConfiguration(config.Auth.AuthenticationIssuer, config.Auth.AuthenticationRealm); wsfedconfig.PersistentCookiesOnPassiveRedirects = true; args.FederationConfiguration.IdentityConfiguration = idconfig; args.FederationConfiguration.WsFederationConfiguration = wsfedconfig; args.FederationConfiguration.CookieHandler = new ChunkedCookieHandler(); }; }