public IActionResult Login(string returnUrl = null, LoginType?loginType = null) { var binding = new Saml2RedirectBinding(); binding.SetRelayStateQuery(new Dictionary <string, string> { { relayStateReturnUrl, returnUrl ?? Url.Content("~/") }, { relayStateLoginType, loginType.HasValue ? loginType.Value.ToString() : LoginType.FoxIDsLogin.ToString() } }); var saml2AuthnRequest = new Saml2AuthnRequest(saml2Config) { //ForceAuthn = true, //NameIdPolicy = new NameIdPolicy { AllowCreate = true, Format = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" }, //RequestedAuthnContext = new RequestedAuthnContext //{ // Comparison = AuthnContextComparisonTypes.Exact, // AuthnContextClassRef = new string[] { AuthnContextClassTypes.PasswordProtectedTransport.OriginalString }, //}, }; saml2AuthnRequest.Destination = AddUpParty(saml2AuthnRequest.Destination, loginType.HasValue ? loginType.Value : LoginType.FoxIDsLogin); return(binding.Bind(saml2AuthnRequest).ToActionResult()); }
public ActionResult Claims(string returnUrl) { if (Request.IsAuthenticated) { return(View()); } // Generate the SAML 2 Authentication Request var binding = new Saml2RedirectBinding(); binding.SetRelayStateQuery(new Dictionary <string, string> { { relayStateReturnUrl, returnUrl } }); var authRequest = new Saml2AuthnRequest { //ForceAuthn = true, //NameIdPolicy = new NameIdPolicy { AllowCreate = true, Format = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" }, RequestedAuthnContext = new RequestedAuthnContext { Comparison = AuthnContextComparisonTypes.Exact, AuthnContextClassRef = new string[] { AuthnContextClassTypes.PasswordProtectedTransport.OriginalString }, }, Issuer = new EndpointReference(Configuration.ISSUER), Destination = new EndpointAddress(Configuration.CFS_ENDPOINT), AssertionConsumerServiceUrl = new EndpointAddress(Configuration.ISSUER + "/Home/AssertionConsumerService") }; return(binding.Bind(authRequest).ToActionResult()); }
public string BuildAuthnRequestUrl(Saml2AuthnRequest saml2AuthnRequest, AsymmetricAlgorithm signingKey, string hashingAlgorithm, string relayState) { var request = saml2AuthnRequest.GetXml().OuterXml; return(BuildRequestUrl(signingKey, hashingAlgorithm, relayState, request, saml2AuthnRequest.Destination)); }
private IActionResult ComputeRequest(App app) { var saml2AuthnRequest = new Saml2AuthnRequest(_samlConfig); var requestBinding = new Saml2RedirectBinding(); if (AccessControl(app)) { try { requestBinding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnRequest); var sessionIndex = Guid.NewGuid().ToString(); return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Success, requestBinding.RelayState, app, sessionIndex, User.Claims)); } catch (Exception ex) { #if DEBUG Debug.WriteLine($"Saml 2.0 Authn Request error: {ex.ToString()}\nSaml Auth Request: '{saml2AuthnRequest.XmlDocument?.OuterXml}'\nQuery String: {Request.QueryString}"); Debug.WriteLine(ex.StackTrace); #endif return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Responder, requestBinding.RelayState, app)); } } else { return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.RequestDenied, requestBinding.RelayState, app)); } }
public ActionResult Login() { var requestBinding = new Saml2RedirectBinding(); var relyingParty = ValidateRelyingParty(ReadRelyingPartyFromLoginRequest(requestBinding)); var saml2AuthnRequest = new Saml2AuthnRequest(config); try { requestBinding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnRequest); // **** Handle user login e.g. in GUI **** // Test user with session index and claims var sessionIndex = Guid.NewGuid().ToString(); var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, User.Identity.Name), new Claim(ClaimTypes.Name, User.Identity.Name), new Claim(ClaimTypes.Email, User.Identity.Name), new Claim("tenancyName", "docketManager"), new Claim("userRole", "admin"), new Claim("userId", User.Identity.GetUserId()), }; return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Success, requestBinding.RelayState, relyingParty, sessionIndex, claims)); } catch (Exception exc) { #if DEBUG Console.WriteLine($"Saml 2.0 Authn Request error: {exc.ToString()}\nSaml Auth Request: '{saml2AuthnRequest.XmlDocument?.OuterXml}'\nQuery String: {Request.QueryString}"); #endif return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Responder, requestBinding.RelayState, relyingParty)); } }
private LoginRequest GetLoginRequestAsync(SamlDownParty party, Saml2AuthnRequest saml2AuthnRequest) { var loginRequest = new LoginRequest { DownPartyLink = new DownPartySessionLink { SupportSingleLogout = !string.IsNullOrWhiteSpace(party.SingleLogoutUrl), Id = party.Id, Type = party.Type } }; if (saml2AuthnRequest.ForceAuthn.HasValue && saml2AuthnRequest.ForceAuthn.Value) { loginRequest.LoginAction = LoginAction.RequireLogin; } else if (saml2AuthnRequest.IsPassive.HasValue && saml2AuthnRequest.IsPassive.Value) { loginRequest.LoginAction = LoginAction.ReadSession; } else { loginRequest.LoginAction = LoginAction.ReadSessionOrLogin; } if (saml2AuthnRequest.RequestedAuthnContext?.AuthnContextClassRef?.Count() > 0) { loginRequest.Acr = saml2AuthnRequest.RequestedAuthnContext?.AuthnContextClassRef; } return(loginRequest); }
public IActionResult Login() { var requestBinding = new Saml2RedirectBinding(); var relyingParty = ValidateRelyingParty(ReadRelyingPartyFromLoginRequest(requestBinding)); var saml2AuthnRequest = new Saml2AuthnRequest(config); try { requestBinding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnRequest); // **** Handle user login e.g. in GUI **** // Test user with session index and claims var sessionIndex = Guid.NewGuid().ToString(); var claims = CreateTestUserClaims(saml2AuthnRequest.Subject?.NameID?.ID); return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Success, requestBinding.RelayState, relyingParty, sessionIndex, claims)); } catch (Exception exc) { #if DEBUG Debug.WriteLine($"Saml 2.0 Authn Request error: {exc.ToString()}\nSaml Auth Request: '{saml2AuthnRequest.XmlDocument?.OuterXml}'\nQuery String: {Request.QueryString}"); #endif return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Responder, requestBinding.RelayState, relyingParty)); } }
private ActionResult LoginResponse(Saml2AuthnRequest saml2AuthnRequest, Saml2StatusCodes status, string relayState, RelyingParty relyingParty, string sessionIndex = null, IEnumerable <Claim> claims = null) { var responsebinding = new Saml2RedirectBinding(); responsebinding.RelayState = relayState; var saml2AuthnResponse = new Saml2AuthnResponse(config) { InResponseTo = saml2AuthnRequest.Id, Status = status, Destination = relyingParty.SingleSignOnDestination, Extensions = saml2AuthnRequest.Extensions }; if (status == Saml2StatusCodes.Success && claims != null) { saml2AuthnResponse.SessionIndex = sessionIndex; var claimsIdentity = new ClaimsIdentity(claims); saml2AuthnResponse.NameId = new Saml2NameIdentifier(claimsIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).Select(c => c.Value).Single(), NameIdentifierFormats.Persistent); saml2AuthnResponse.ClaimsIdentity = claimsIdentity; var token = saml2AuthnResponse.CreateSecurityToken(SettingManager.GetInstance().Configuration.Issuer); } return(responsebinding.Bind(saml2AuthnResponse).ToActionResult()); }
private string GetAcsUrl(SamlDownParty party, Saml2AuthnRequest saml2AuthnRequest) { if (saml2AuthnRequest.AssertionConsumerServiceUrl != null) { return(saml2AuthnRequest.AssertionConsumerServiceUrl.OriginalString); } else { return(party.AcsUrls.First()); } }
public Saml2AuthnRequest CreateAuthnRequest(string providerName, string authnRequestId, string assertionConsumerServiceUrl) { var identityProviderConfiguration = _configurationProvider.GetIdentityProviderConfiguration(providerName); var request = new Saml2AuthnRequest { ID = authnRequestId, Issuer = ServiceProviderConfiguration.EntityId, ForceAuthn = identityProviderConfiguration.ForceAuth, IsPassive = identityProviderConfiguration.IsPassive, Destination = identityProviderConfiguration.SingleSignOnService, IssuerFormat = identityProviderConfiguration.IssuerFormat, IssueInstant = DateTime.UtcNow, ProtocolBinding = identityProviderConfiguration.ProtocolBinding }; request.Request.AssertionConsumerServiceURL = assertionConsumerServiceUrl; var audienceRestrictions = new List <ConditionAbstract>(1); var audienceRestriction = new AudienceRestriction { Audience = new List <string>(1) { ServiceProviderConfiguration.EntityId } }; audienceRestrictions.Add(audienceRestriction); request.Request.Conditions = new Conditions { Items = audienceRestrictions }; if (identityProviderConfiguration.AllowCreate.HasValue && identityProviderConfiguration.NameIdPolicyFormat.IsNotNullOrEmpty()) { request.Request.NameIDPolicy = new NameIDPolicy { AllowCreate = identityProviderConfiguration.AllowCreate, Format = identityProviderConfiguration.NameIdPolicyFormat }; } if (identityProviderConfiguration.AuthnContextComparisonType.IsNotNullOrEmpty()) { request.Request.RequestedAuthnContext = new RequestedAuthnContext { Comparison = (AuthnContextComparisonType)Enum.Parse(typeof(AuthnContextComparisonType), identityProviderConfiguration.AuthnContextComparisonType), ComparisonSpecified = true, Items = identityProviderConfiguration.AuthnContextComparisonItems }; } return(request); }
private async Task <IActionResult> AuthnRequestAsync <T>(SamlDownParty party, Saml2Binding <T> binding) { var samlConfig = saml2ConfigurationLogic.GetSamlDownConfig(party); var request = HttpContext.Request; var saml2AuthnRequest = new Saml2AuthnRequest(samlConfig); binding.ReadSamlRequest(request.ToGenericHttpRequest(), saml2AuthnRequest); logger.ScopeTrace($"SAML Authn request '{saml2AuthnRequest.XmlDocument.OuterXml}'."); try { ValidateAuthnRequest(party, saml2AuthnRequest); binding.Unbind(request.ToGenericHttpRequest(), saml2AuthnRequest); logger.ScopeTrace("Down, SAML Auth request accepted.", triggerEvent: true); var responseUrl = GetAcsUrl(party, saml2AuthnRequest); await sequenceLogic.SaveSequenceDataAsync(new SamlDownSequenceData { Id = saml2AuthnRequest.Id.Value, RelayState = binding.RelayState, ResponseUrl = responseUrl, }); await formActionLogic.CreateFormActionByUrlAsync(responseUrl); var type = RouteBinding.ToUpParties.First().Type; logger.ScopeTrace($"Request, Up type '{type}'."); switch (type) { case PartyTypes.Login: return(await serviceProvider.GetService <LoginUpLogic>().LoginRedirectAsync(RouteBinding.ToUpParties.First(), GetLoginRequestAsync(party, saml2AuthnRequest))); case PartyTypes.OAuth2: throw new NotImplementedException(); case PartyTypes.Oidc: return(await serviceProvider.GetService <OidcAuthUpLogic <OidcDownParty, OidcDownClient, OidcDownScope, OidcDownClaim> >().AuthenticationRequestAsync(RouteBinding.ToUpParties.First())); case PartyTypes.Saml2: return(await serviceProvider.GetService <SamlAuthnUpLogic>().AuthnRequestAsync(RouteBinding.ToUpParties.First(), GetLoginRequestAsync(party, saml2AuthnRequest))); default: throw new NotSupportedException($"Party type '{type}' not supported."); } } catch (SamlRequestException ex) { logger.Error(ex); return(await AuthnResponseAsync(party.Id, samlConfig, saml2AuthnRequest.Id.Value, binding.RelayState, GetAcsUrl(party, saml2AuthnRequest), party.AuthnBinding.ResponseBinding, ex.Status)); } }
private async Task <IActionResult> AuthnRequestAsync <T>(SamlUpParty party, Saml2Binding <T> binding, SamlUpSequenceData samlUpSequenceData) { var samlConfig = await saml2ConfigurationLogic.GetSamlUpConfigAsync(party, includeSigningAndDecryptionCertificate : true); binding.RelayState = await sequenceLogic.CreateExternalSequenceIdAsync(); var saml2AuthnRequest = new Saml2AuthnRequest(samlConfig); switch (samlUpSequenceData.LoginAction) { case LoginAction.ReadSession: saml2AuthnRequest.IsPassive = true; break; case LoginAction.RequireLogin: saml2AuthnRequest.ForceAuthn = true; break; default: break; } if (party.AuthnContextClassReferences?.Count() > 0) { saml2AuthnRequest.RequestedAuthnContext = new RequestedAuthnContext { Comparison = party.AuthnContextComparison.HasValue ? (AuthnContextComparisonTypes)Enum.Parse(typeof(AuthnContextComparisonTypes), party.AuthnContextComparison.Value.ToString()) : null, AuthnContextClassRef = party.AuthnContextClassReferences, }; } binding.Bind(saml2AuthnRequest); logger.ScopeTrace(() => $"SAML Authn request '{saml2AuthnRequest.XmlDocument.OuterXml}'.", traceType: TraceTypes.Message); logger.ScopeTrace(() => $"Authn URL '{samlConfig.SingleSignOnDestination?.OriginalString}'."); logger.ScopeTrace(() => "Up, Sending SAML Authn request.", triggerEvent: true); securityHeaderLogic.AddFormActionAllowAll(); if (binding is Saml2Binding <Saml2RedirectBinding> ) { return(await(binding as Saml2RedirectBinding).ToActionFormResultAsync()); } else if (binding is Saml2Binding <Saml2PostBinding> ) { return(await(binding as Saml2PostBinding).ToActionFormResultAsync()); } else { throw new NotSupportedException(); } }
public IActionResult LogIn(string returnUrl) { var binding = new Saml2RedirectBinding(); var relayState = new Dictionary <string, string> { { ReturnUrlRelayStateKey, returnUrl ?? Url.Action("Index", "Home") } }; binding.SetRelayStateQuery(relayState); var request = new Saml2AuthnRequest(_configuration); return(binding.Bind(request) .ToActionResult()); }
public string BuildAuthnRequestUrl(Saml2AuthnRequest saml2AuthnRequest, AsymmetricAlgorithm signingKey, string hashingAlgorithm, string relayState) { System.Console.WriteLine(""); System.Console.WriteLine("[HttpRedirectBinding][BuildAuthnRequestUrl] => saml2AuthnRequest: " + saml2AuthnRequest); System.Console.WriteLine("[HttpRedirectBinding][BuildAuthnRequestUrl] => hashingAlgorithm: " + hashingAlgorithm); System.Console.WriteLine("[HttpRedirectBinding][BuildAuthnRequestUrl] => relayState: " + relayState); var request = saml2AuthnRequest.GetXml().OuterXml; System.Console.WriteLine(""); System.Console.WriteLine("[HttpRedirectBinding][BuildAuthnRequestUrl] => request: " + request); System.Console.WriteLine(""); return(BuildRequestUrl(signingKey, hashingAlgorithm, relayState, request, saml2AuthnRequest.Destination)); }
public ValueTask <IdentityHttpResponse> Login(string state) { var id = SamlIDManager.Generate(serviceProvider); var requestDocument = new Saml2AuthnRequest( id: id, issuer: serviceProvider, assertionConsumerServiceURL: redirectUrl, bindingType: BindingType.Form ); var requestBinding = Saml2Binding.GetBindingForDocument(requestDocument, BindingType.Form, XmlSignatureAlgorithmType.RsaSha256, null, null); requestBinding.Sign(serviceProviderCert, requiredSignature); var response = requestBinding.GetResponse(loginUrl); return(new ValueTask <IdentityHttpResponse>(response)); }
/// <summary> /// Creates a saml authentication request /// </summary> /// <param name="authnRequest">contains the authentication request properties</param> /// <param name="signAlgorithm">algorithm to sign the saml request</param> /// <returns>signed saml request</returns> public string CreateSamlAuthnRequest(Saml2AuthnRequest authnRequest, Cryptography.SigningAlgorithm signAlgorithm = Cryptography.SigningAlgorithm.SHA1withRSA) { if (!initialized) { throw new SamlCommunicationException("Init must be called first", SamlCommunicationType.SAMLCOMMUNICATION); } // load signing certificate X509Certificate2 signingCertificate = certificate; // LoadCertificate(); // set creation time TimeZone localZone = TimeZone.CurrentTimeZone; authnRequest.IssueInstant = localZone.ToUniversalTime(DateTime.Now); // make id -> hash the authn request make it unique byte[] hash = crypto.Hash(authnRequest.ToXML(), Cryptography.HashTypes.SHA256); authnRequest.ID = Convert.ToBase64String(hash); // set signing algorithm string signingAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; if (signAlgorithm == Cryptography.SigningAlgorithm.SHA256withRSA) { signingAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; // TODO correct algorithm } string original; string deflated = serializer.Deflate(authnRequest.ToXML(), out original); // todo store authn request in storage! archiver.SetObjectToArchive(authnRequest.ID, Convert.ToBase64String(Encoding.UTF8.GetBytes(authnRequest.ToXML()))); // SAMLResponse=value&RelayState=value&SigAlg=value string toSign = "SAMLRequest=" + WebUtility.UrlEncode(deflated) // HttpUtility if in Webproject + "&RelayState=" + WebUtility.UrlEncode(authnRequest.ID) + "&SigAlg=" + WebUtility.UrlEncode(signingAlgorithm); string signature = crypto.SignString(toSign, signingCertificate, signAlgorithm); string request = authnRequest.Destination + "?" + toSign + "&Signature=" + WebUtility.UrlEncode(signature); LogService.Log(LogService.LogType.Info, "CreateSamlAuthnRequest - authnRequest created: '" + request + "'"); return(request); }
public void CreateAuthnRequstTest() { string xmlString = ReadFile(xmlFilename); Saml2Serializer saml = new Saml2Serializer(); Cryptography crypto = new Cryptography(); Saml2AuthnRequest authn = new Saml2AuthnRequest(); AuthnRequest authnRequest = saml.ConvertXMLToAuthnRequestObject(xmlString); authn.AssertionConsumerServiceURL = authnRequest.AssertionConsumerServiceURL; authn.AttributeConsumingServiceIndex = authnRequest.AttributeConsumingServiceIndex; authn.Destination = authnRequest.Destination; authn.ForceAuthn = authnRequest.ForceAuthn; authn.Issuer = authnRequest.Issuer; authn.ProviderName = "HybridIssuer"; TimeZone localZone = TimeZone.CurrentTimeZone; authn.IssueInstant = localZone.ToUniversalTime(DateTime.Now); authn.ID = "65464-6546-6454889-3313"; string original; string zipped = saml.Deflate(authn.ToXML(), out original); string sigAlg = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; // SAMLResponse=value&RelayState=value&SigAlg=value string toSign = "SAMLRequest=" + HttpUtility.UrlEncode(zipped, Encoding.UTF8) + "&RelayState=" + HttpUtility.UrlEncode("34bad366-f60b-4491-a462-230ea22423ad", Encoding.UTF8) + "&SigAlg=" + HttpUtility.UrlEncode(sigAlg, Encoding.UTF8); //byte[] sig = saml.SignXML(xmlString); //string signature = Convert.ToBase64String(sig); string keystorePath = AppDomain.CurrentDomain.BaseDirectory + "\\Keys\\hybridissuer.pfx"; string keystorePassword = "******"; string friendlyName = "hybridissuer"; SamlCertificateController certController = new SamlCertificateController(); X509Certificate2 cert = certController.GetCertificate(friendlyName, keystorePath, keystorePassword); string signature = crypto.SignString(toSign, cert, Cryptography.SigningAlgorithm.SHA1withRSA); string request = authnRequest.Destination + "?" + toSign + "&Signature=" + HttpUtility.UrlEncode(signature, Encoding.UTF8); }
private LoginRequest GetLoginRequestAsync(Saml2AuthnRequest saml2AuthnRequest) { var loginRequest = new LoginRequest(); if (saml2AuthnRequest.ForceAuthn.HasValue && saml2AuthnRequest.ForceAuthn.Value) { loginRequest.LoginAction = LoginAction.RequereLogin; } else if (saml2AuthnRequest.IsPassive.HasValue && saml2AuthnRequest.IsPassive.Value) { loginRequest.LoginAction = LoginAction.ReadSession; } else { loginRequest.LoginAction = LoginAction.ReadSessionOrLogin; } return(loginRequest); }
private async Task <IActionResult> AuthnRequestAsync <T>(SamlUpParty party, Saml2Binding <T> binding, SamlUpSequenceData samlUpSequenceData) { var samlConfig = saml2ConfigurationLogic.GetSamlUpConfig(party); binding.RelayState = SequenceString; var saml2AuthnRequest = new Saml2AuthnRequest(samlConfig); switch (samlUpSequenceData.LoginAction) { case LoginAction.ReadSession: saml2AuthnRequest.IsPassive = true; break; case LoginAction.RequireLogin: saml2AuthnRequest.ForceAuthn = true; break; default: break; } binding.Bind(saml2AuthnRequest); logger.ScopeTrace($"SAML Authn request '{saml2AuthnRequest.XmlDocument.OuterXml}'."); logger.ScopeTrace($"Authn URL '{samlConfig.SingleSignOnDestination?.OriginalString}'."); logger.ScopeTrace("Up, Sending SAML Authn request.", triggerEvent: true); securityHeaderLogic.AddFormActionAllowAll(); if (binding is Saml2Binding <Saml2RedirectBinding> ) { return(await(binding as Saml2RedirectBinding).ToActionFormResultAsync()); } else if (binding is Saml2Binding <Saml2PostBinding> ) { return(await(binding as Saml2PostBinding).ToActionFormResultAsync()); } else { throw new NotSupportedException(); } }
private void ValidateAuthnRequest(SamlDownParty party, Saml2AuthnRequest saml2AuthnRequest) { if (saml2AuthnRequest.AssertionConsumerServiceUrl != null && !party.AcsUrls.Any(u => u.Equals(saml2AuthnRequest.AssertionConsumerServiceUrl.OriginalString, StringComparison.InvariantCultureIgnoreCase))) { throw new EndpointException($"Invalid assertion consumer service url '{saml2AuthnRequest.AssertionConsumerServiceUrl.OriginalString}'.") { RouteBinding = RouteBinding }; } var requestIssuer = saml2AuthnRequest.Issuer; logger.SetScopeProperty("Issuer", requestIssuer); if (!party.Issuer.Equals(requestIssuer)) { throw new SamlRequestException($"Invalid issuer '{requestIssuer}'.") { RouteBinding = RouteBinding, Status = Saml2StatusCodes.Responder }; } }
/// <summary> /// Creates a saml authentication request with the given authentication request properties /// </summary> /// <param name="assertionConsumerServiceURL"></param> /// <param name="attributeConsumingServiceIndex"></param> /// <param name="destination"></param> /// <param name="forceAuthn"></param> /// <param name="providerName"></param> /// <param name="issuer"></param> /// <param name="signAlgorithm"></param> /// <returns>signed saml request</returns> public string CreateSamlAuthnRequest(string assertionConsumerServiceURL, int attributeConsumingServiceIndex, string destination, bool forceAuthn, string providerName, string issuer, Cryptography.SigningAlgorithm signAlgorithm = Cryptography.SigningAlgorithm.SHA1withRSA) { LogService.Log(LogService.LogType.Info, "CreateSamlAuthnRequest called"); if (!initialized) { throw new SamlCommunicationException("Init must be called first", SamlCommunicationType.SAMLCOMMUNICATION); } Saml2AuthnRequest authnRequest = new Saml2AuthnRequest() { AssertionConsumerServiceURL = assertionConsumerServiceURL, AttributeConsumingServiceIndex = attributeConsumingServiceIndex, Destination = destination, ForceAuthn = forceAuthn, ProviderName = providerName, Issuer = issuer }; LogService.Log(LogService.LogType.Info, "CreateSamlAuthnRequest authnRequest properties set - '" + authnRequest.ToString() + "'"); return(CreateSamlAuthnRequest(authnRequest, signAlgorithm)); }
public async Task <IActionResult> Login() { var requestBinding = new Saml2RedirectBinding(); var relyingParty = ValidateRelyingParty(ReadRelyingPartyFromLoginRequest(requestBinding)); var saml2AuthnRequest = new Saml2AuthnRequest(saml2Config); try { requestBinding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnRequest); // **** Handle user login e.g. in GUI **** // Test user with session index and claims var session = await idPSessionCookieRepository.GetAsync(); if (session == null) { session = new IdPSession { RelyingPartyIssuer = relyingParty.Issuer, NameIdentifier = "12345", Upn = "*****@*****.**", Email = "*****@*****.**", SessionIndex = Guid.NewGuid().ToString() }; await idPSessionCookieRepository.SaveAsync(session); } var claims = CreateClaims(session); return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Success, requestBinding.RelayState, relyingParty, session.SessionIndex, claims)); } catch (Exception ex) { logger.LogWarning(ex, $"SAML 2.0 Authn Request error. Authn Request '{saml2AuthnRequest.XmlDocument?.OuterXml}', Query String '{Request.QueryString}'."); return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Responder, requestBinding.RelayState, relyingParty)); } }
public ActionResult Redirect() { var requestBinding = new Saml2RedirectBinding(); var relyingParty = ValidateRelyingParty(ReadRelyingPartyFromLoginRequest(requestBinding)); var saml2AuthnRequest = new Saml2AuthnRequest(config.IDP); try { requestBinding.Unbind(Request.ToGenericHttpRequest(), saml2AuthnRequest); // **** Handle user login e.g. in GUI **** // Test user with session index and claims var sessionIndex = Guid.NewGuid().ToString(); var claims = GetClaimsFromCertificate(this.Request.ClientCertificate); return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Success, requestBinding.RelayState, relyingParty, sessionIndex, claims)); } catch (Exception exc) { return(LoginResponse(saml2AuthnRequest.Id, Saml2StatusCodes.Responder, requestBinding.RelayState, relyingParty)); } }
private async Task <IActionResult> AuthnRequestAsync <T>(SamlDownParty party, Saml2Binding <T> binding) { var samlConfig = await saml2ConfigurationLogic.GetSamlDownConfigAsync(party); var request = HttpContext.Request; var saml2AuthnRequest = new Saml2AuthnRequest(samlConfig); binding.ReadSamlRequest(request.ToGenericHttpRequest(), saml2AuthnRequest); logger.ScopeTrace(() => $"SAML Authn request '{saml2AuthnRequest.XmlDocument.OuterXml}'.", traceType: TraceTypes.Message); try { ValidateAuthnRequest(party, saml2AuthnRequest); try { binding.Unbind(request.ToGenericHttpRequest(), saml2AuthnRequest); logger.ScopeTrace(() => "Down, SAML Authn request accepted.", triggerEvent: true); } catch (Exception ex) { var isex = saml2ConfigurationLogic.GetInvalidSignatureValidationCertificateException(samlConfig, ex); if (isex != null) { throw isex; } throw; } await sequenceLogic.SaveSequenceDataAsync(new SamlDownSequenceData { Id = saml2AuthnRequest.Id.Value, RelayState = binding.RelayState, AcsResponseUrl = GetAcsUrl(party, saml2AuthnRequest), }); var type = RouteBinding.ToUpParties.First().Type; logger.ScopeTrace(() => $"Request, Up type '{type}'."); switch (type) { case PartyTypes.Login: return(await serviceProvider.GetService <LoginUpLogic>().LoginRedirectAsync(RouteBinding.ToUpParties.First(), GetLoginRequestAsync(party, saml2AuthnRequest))); case PartyTypes.OAuth2: throw new NotImplementedException(); case PartyTypes.Oidc: return(await serviceProvider.GetService <OidcAuthUpLogic <OidcUpParty, OidcUpClient> >().AuthenticationRequestRedirectAsync(RouteBinding.ToUpParties.First(), GetLoginRequestAsync(party, saml2AuthnRequest))); case PartyTypes.Saml2: return(await serviceProvider.GetService <SamlAuthnUpLogic>().AuthnRequestRedirectAsync(RouteBinding.ToUpParties.First(), GetLoginRequestAsync(party, saml2AuthnRequest))); default: throw new NotSupportedException($"Party type '{type}' not supported."); } } catch (SamlRequestException ex) { logger.Error(ex); return(await AuthnResponseAsync(party, samlConfig, saml2AuthnRequest.Id.Value, binding.RelayState, GetAcsUrl(party, saml2AuthnRequest), ex.Status)); } }
public string BuildAuthnRequestUrl(string providerName, Saml2AuthnRequest saml2AuthnRequest, string relayState) { var request = saml2AuthnRequest.GetXml().OuterXml; return(BuildRequestUrl(providerName, relayState, request, saml2AuthnRequest.Destination)); }