public SignInResponseMessage Generate(SignInRequestMessage request, WindowsPrincipal windowsPrincipal) { Logger.Info("Creating WS-Federation signin response"); // create subject var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options); // create token for user var token = CreateSecurityToken(outgoingSubject); // return response var rstr = new RequestSecurityTokenResponse { AppliesTo = new EndpointReference(_options.IdpRealm), Context = request.Context, ReplyTo = _options.IdpReplyUrl, RequestedSecurityToken = new RequestedSecurityToken(token) }; var serializer = new WSFederationSerializer( new WSTrust13RequestSerializer(), new WSTrust13ResponseSerializer()); var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager(); mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler(); var responseMessage = new SignInResponseMessage( new Uri(_options.IdpReplyUrl), rstr, serializer, new WSTrustSerializationContext(mgr)); return(responseMessage); }
public Stream Issue(string realm, string wctx, string wct, string wreply) { MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream, Encoding.UTF8); string fullRequest = Constants.HttpLocalhost + Constants.Port + Constants.WSFedStsIssue + string.Format("?wa=wsignin1.0&wtrealm={0}&wctx={1}&wct={2}&wreply={3}", realm, HttpUtility.UrlEncode(wctx), wct, wreply); SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(new Uri(fullRequest)); ClaimsIdentity identity = new ClaimsIdentity(AuthenticationTypes.Federation); identity.AddClaim(new Claim(ClaimTypes.Name, "foo")); ClaimsPrincipal principal = new ClaimsPrincipal(identity); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, principal, this.securityTokenService); responseMessage.Write(writer); writer.Flush(); stream.Position = 0; WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"; return(stream); }
public IHttpActionResult LoginMock(string id) { if (string.IsNullOrWhiteSpace(id)) { return(BadRequest("No relying party id provided")); } IRelyingParty rp = STSConfiguration <RelyingParty> .Current.RelyingParties.FindByName(id); if (rp == null) { return(BadRequest(string.Format("Relying party with id {0} was not found", id))); } var sts = new SimpleSts(rp.GetStsConfiguration()); var rMessage = rp.GetSignInRequestMessage(Request.RequestUri); ClaimsPrincipal principal = GetMockPrincipalPrincipal(GetMockUser(rMessage)); //ClearAllCookies(); SignInResponseMessage res = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(rMessage, principal, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(res, HttpContext.Current.Response); return(StatusCode(HttpStatusCode.NoContent)); }
protected void Page_Load() { string action = this.Request.QueryString[WSFederationConstants.Parameters.Action]; if (action == WSFederationConstants.Actions.SignIn) { // Process signin request. if (SimulatedWindowsAuthenticationOperations.TryToAuthenticateUser(this.Context, this.Request, this.Response)) { SecurityTokenService sts = new IdentityProviderSecurityTokenService(IdentityProviderSecurityTokenServiceConfiguration.Current); var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(this.Request.Url); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, this.User, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.Response); } } else if (action == WSFederationConstants.Actions.SignOut) { // Process signout request in the default page. this.Response.Redirect("~/?" + this.Request.QueryString, false); } else { throw new InvalidOperationException( 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)); } }
public SignInResponseMessage Generate(SignInRequestMessage request, WindowsPrincipal windowsPrincipal) { Logger.Info("Creating WS-Federation signin response"); // create subject var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options); // create token for user var token = CreateSecurityToken(outgoingSubject); // return response var rstr = new RequestSecurityTokenResponse { AppliesTo = new EndpointReference(_options.IdpRealm), Context = request.Context, ReplyTo = _options.IdpReplyUrl, RequestedSecurityToken = new RequestedSecurityToken(token) }; var serializer = new WSFederationSerializer( new WSTrust13RequestSerializer(), new WSTrust13ResponseSerializer()); var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager(); mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler(); var responseMessage = new SignInResponseMessage( new Uri(_options.IdpReplyUrl), rstr, serializer, new WSTrustSerializationContext(mgr)); return responseMessage; }
private ActionResult ProcessWSFedSignInResponse(SignInResponseMessage responseMessage, SecurityToken token) { var principal = ValidateToken(token); var issuerName = principal.Claims.First().Issuer; principal.Identities.First().AddClaim( new Claim(Constants.Claims.IdentityProvider, issuerName, ClaimValueTypes.String, Constants.InternalIssuer)); var context = GetContextCookie(); var message = new SignInRequestMessage(new Uri("http://foo"), context.Realm); message.Context = context.Wctx; // issue token and create ws-fed response var wsFedResponse = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest( message, principal, TokenServiceConfiguration.Current.CreateSecurityTokenService()); // set cookie for single-sign-out new SignInSessionsManager(HttpContext, _cookieName, ConfigurationRepository.Global.MaximumTokenLifetime) .AddEndpoint(wsFedResponse.BaseUri.AbsoluteUri); // set cookie for idp signout SetIdPCookie(context.WsFedEndpoint); return(new WSFederationResult(wsFedResponse, requireSsl: ConfigurationRepository.WSFederation.RequireSslForReplyTo)); }
public async Task<SignInResponseMessage> GenerateResponseAsync(SignInValidationResult validationResult) { Logger.Info("Creating WS-Federation signin response"); // create subject var outgoingSubject = await CreateSubjectAsync(validationResult); // create token for user var token = CreateSecurityToken(validationResult, outgoingSubject); // return response var rstr = new RequestSecurityTokenResponse { AppliesTo = new EndpointReference(validationResult.RelyingParty.Realm), Context = validationResult.SignInRequestMessage.Context, ReplyTo = validationResult.ReplyUrl, RequestedSecurityToken = new RequestedSecurityToken(token) }; var serializer = new WSFederationSerializer( new WSTrust13RequestSerializer(), new WSTrust13ResponseSerializer()); var responseMessage = new SignInResponseMessage( new Uri(validationResult.ReplyUrl), rstr, serializer, new WSTrustSerializationContext()); return responseMessage; }
private SignInResponseMessage CreateResponse(SignInValidationResult validationResult, SecurityToken token) { var rstr = new RequestSecurityTokenResponse { AppliesTo = new EndpointReference(validationResult.Client.ClientId), Context = validationResult.SignInRequestMessage.Context, ReplyTo = validationResult.ReplyUrl, RequestedSecurityToken = new RequestedSecurityToken(token) }; //var serializer = new WSFederationSerializer( // new WSTrust13RequestSerializer(), // new WSTrust13ResponseSerializer()); // the asp.net core MW does currently not support WS-Trust 1.3 var serializer = new WSFederationSerializer( new WSTrustFeb2005RequestSerializer(), new WSTrustFeb2005ResponseSerializer()); var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager(); mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler(); var responseMessage = new SignInResponseMessage( new Uri(validationResult.ReplyUrl), rstr, serializer, new WSTrustSerializationContext(mgr)); return(responseMessage); }
public async Task <SignInResponseMessage> GenerateResponseAsync(SignInValidationResult validationResult) { Logger.Info("Creating WS-Federation signin response"); // create subject var outgoingSubject = await CreateSubjectAsync(validationResult); // create token for user var token = CreateSecurityToken(validationResult, outgoingSubject); // return response var rstr = new RequestSecurityTokenResponse { AppliesTo = new EndpointReference(validationResult.RelyingParty.Realm), Context = validationResult.SignInRequestMessage.Context, ReplyTo = validationResult.ReplyUrl, RequestedSecurityToken = new RequestedSecurityToken(token) }; var serializer = new WSFederationSerializer( new WSTrust13RequestSerializer(), new WSTrust13ResponseSerializer()); var responseMessage = new SignInResponseMessage( new Uri(validationResult.ReplyUrl), rstr, serializer, new WSTrustSerializationContext()); return(responseMessage); }
private ClaimsPrincipal GetClaimsPrincipal(SignInResponseMessage signInResponse) { try { //configure the certificate and some service token handler configuration properties (these basically match the web.config settings for MVC 4/5 app). SecurityTokenHandlerConfiguration config = new SecurityTokenHandlerConfiguration(); config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Options.Realm)); config.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None; //we have dodgy certs in dev ConfigurationBasedIssuerNameRegistry inr = new ConfigurationBasedIssuerNameRegistry(); inr.AddTrustedIssuer(Options.SigningCertThumbprint, Options.ClaimsIssuer); config.IssuerNameRegistry = inr; config.CertificateValidator = System.IdentityModel.Selectors.X509CertificateValidator.None; //we have dodgy certs in dev //Load up an XmlDocument with the result. Have to use XmlDocument so we can generate a valid reader unfortunately. XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(signInResponse.Result); //Add the namespaces and search for Assertion or EncryptedAssertion XmlNamespaceManager nsMan = new XmlNamespaceManager(xmlDoc.NameTable); 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 = xmlDoc.SelectSingleNode(parentNodes + "saml2:EncryptedAssertion", nsMan); if (assertionNode == null) { assertionNode = xmlDoc.SelectSingleNode(parentNodes + "saml2:Assertion", nsMan); } else { //this is an encrypted response so add a ServiceTokenResolver of X509CertificateStoreTokenResolver so the assertion can be decrypted. Hard codes LocalMachine - could be configured as well. config.ServiceTokenResolver = new X509CertificateStoreTokenResolver(Options.EncryptionCertStoreName, StoreLocation.LocalMachine); } if (assertionNode == null) { throw new Exception("No assertion element found in Response."); } using (var reader = new XmlNodeReader(assertionNode)) { //Get the token and convert it to a Claims Principal for return SecurityTokenHandlerCollection collection = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config); var securityToken = collection.ReadToken(reader); var claimsIdentities = collection.ValidateToken(securityToken); ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentities); return(principal); } } catch (Exception ex) { //TODO: Add some logging var err = ex; } return(null); }
private SignInResponseMessage ExtractTokenResponse() { var formResult = Request.Content.ReadAsFormDataAsync().Result; var wresult = formResult["wresult"]; var signInResponse = new SignInResponseMessage(Request.RequestUri, wresult); return(signInResponse); }
private SignInResponseMessage getMessage() { String realm = this.Request.Params["wtrealm"]; String token = File.ReadAllText(@"C:\Users\troy\projects\FederatedDemos\Custom Token Demo\Code\Adatum.SimulatedIssuer.1\Token.xml"); SignInResponseMessage responseMessage = new SignInResponseMessage(new Uri(realm), token); return(responseMessage); }
protected override void OnLoad(EventArgs e) { string action = this.Request.QueryString[WSFederationConstants.Parameters.Action]; if (action == WSFederationConstants.Actions.SignIn) { // Process signin request. var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(this.Request.Url); if (this.User != null && this.User.Identity.IsAuthenticated) { SecurityTokenService sts = new IdentityProviderSecurityTokenService(IdentityProviderSecurityTokenServiceConfiguration.Current); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, this.User, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.Response); } else { throw new UnauthorizedAccessException(); } } else if (action == WSFederationConstants.Actions.SignOut || action == WSFederationConstants.Actions.SignOutCleanup) { // Process signout request. WSFederationMessage requestMessage = WSFederationMessage.CreateFromUri(this.Request.Url); FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(requestMessage, this.User, null, this.Response); // Simulate what happens when you sign out of WIF to send a response that everything was Ok var signOutImage = new byte[] { 71, 73, 70, 56, 57, 97, 17, 0, 13, 0, 162, 0, 0, 255, 255, 255, 169, 240, 169, 125, 232, 125, 82, 224, 82, 38, 216, 38, 0, 0, 0, 0, 0, 0, 0, 0, 0, 33, 249, 4, 5, 0, 0, 5, 0, 44, 0, 0, 0, 0, 17, 0, 13, 0, 0, 8, 84, 0, 11, 8, 28, 72, 112, 32, 128, 131, 5, 19, 22, 56, 24, 128, 64, 0, 0, 10, 13, 54, 116, 8, 49, 226, 193, 1, 4, 6, 32, 36, 88, 113, 97, 0, 140, 26, 11, 30, 68, 8, 64, 0, 129, 140, 29, 5, 2, 56, 73, 209, 36, 202, 132, 37, 79, 14, 112, 73, 81, 97, 76, 150, 53, 109, 210, 36, 32, 32, 37, 76, 151, 33, 35, 26, 20, 16, 84, 168, 65, 159, 9, 3, 2, 0, 59 }; this.Response.Cache.SetCacheability(HttpCacheability.NoCache); this.Response.ClearContent(); this.Response.ContentType = "image/gif"; this.Response.BinaryWrite(signOutImage); } else { throw new InvalidOperationException( 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)); } base.OnLoad(e); }
public WsFedSignInContext( string authenticationScheme, ClaimsPrincipal principal, IDictionary <string, string> properties, SignInResponseMessage signInMessage, string returnUrl) : base(authenticationScheme, principal, properties) { SignInMessage = signInMessage; ReturnUrl = returnUrl; }
public SitefinityResult(SignInResponseMessage message, bool requireSsl) { if (requireSsl) { if (message.BaseUri.Scheme != Uri.UriSchemeHttps) { throw new InvalidRequestException(Resources.WSFederation.WSFederationResult.ReturnUrlMustBeSslException); } } Content = message.WriteFormPost(); }
public WSFederationResult(SignInResponseMessage message, bool requireSsl) { if (requireSsl) { if (message.BaseUri.Scheme != Uri.UriSchemeHttps) { throw new InvalidRequestException("Return URL must be SSL."); } } Content = message.WriteFormPost(); }
/// <summary> /// We perform WS-Federation passive protocol logic in this method and call out to the appropriate request handlers. /// </summary> protected void Page_PreRender(object sender, EventArgs e) { if (IsAuthenticatedUser) { IClaimsIdentity id = (IClaimsIdentity)((IClaimsPrincipal)Thread.CurrentPrincipal).Identities[0]; // Use the WSFederationMessage.CreateFromUri to parse the request and create a SignInRequestMessage object. Uri requestUri = new Uri(Request.Url.ToString() + "?" + Request.Params["wctx"]); SignInRequestMessage requestMessage = WSFederationMessage.CreateFromUri(requestUri) as SignInRequestMessage; if (requestMessage != null) { // Process the sign in request. SignInResponseMessage responseMessage = ProcessSignInRequest(requestMessage); // Write the response message. responseMessage.Context = requestMessage.Context; responseMessage.Write(Page.Response.Output); Response.Flush(); Response.End(); } string action = Request.QueryString["wa"]; if (action == WSFederationConstants.Actions.SignOut) { FederatedAuthentication.SessionAuthenticationModule.CookieHandler.Delete(); string redirectUrl = Request.QueryString["wreply"]; if (IsValidReplyUrl(redirectUrl)) { Response.Redirect(redirectUrl); } } } // forward to an identity provider else { // Check if 'whr' parameter is specified. string identityProviderUri = Request.QueryString["whr"]; string action = Request.QueryString["wa"]; if (action == WSFederationConstants.Actions.SignIn) { if (String.IsNullOrEmpty(identityProviderUri)) { // Forward the user to the IdetityProvider selection page. identityProviderUri = "https://localhost/PassiveFPSTS/homeRealmSelectionPage.aspx"; } SignInRequestMessage signInMessage = new SignInRequestMessage(new Uri(identityProviderUri), "https://localhost/PassiveFPSTS/Default.aspx"); signInMessage.Context = Request.QueryString.ToString(); Response.Redirect(signInMessage.RequestUrl); } } }
public string GetResponseHtml(IDictionary <string, string> parameters, Uri signinUri) { string code = parameters["code"]; // Exchange the Request Token for an Access Token string appId = _settings.VkApplicationId; string appSecret = _settings.VkApplicationSecret; string scheme = parameters["SERVER_PORT_SECURE"] == "1" ? "https" : "http"; var callbackUri = new UriBuilder(string.Format("{0}://{1}", scheme, parameters["HTTP_HOST"])) { Path = parameters["URL"], Query = string.Format("context={0}", parameters["context"]) }; var service = new VkClient(appId, appSecret); dynamic accessToken = service.GetAccessToken(code, callbackUri.ToString()); dynamic token = accessToken.access_token; service.AuthenticateWith(token.ToString()); // Claims dynamic result = service.Get("users.get", new { fields = "screen_name" }); dynamic user = result.response[0]; string acsNamespace = _settings.AcsNamespace; string wtRealm = string.Format(WtRealm, acsNamespace); string wReply = string.Format(WReply, acsNamespace); var requestMessage = new SignInRequestMessage(signinUri, wtRealm, wReply); // Add extracted claims var identity = new ClaimsIdentity(AuthenticationTypes.Federation); identity.AddClaim(new Claim(ClaimTypes.Name, string.Format("{0} {1}", user.first_name, user.last_name))); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.uid.ToString())); identity.AddClaim(new Claim(VkClaims.VkToken, token.ToString())); var principal = new ClaimsPrincipal(identity); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, principal, this); responseMessage.Context = parameters["context"]; return(responseMessage.WriteFormPost()); }
private ClaimsPrincipal ValidateToken(SignInResponseMessage signInResponse) { var serviceConfig = new FederationConfiguration(); var fam = new WSFederationAuthenticationModule { FederationConfiguration = serviceConfig }; var tokenFromAcs = fam.GetSecurityToken(signInResponse); var icp = ValidateToken(tokenFromAcs); return(icp); }
/// <summary> /// Performs WS-Federation Passive Protocol processing. /// </summary> protected void Page_PreRender(object sender, EventArgs e) { string action = Request.QueryString[WSFederationConstants.Parameters.Action]; try { if (action == WSFederationConstants.Actions.SignIn) { // Process signin request. var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url); if (User != null && User.Identity.IsAuthenticated) { SecurityTokenService sts = new CustomSecurityTokenService(CustomSecurityTokenServiceConfiguration.Current); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User as ClaimsPrincipal, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, Response); } else { throw new UnauthorizedAccessException(); } } else if (action == WSFederationConstants.Actions.SignOut) { // Process signout request. var requestMessage = (SignOutRequestMessage)WSFederationMessage.CreateFromUri(Request.Url); FederatedPassiveSecurityTokenServiceOperations.ProcessSignOutRequest(requestMessage, User as ClaimsPrincipal, requestMessage.Reply, Response); } else { throw new InvalidOperationException( 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)); } } catch (ThreadAbortException) { // Swallow exception } catch (Exception genericException) { throw new Exception( "An unexpected error occurred when processing the request. See inner exception for details.", genericException); } }
// <Snippet1> /// <summary> /// We perform WS-Federation passive protocol logic in this method and call out to the appropriate request handlers. /// </summary> protected void Page_PreRender(object sender, EventArgs e) { if (IsAuthenticatedUser) { ClaimsIdentity id = ((ClaimsPrincipal)Thread.CurrentPrincipal).Identities[0]; // Use the WSFederationMessage.CreateFromUri to parse the request and create a SignInRequestMessage object. Uri requestUri = new Uri(Request.Url.AbsoluteUri); SignInRequestMessage requestMessage = WSFederationMessage.CreateFromUri(requestUri) as SignInRequestMessage; if (requestMessage != null) { // Process the sign in request. SignInResponseMessage responseMessage = ProcessSignInRequest(requestMessage); // Write the response message. responseMessage.Context = requestMessage.Context; responseMessage.Write(Page.Response.Output); Response.Flush(); Response.End(); } string action = Request.QueryString["wa"]; if (action == "wsignout1.0") { FederatedAuthentication.SessionAuthenticationModule.CookieHandler.Delete(); string redirectUrl = Request.QueryString["wreply"]; if (IsValidReplyUrl(redirectUrl)) { Response.Redirect(redirectUrl); } } } // forward to an identity provider else { // <Snippet2> string identityProviderUri = Request.QueryString["whr"]; string action = Request.QueryString["wa"]; SignInRequestMessage signInRequest = FederatedAuthentication.WSFederationAuthenticationModule.CreateSignInRequest(Guid.NewGuid().ToString(), "http://MyAppreturnUrl", false); signInRequest.Realm = "htp://MyApp.com"; signInRequest.HomeRealm = identityProviderUri; Response.Redirect(signInRequest.RequestUrl); // </Snippet2> } }
public virtual void ProcessSignIn(ClaimsPrincipal principal, Uri requestUri) { // Get the current context. HttpContext context = HttpContext.Current; // Create the signin request message based on the current request context. SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(requestUri); // Create the signin response message based on the processing the signin request. SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, principal, this); // Process the signin response. FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, context.Response); }
// 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)); }
protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex) { validationFailureIndex = 0; if (requestValidationSource == RequestValidationSource.Form && collectionKey.Equals(WSFederationConstants.Parameters.Result, StringComparison.Ordinal)) { SignInResponseMessage message = WSFederationMessage.CreateFromFormPost(context.Request) as SignInResponseMessage; if (message != null) { return(true); } } return(base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex)); }
private static string ProcessSignIn(Uri url, ClaimsPrincipal principal) { SignInRequestMessage requestMSG = (SignInRequestMessage)WSFederationMessage.CreateFromUri(url); X509SigningCredentials credentials = new X509SigningCredentials (GetX509Cert(ConfigurationManager.AppSettings["SigningCertificateName"])); SecurityTokenServiceConfiguration config = new SecurityTokenServiceConfiguration(ConfigurationManager.AppSettings["IssuerName"], credentials); CustomSecurityTokenService sts = new CustomSecurityTokenService(config); SignInResponseMessage finalResponse = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMSG, principal, sts); return(finalResponse.WriteFormPost()); }
private void HandleSignInRequest() { SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url); if (this.User != null && this.User.Identity != null && this.User.Identity.IsAuthenticated) { SecurityTokenService sts = new IdentityProviderSecurityTokenService(IdentityProviderSecurityTokenServiceConfiguration.Current); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.Response); } else { throw new UnauthorizedAccessException(); } }
private ActionResult HandleTailspinSignInResponse(string userNameToValidate, Uri originalRequestUrl) { var ctx = System.Web.HttpContext.Current; SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(originalRequestUrl); SecurityTokenService sts = new IdentityProviderSecurityTokenService(SecurityTokenServiceConfiguration <IdentityProviderSecurityTokenService> .Current) { CustomUserName = userNameToValidate }; SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, this.User, sts); FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, ctx.Response); return(this.Content(responseMessage.WriteFormPost())); }
public string GetResponseHtml(IDictionary <string, string> parameters, Uri signinUri) { var requestToken = new OAuthRequestToken { Token = parameters["oauth_token"] }; // Exchange the Request Token for an Access Token string consumerKey = _settings.TwitterConsumerKey; string consumerSecret = _settings.TwitterConsumerSecret; var service = new TwitterService(consumerKey, consumerSecret); OAuthAccessToken accessToken = service.GetAccessToken(requestToken, parameters["oauth_verifier"]); service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret); TwitterUser user = service.GetUserProfile(new GetUserProfileOptions()); // Claims string name = user != null ? user.Name : accessToken.ScreenName; string nameIdentifier = string.Format(TwitterAccountPage, accessToken.UserId); string token = accessToken.Token; string tokenSecret = accessToken.TokenSecret; string acsNamespace = _settings.AcsNamespace; string wtRealm = string.Format(WtRealm, acsNamespace); string wReply = string.Format(WReply, acsNamespace); var requestMessage = new SignInRequestMessage(signinUri, wtRealm, wReply); // Add extracted claims var identity = new ClaimsIdentity(AuthenticationTypes.Federation); identity.AddClaim(new Claim(ClaimTypes.Name, name)); identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, nameIdentifier)); identity.AddClaim(new Claim(TwitterClaims.TwitterToken, token)); identity.AddClaim(new Claim(TwitterClaims.TwitterTokenSecret, tokenSecret)); var principal = new ClaimsPrincipal(identity); SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, principal, this); responseMessage.Context = parameters["context"]; return(responseMessage.WriteFormPost()); }
public IHttpActionResult Tokens([FromUri] string id) { if (string.IsNullOrWhiteSpace(id)) { return(BadRequest("No relying party id provided")); } IRelyingParty rp = STSConfiguration <RelyingParty> .Current.RelyingParties.FindByName(id); if (rp == null) { return(BadRequest(string.Format("Relying party with id {0} was not found", id))); } var sts = new SimpleSts(rp.GetStsConfiguration()); var rMessage = rp.GetSignInRequestMessage(Request.RequestUri); //ClearAllCookies(); SignInResponseMessage res = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(rMessage, GetPrincipal(), sts); //SecurityToken st = FederatedAuthentication.WSFederationAuthenticationModule.GetSecurityToken(res); //XmlReader reader = XmlReader.Create("addressdata.xml"); //XmlDictionaryReader dictReader = XmlDictionaryReader.CreateDictionaryReader(reader); //string s= FederatedAuthentication.WSFederationAuthenticationModule.GetXmlTokenFromMessage(res); //FederatedPassiveSecurityTokenServiceOperations..ProcessSignInResponse(res, HttpContext.Current.Response); var response = Request.CreateResponse(HttpStatusCode.OK); NameValueCollection nvc = WSFederationMessage.ParseQueryString(new Uri(res.WriteQueryString())); response.Content = new FormUrlEncodedContent(nvc.AllKeys.Select(f => new KeyValuePair <string, string>(f, nvc[f]))); //response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/soap+xml"); return(ResponseMessage(response)); }
private SignInResponseMessage GetSignInResponseMessage() { if (Context.Request.HasFormContentType) { //convert form into NameValueCollection for SignInResponseMessage checking. var nvc = new NameValueCollection(); foreach (var fv in Context.Request.Form) { nvc.Add(fv.Key, fv.Value); } //check if this is a sign in response SignInResponseMessage signInResponse = SignInResponseMessage.CreateFromNameValueCollection(new Uri(Options.Realm), nvc) as SignInResponseMessage; return(signInResponse); } return(null); }
public async Task <SignInResponseMessage> GenerateAsync(SignInRequestMessage request, WindowsPrincipal windowsPrincipal) { Logger.Info("Creating WS-Federation signin response"); // create subject var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options); // call custom claims tranformation logic var context = new CustomClaimsProviderContext { WindowsPrincipal = windowsPrincipal, OutgoingSubject = outgoingSubject }; await _options.CustomClaimsProvider.TransformAsync(context); // create token for user var token = CreateSecurityToken(context.OutgoingSubject); // return response var rstr = new RequestSecurityTokenResponse { AppliesTo = new EndpointReference(_options.IdpRealm), Context = request.Context, ReplyTo = _options.IdpReplyUrl, RequestedSecurityToken = new RequestedSecurityToken(token) }; var serializer = new WSFederationSerializer( new WSTrust13RequestSerializer(), new WSTrust13ResponseSerializer()); var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager(); mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler(); var responseMessage = new SignInResponseMessage( new Uri(_options.IdpReplyUrl), rstr, serializer, new WSTrustSerializationContext(mgr)); return(responseMessage); }
public async Task<SignInResponseMessage> GenerateAsync(SignInRequestMessage request, WindowsPrincipal windowsPrincipal) { Logger.Info("Creating WS-Federation signin response"); // create subject var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options); // call custom claims tranformation logic var context = new CustomClaimsProviderContext { WindowsPrincipal = windowsPrincipal, OutgoingSubject = outgoingSubject }; await _options.CustomClaimsProvider.TransformAsync(context); // create token for user var token = CreateSecurityToken(context.OutgoingSubject); // return response var rstr = new RequestSecurityTokenResponse { AppliesTo = new EndpointReference(_options.IdpRealm), Context = request.Context, ReplyTo = _options.IdpReplyUrl, RequestedSecurityToken = new RequestedSecurityToken(token) }; var serializer = new WSFederationSerializer( new WSTrust13RequestSerializer(), new WSTrust13ResponseSerializer()); var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager(); mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler(); var responseMessage = new SignInResponseMessage( new Uri(_options.IdpReplyUrl), rstr, serializer, new WSTrustSerializationContext(mgr)); return responseMessage; }
/// <summary> /// Processes a WS-Federation sign in request. /// </summary> /// <param name="request">The request.</param> /// <param name="principal">The client principal.</param> /// <param name="configuration">The token service configuration.</param> /// <returns>A SignInResponseMessage</returns> public static SignInResponseMessage ProcessSignInRequest(SignInRequestMessage request, IClaimsPrincipal principal, SecurityTokenServiceConfiguration configuration) { Contract.Requires(request != null); Contract.Requires(principal != null); Contract.Requires(configuration != null); Contract.Ensures(Contract.Result <SignInResponseMessage>() != null); // create token service and serializers var sts = configuration.CreateSecurityTokenService(); var context = new WSTrustSerializationContext( sts.SecurityTokenServiceConfiguration.SecurityTokenHandlerCollectionManager, sts.SecurityTokenServiceConfiguration.ServiceTokenResolver, sts.SecurityTokenServiceConfiguration.IssuerTokenResolver); var federationSerializer = new WSFederationSerializer( sts.SecurityTokenServiceConfiguration.WSTrust13RequestSerializer, sts.SecurityTokenServiceConfiguration.WSTrust13ResponseSerializer); // convert ws-fed message to RST and call issue pipeline var rst = federationSerializer.CreateRequest(request, context); var rstr = sts.Issue(principal, rst); // check ReplyTo Uri result = null; if (!Uri.TryCreate(rstr.ReplyTo, UriKind.Absolute, out result)) { throw new InvalidOperationException("Invalid ReplyTo"); } var response = new SignInResponseMessage(result, rstr, federationSerializer, context); // copy the incoming context data (as required by the WS-Federation spec) if (!String.IsNullOrEmpty(request.Context)) { response.Context = request.Context; } return(response); }
public SignInResult(SignInResponseMessage message) { _message = message; }
public PassiveSignInResponseResult(HttpContextBase context) : base("text/html") { message = new WSFederationSignIn(context).CreateMessage(); }
public SignInActionResult(SignInResponseMessage message) { this.message = message; }
/// <summary> /// Processes a WS-Federation sign in request. /// </summary> /// <param name="request">The request.</param> /// <param name="principal">The client principal.</param> /// <param name="configuration">The token service configuration.</param> /// <returns>A SignInResponseMessage</returns> public static SignInResponseMessage ProcessSignInRequest(SignInRequestMessage request, IClaimsPrincipal principal, SecurityTokenServiceConfiguration configuration) { Contract.Requires(request != null); Contract.Requires(principal != null); Contract.Requires(configuration != null); Contract.Ensures(Contract.Result<SignInResponseMessage>() != null); // create token service and serializers var sts = configuration.CreateSecurityTokenService(); var context = new WSTrustSerializationContext( sts.SecurityTokenServiceConfiguration.SecurityTokenHandlerCollectionManager, sts.SecurityTokenServiceConfiguration.ServiceTokenResolver, sts.SecurityTokenServiceConfiguration.IssuerTokenResolver); var federationSerializer = new WSFederationSerializer( sts.SecurityTokenServiceConfiguration.WSTrust13RequestSerializer, sts.SecurityTokenServiceConfiguration.WSTrust13ResponseSerializer); // convert ws-fed message to RST and call issue pipeline var rst = federationSerializer.CreateRequest(request, context); var rstr = sts.Issue(principal, rst); // check ReplyTo Uri result = null; if (!Uri.TryCreate(rstr.ReplyTo, UriKind.Absolute, out result)) { throw new InvalidOperationException("Invalid ReplyTo"); } var response = new SignInResponseMessage(result, rstr, federationSerializer, context); // copy the incoming context data (as required by the WS-Federation spec) if (!String.IsNullOrEmpty(request.Context)) { response.Context = request.Context; } return response; }
private SignInResponseMessage ExtractTokenResponse() { var formResult = Request.Content.ReadAsFormDataAsync().Result; var wresult = formResult["wresult"]; var signInResponse = new SignInResponseMessage(Request.RequestUri, wresult); return signInResponse; }
private ClaimsPrincipal ValidateToken(SignInResponseMessage signInResponse) { var serviceConfig = new FederationConfiguration(); var fam = new WSFederationAuthenticationModule { FederationConfiguration = serviceConfig }; var tokenFromAcs = fam.GetSecurityToken(signInResponse); var icp = ValidateToken(tokenFromAcs); return icp; }
public WSFederationResult(SignInResponseMessage message) { Content = message.WriteFormPost(); }
private ActionResult ProcessWSFedSignInResponse(SignInResponseMessage responseMessage, SecurityToken token) { var principal = ValidateToken(token); var issuerName = principal.Claims.First().Issuer; principal.Identities.First().AddClaim( new Claim(Constants.Claims.IdentityProvider, issuerName, ClaimValueTypes.String, Constants.InternalIssuer)); var context = GetContextCookie(); var message = new SignInRequestMessage(new Uri("http://foo"), context.Realm); message.Context = context.Wctx; // issue token and create ws-fed response var wsFedResponse = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest( message, principal, TokenServiceConfiguration.Current.CreateSecurityTokenService()); // set cookie for single-sign-out new SignInSessionsManager(HttpContext, _cookieName, ConfigurationRepository.Global.MaximumTokenLifetime) .AddEndpoint(wsFedResponse.BaseUri.AbsoluteUri); // set cookie for idp signout SetIdPCookie(context.WsFedEndpoint); return new WSFederationResult(wsFedResponse, requireSsl: ConfigurationRepository.WSFederation.RequireSslForReplyTo); }