private string GetContextFromRequest() { Uri requestBaseUrl = WSFederationMessage.GetBaseUrl(this.Request.Url); var message = WSFederationMessage.CreateFromNameValueCollection(requestBaseUrl, this.Request.Form); return(message != null ? message.Context : string.Empty); }
public ActionResult Return() { if (!Thread.CurrentPrincipal.Identity.IsAuthenticated) { return(RedirectToAction("Index")); } var formData = ControllerContext.HttpContext.Request.Unvalidated.Form; string contextQuery = null; if (formData["wresult"] != null) { var baseUrl = FederationMessage.GetBaseUrl(ControllerContext.HttpContext.Request.Url); var signInResponseMessage = WSFederationMessage.CreateFromNameValueCollection(baseUrl, formData) as SignInResponseMessage; if (signInResponseMessage != null) { contextQuery = signInResponseMessage.Context; } } var returnUrl = GetReturnUrl(contextQuery); return(Redirect(string.IsNullOrWhiteSpace(returnUrl) ? "~/" : returnUrl)); }
public ActionResult LogOn(FormCollection forms) { using (new Service.PerformanceMonitor()) { var newUser = this.Register(User.Identity); var message = WSFederationMessage.CreateFromNameValueCollection(new Uri("http://www.notused.com"), forms); var returnUrl = message != null ? message.Context : null; if (string.IsNullOrWhiteSpace(returnUrl)) { if (newUser) { //return RedirectToAction("Details", "Apps", new { appId = Guid.Empty }); return(RedirectToAction("Profile", "Account")); } else { return(RedirectToAction("Index", "Home")); } } else { return(Redirect(returnUrl)); } } }
private string GetContextFromRequest() { Uri requestBaseUrl = WSFederationMessage.GetBaseUrl(this.Request.Url); WSFederationMessage message = WSFederationMessage.CreateFromNameValueCollection(requestBaseUrl, this.Request.Form); return(message != null && message.Context != null?Uri.UnescapeDataString(message.Context) : string.Empty); }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { if (!string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { return(null); } var form = await Request.ReadFormAsync(); var nameValueForm = ConvertToNameValueCollection(form); WSFederationMessage message = WSFederationMessage.CreateFromNameValueCollection( new Uri(_federationConfiguration.WsFederationConfiguration.Realm), nameValueForm); var signIn = message as SignInResponseMessage; if (signIn == null) { return(null); } var extra = Options.StateDataFormat.Unprotect(message.Context); if (extra == null) { return(null); } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(extra, _logger)) { return(new AuthenticationTicket(null, extra)); } XmlDictionaryReader xmlReader = XmlDictionaryReader.CreateTextReader(Encoding.UTF8.GetBytes(signIn.Result), XmlDictionaryReaderQuotas.Max); var federationSerializer = new WSFederationSerializer(xmlReader); var serializationContext = new WSTrustSerializationContext(_federationConfiguration.IdentityConfiguration.SecurityTokenHandlerCollectionManager); RequestSecurityTokenResponse securityTokenResponse = federationSerializer.CreateResponse(signIn, serializationContext); string xml = securityTokenResponse.RequestedSecurityToken.SecurityTokenXml.OuterXml; SecurityToken securityToken = ReadToken(xml); var securityTokenReceivedContext = new SecurityTokenReceivedContext(securityToken); await Options.Provider.SecurityTokenReceived(securityTokenReceivedContext); ClaimsPrincipal principal = AuthenticateToken(securityToken, Request.Uri.AbsoluteUri); var securityTokenValidatedContext = new SecurityTokenValidatedContext(principal); await Options.Provider.SecurityTokenValidated(securityTokenValidatedContext); return(new AuthenticationTicket( securityTokenValidatedContext.ClaimsPrincipal.Identities.FirstOrDefault(), extra)); }
// See http://social.technet.microsoft.com/wiki/contents/articles/1725.windows-identity-foundation-wif-a-potentially-dangerous-request-form-value-was-detected-from-the-client-wresult-t-requestsecurityto/history.aspx protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex) { validationFailureIndex = 0; if (requestValidationSource == RequestValidationSource.Form && !String.IsNullOrEmpty(collectionKey) && collectionKey.Equals(WSFederationConstants.Parameters.Result, StringComparison.Ordinal)) { var unvalidatedFormValues = GetUnvalidatedFormValues(context); SignInResponseMessage message = WSFederationMessage.CreateFromNameValueCollection(WSFederationMessage.GetBaseUrl(context.Request.Url), unvalidatedFormValues) as SignInResponseMessage; if (message != null) { return(true); } } return(base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex)); }
private static bool IsInvitationRequest(out Guid invitationNumber) { Uri requestBaseUrl = WSFederationMessage.GetBaseUrl(HttpContext.Current.Request.Url); WSFederationMessage message = WSFederationMessage.CreateFromNameValueCollection(requestBaseUrl, HttpContext.Current.Request.Form); invitationNumber = Guid.Empty; if (message != null) { invitationNumber = message.Context.ToUpperInvariant().Contains(ConfigurationManager.AppSettings["UserAccountInvitationAction"].ToUpperInvariant()) ? new Guid(message.Context.Split('/').Last()) : Guid.Empty; } else { invitationNumber = requestBaseUrl.AbsolutePath.StartsWith(ConfigurationManager.AppSettings["UserAccountInvitationAction"], StringComparison.OrdinalIgnoreCase) ? new Guid(requestBaseUrl.AbsolutePath.Split('/').Last()) : Guid.Empty; } return(invitationNumber != Guid.Empty); }
/// <summary> /// Gets from the form the context /// </summary> /// <param name="form"></param> /// <returns></returns> private static string GetUrlFromContext(FormCollection form) { WSFederationMessage message = WSFederationMessage.CreateFromNameValueCollection(new Uri("http://www.notused.com"), form); return(message != null ? message.Context : null); }
protected virtual async Task <bool> HandleRemoveCallbackAsync() { try { if (string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(Request.ContentType) // May have media/type; charset=utf-8, allow partial match. && Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase) && Request.Body.CanRead) { if (!Request.Body.CanSeek) { // Buffer in case this body was not meant for us. var memoryStream = new MemoryStream(); await Request.Body.CopyToAsync(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); Request.Body = memoryStream; } var form = await Request.ReadFormAsync(); var collection = new Dictionary <string, StringValues>(); foreach (var tuple in form) { collection.Add(tuple.Key, tuple.Value); } var uri = new Uri($"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}"); var wsFederationMessage = WSFederationMessage.CreateFromNameValueCollection(uri, collection); var xml = wsFederationMessage.GetParameter("wresult"); var document = new XmlDocument(); document.LoadXml(xml); var nsMan = new XmlNamespaceManager(document.NameTable); // Parse SAML2 response nsMan.AddNamespace("trust", "http://docs.oasis-open.org/ws-sx/ws-trust/200512"); nsMan.AddNamespace("saml2", "urn:oasis:names:tc:SAML:2.0:assertion"); var parentNodes = "trust:RequestSecurityTokenResponseCollection/trust:RequestSecurityTokenResponse/trust:RequestedSecurityToken/"; var assertionNode = document.SelectSingleNode(parentNodes + "saml2:EncryptedAssertion", nsMan); if (assertionNode == null) { assertionNode = document.SelectSingleNode(parentNodes + "saml2:Assertion", nsMan); } // Parse SAML response if (assertionNode == null) { nsMan = new XmlNamespaceManager(document.NameTable); nsMan.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion"); nsMan.AddNamespace("t", "http://schemas.xmlsoap.org/ws/2005/02/trust"); parentNodes = "t:RequestSecurityTokenResponse/t:RequestedSecurityToken/"; assertionNode = document.SelectSingleNode(parentNodes + "saml:EncryptedAssertion", nsMan); if (assertionNode == null) { assertionNode = document.SelectSingleNode(parentNodes + "saml:Assertion", nsMan); } } if (assertionNode == null) { return(false); } List <Claim> claims = null; if (Options.GetClaimsCallback != null) { claims = Options.GetClaimsCallback(assertionNode.ChildNodes); } else { claims = new List <Claim>(); if (Options.Events.OnClaimsReceived != null) { claims = Options.Events.OnClaimsReceived(assertionNode); } else { foreach (XmlNode child in assertionNode.ChildNodes) { if (child.Name == "saml2:Subject" || child.Name == "saml:Subject") { claims.Add(new Claim("sub", child.InnerText)); } if (child.Name == "saml2:AttributeStatement" || child.Name == "saml:AttributeStatement") { foreach (XmlNode attribute in child.ChildNodes) { var id = string.Empty; foreach (XmlAttribute metadata in attribute.Attributes) { if (metadata.Name == "Name") { id = metadata.Value; } } claims.Add(ToClaim(id, attribute.InnerText)); } } } } } var claimsIdentity = new ClaimsIdentity(claims, Options.AuthenticationScheme); var principal = new ClaimsPrincipal(claimsIdentity); var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), Options.AuthenticationScheme); await Context.Authentication.SignInAsync( Options.SignInScheme, principal, new AuthenticationProperties()); var redirectPath = Options.RedirectPath; if (string.IsNullOrWhiteSpace(redirectPath)) { redirectPath = "/"; } var redirectUrl = BuildRedirectUri(redirectPath); Response.Redirect(redirectUrl); return(true); } } catch (Exception) { return(false); } return(false); }
public async Task <IHttpActionResult> Login(string relyingPartyName) { if (string.IsNullOrWhiteSpace(relyingPartyName)) { return(BadRequest("No relying party id provided")); } string action; NameValueCollection content = null; NameValueCollection qs = Request.RequestUri.ParseQueryString(); action = qs.Get(WSFederationConstants.Parameters.Action); if (string.IsNullOrWhiteSpace(action)) { content = await Request.Content.ReadAsFormDataAsync(); action = content.Get(WSFederationConstants.Parameters.Action); } if (action == WSFederationConstants.Actions.SignIn) { IRelyingParty rp = STSConfiguration <RelyingParty> .Current.RelyingParties.FindByName(relyingPartyName); if (this.User != null && this.User.Identity.IsAuthenticated) { if (content == null) { content = await Request.Content.ReadAsFormDataAsync(); } WSFederationMessage responseMessageFromIssuer = WSFederationMessage.CreateFromNameValueCollection(Request.RequestUri, content); var contextId = responseMessageFromIssuer.Context; var ctxCookie = System.Web.HttpContext.Current.Request.Cookies[contextId]; if (ctxCookie == null) { throw new InvalidOperationException("Context cookie not found"); } var originalRequestUri = new Uri(ctxCookie.Value); HttpCookie cookie = DeleteContextCookie(contextId); System.Web.HttpContext.Current.Response.Cookies.Add(cookie); var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(originalRequestUri); var sts = new SimpleSts(rp.GetStsConfiguration()); SignInResponseMessage rm = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User as ClaimsPrincipal, sts); //WSTrustSerializationContext context = new WSTrustSerializationContext(FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlerCollectionManager); //WSFederationSerializer fedSer = new WSFederationSerializer(); //RequestSecurityTokenResponse token = fedSer.CreateResponse(rm, context); //token.RequestedSecurityToken.SecurityToken. FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(rm, System.Web.HttpContext.Current.Response); return(StatusCode(HttpStatusCode.NoContent)); } else { var contextId = Guid.NewGuid().ToString(); HttpCookie cookie = CreateContextCookie(contextId, HttpUtility.UrlDecode(this.Request.RequestUri.AbsoluteUri)); System.Web.HttpContext.Current.Response.Cookies.Add(cookie); var message = new SignInRequestMessage(new Uri(rp.AuthenticationUrl), FederatedAuthentication.WSFederationAuthenticationModule.Realm) { CurrentTime = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "Z", HomeRealm = rp.Realm, Context = contextId, Reply = Url.Link("Login", new { relyingPartyName = relyingPartyName }) }; message.Parameters.Add(new KeyValuePair <string, string>("originalRequest", Request.RequestUri.ToString())); return(Redirect(message.RequestUrl)); } } else { return(BadRequest(String.Format( CultureInfo.InvariantCulture, "The action '{0}' (Request.QueryString['{1}']) is unexpected. Expected actions are: '{2}' or '{3}'.", String.IsNullOrEmpty(action) ? "<EMPTY>" : action, WSFederationConstants.Parameters.Action, WSFederationConstants.Actions.SignIn, WSFederationConstants.Actions.SignOut))); } }