Example #1
0
        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);
        }
Example #2
0
        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));
        }
        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));
            }
        }
Example #4
0
        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));
        }
Example #5
0
        /// <summary>
        /// Handles the click event on the logon button.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event arguments.</param>
        private void _logonButton_Click(object sender, EventArgs e)
        {
            // Get the user provider.
            var userProvider = this.Container.Resolve <IUserProvider>();

            // Get the principal object for the current user.
            IPrincipal principal;

            try
            {
                principal = userProvider.Logon(this._loginTextBox.Text, this._passwordTextBox.Text);
            }
            catch (SecurityException)
            {
                return;
            }

            // Create the sign in request.
            var signInRequestMessage =
                (SignInRequestMessage)WSFederationMessage.CreateFromUri(this.Request.Url);

            // Create the security token service.
            var securityTokenService =
                new SecurityTokenService(new SecurityTokenServiceConfiguration());

            // Send the sign request to the security token service and get a sign in response.
            var signInResponseMessage =
                FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(
                    signInRequestMessage, principal, securityTokenService);

            // Redirect based on the sign in response.
            FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(
                signInResponseMessage, this.Response);
        }
        public static SignInResponseMessage ProcessSignInRequest(this IRelyingParty rp, Uri baseUri, ClaimsPrincipal principal)
        {
            var sts      = new SimpleSts(rp.GetStsConfiguration());
            var rMessage = rp.GetSignInRequestMessage(baseUri);

            return(FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(
                       rMessage, principal, sts));
        }
        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);
        }
        private static string ProcessSignIn(Uri url, ClaimsPrincipal user)
        {
            var requestMessage     = (SignInRequestMessage)WSFederationMessage.CreateFromUri(url);
            var signingCredentials = new X509SigningCredentials(CustomSecurityTokenService.GetCertificate(ConfigurationManager.AppSettings["SigningCertificateName"]));
            var config             = new SecurityTokenServiceConfiguration(ConfigurationManager.AppSettings["IssuerName"], signingCredentials);
            var sts             = new CustomSecurityTokenService(config);
            var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, user, sts);

            return(responseMessage.WriteFormPost());
        }
Example #9
0
        private string ProcessSignIn(Uri url, ClaimsPrincipal user)
        {
            var requestMessage        = (SignInRequestMessage)WSFederationMessage.CreateFromUri(url);
            var config                = new SecurityTokenServiceConfiguration(ConfigurationManager.AppSettings["SecurityTokenServiceEndpointUrl"], SecurityHelper.CreateSignupCredentialsFromConfig());
            var encryptionCredentials = SecurityHelper.CreateEncryptingCredentialsFromConfig();
            var sts             = new CustomSecurityTokenService <AppMember>(WebConfigurationManager.AppSettings["LoginProviderName"], config, encryptionCredentials, _userStore);
            var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, user, sts);

            return(responseMessage.WriteFormPost());
        }
        public static string ProcessSignIn(Uri url, ClaimsPrincipal user)
        {
            var requestMessage     = (SignInRequestMessage)WSFederationMessage.CreateFromUri(url);
            var signingCredentials = new X509SigningCredentials(CustomSecurityTokenService.GetCertificate2());
            var config             = new SecurityTokenServiceConfiguration($"{url.Scheme}://{url.Authority}/FederatedLogin/", signingCredentials);
            var sts             = new CustomSecurityTokenService(config);
            var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, user, sts);

            return(responseMessage.WriteFormPost());
        }
Example #11
0
        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 void ActionSignon()
        {
            var message         = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);
            var user            = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>(), AuthenticationType));
            var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(
                message,
                user,
                SecurityTokenService);

            FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(
                responseMessage,
                System.Web.HttpContext.Current.Response);
        }
Example #13
0
        /// <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);
            }
        }
Example #14
0
        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);
        }
        private ActionResult ProcessWSFederationSignIn(SignInRequestMessage message, ClaimsPrincipal principal)
        {
            // issue token and create ws-fed response
            var response = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(
                message,
                principal as ClaimsPrincipal,
                TokenServiceConfiguration.Current.CreateSecurityTokenService());

            // set cookie for single-sign-out
            new SignInSessionsManager(HttpContext, _cookieName, ConfigurationRepository.Global.MaximumTokenLifetime)
            .AddEndpoint(response.BaseUri.AbsoluteUri);

            return(new WSFederationResult(response, requireSsl: ConfigurationRepository.WSFederation.RequireSslForReplyTo));
        }
Example #16
0
        private ActionResult ProcessWSFederationSignIn(SignInRequestMessage message, IPrincipal principal)
        {
            // issue token and create ws-fed response
            var response = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(
                message,
                principal,
                TokenServiceConfiguration.Current.CreateSecurityTokenService());

            // set cookie for single-sign-out
            new SignInSessionsManager(HttpContext, ConfigurationRepository.Configuration.MaximumTokenLifetime)
            .AddRealm(response.BaseUri.AbsoluteUri);

            return(new WSFederationResult(response));
        }
Example #17
0
        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()));
        }
Example #18
0
        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();
            }
        }
Example #20
0
        private string ProcessSignIn(Uri url, ClaimsPrincipal user)
        {
            var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(url);

            //var _signingCreds = new X509SigningCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=localhost"));
            //var _signingCreds = new X509SigningCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=MySTSCert2"));
            var _signingCreds = new X509SigningCredentials(CertificateUtil.GetCertificateFromFile(System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["CertName"])));


            var config = new SecurityTokenServiceConfiguration("http://localhost:5000", _signingCreds);
            var sts    = new CustomSecurityTokenService(config);

            var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, user, sts);

            return(responseMessage.WriteFormPost());
        }
Example #21
0
        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());
        }
Example #22
0
        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));
        }
Example #23
0
        private ActionResult ProcessOAuthResponse(ClaimsPrincipal principal, Context context)
        {
            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);

            return(new WSFederationResult(wsFedResponse, requireSsl: ConfigurationRepository.WSFederation.RequireSslForReplyTo));
        }
Example #24
0
        public bool SignIn()
        {
            try
            {
                SecurityTokenService sts = new TelligentSTS(Configuration);

                var requestMessage  = WSFederationMessage.CreateFromUri(HttpContext.Current.Request.Url) as SignInRequestMessage;
                var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, HttpContext.Current.User, sts);

                FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, HttpContext.Current.Response);
            }
            catch (Exception)
            {
                SPLog.Event("SAML Authentication SignIn failed or FedAuth cookie expired.");
            }

            return(true);
        }
Example #25
0
        private ActionResult ProcessSignIn(SignInRequestMessage signInMsg, ClaimsPrincipal user)
        {
            var config = new EmbeddedTokenServiceConfiguration();
            var sts    = config.CreateSecurityTokenService();

            var appPath = Request.ApplicationPath;

            if (!appPath.EndsWith("/"))
            {
                appPath += "/";
            }

            signInMsg.Reply = new Uri(Request.Url, appPath).AbsoluteUri;
            var response = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(signInMsg, user, sts);

            var body = response.WriteFormPost();

            return(Html(body));
        }
Example #26
0
        /// <summary>
        /// 登录请求处理
        /// </summary>
        /// <param name="url"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        private static string ProcessSignIn(Uri url, ClaimsPrincipal user)
        {
            //创建登录请求消息
            var requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(url);
            //提取证书
            //  var signingCredentials = new X509SigningCredentials(CustomSecurityTokenService.GetCertificate(ConfigurationManager.AppSettings["SigningCertificateName"]));

            // Cache?
            //创建令牌服务配置类
            // var config = new SecurityTokenServiceConfiguration(ConfigurationManager.AppSettings["IssuerName"], signingCredentials);
            ////实例化自定义令牌服务类
            //var sts = new CustomSecurityTokenService(config);
            var sts = CustomSecurityTokenServiceConfiguration.Current.CreateSecurityTokenService();

            //交给真正的登录处理方法(颁发令牌)
            var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, user, sts);

            //得到回复结果
            return(responseMessage.WriteFormPost());
        }
Example #27
0
        private SignInResponseMessage CreateSigninReponseMessage(SignInRequestMessage signInRequestMessage)
        {
            //get from config...
            const string SamlTwoTokenType = "urn:oasis:names:tc:SAML:2.0:assertion";
            const bool   RequireSsl       = false;

            var allowedRpAudiences          = GetAuthorisedAudiencesWeCanIssueTokensTo(signInRequestMessage.Realm);
            var samlTokenSigningCertificate = GetSamlTokenSigningCertificate();
            var stsConfiguration            = configurationFactory.Create(SamlTwoTokenType, "http://sidekick.local/sso/token", samlTokenSigningCertificate, allowedRpAudiences);
            var tokenService = stsConfiguration.CreateSecurityTokenService();

            var signInResponseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(signInRequestMessage,
                                                                                                            ClaimsPrincipal.Current, tokenService);

            this.realmTracker.AddNewRealm(signInRequestMessage.Realm);

            //sanity check
            ValidateRequestIsSsl(RequireSsl, signInRequestMessage);

            return(signInResponseMessage);
        }
        private void ActionSignon()
        {
            var message = (SignInRequestMessage)WSFederationMessage.CreateFromUri(Request.Url);

            var userName = User.Identity.GetUserName();

            var claims = new List <Claim> {
                new Claim(ClaimTypes.Name, userName)
            };

            var principal = new ClaimsPrincipal(new ClaimsIdentity(claims));

            var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(
                message,
                principal,
                SecurityTokenService);

            FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(
                responseMessage,
                System.Web.HttpContext.Current.Response);
        }
Example #29
0
        private ActionResult HandleSignInResponse(string contextId)
        {
            var ctxCookie = this.Request.Cookies[contextId];

            if (ctxCookie == null)
            {
                throw new InvalidOperationException("Context cookie not found");
            }

            var originalRequestUri = new Uri(ctxCookie.Value);

            this.DeleteContextCookie(contextId);

            SignInRequestMessage requestMessage = (SignInRequestMessage)WSFederationMessage.CreateFromUri(originalRequestUri);

            SecurityTokenService  sts             = new FederationSecurityTokenService(SecurityTokenServiceConfiguration <FederationSecurityTokenService> .Current);
            SignInResponseMessage responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, User, sts);

            FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, this.HttpContext.ApplicationInstance.Response);

            return(this.Content(responseMessage.WriteFormPost()));
        }
Example #30
0
        private static string STSResponse(string sharepointUrl, string realm)
        {
            try
            {
                var samlService = ServiceLocator.Get <ISAMLAuthentication>();
                if (samlService == null)
                {
                    return(string.Empty);
                }

                SecurityTokenService sts = new TelligentSTS(samlService.Configuration);

                var requestMessage  = new SignInRequestMessage(new Uri(sharepointUrl), realm);
                var responseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, CurrentPrincipal(), sts);

                return(responseMessage.Result);
            }
            catch (Exception)
            {
                return(string.Empty);
            }
        }