Пример #1
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));
        }
Пример #2
0
        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));
        }
Пример #3
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));
        }
Пример #4
0
        public string Issue(string relayingPartyName, string realm, string userName, string userId)
        {
            if (string.IsNullOrWhiteSpace(relayingPartyName))
            {
                throw new ArgumentNullException("relayingPartyName");
            }

            if (string.IsNullOrWhiteSpace(realm))
            {
                throw new ArgumentNullException("realm");
            }

            if (string.IsNullOrWhiteSpace(userName))
            {
                throw new ArgumentNullException("userName");
            }

            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new ArgumentNullException("userId");
            }

            ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> {
                new Claim(ClaimTypes.Name, userName), new Claim(ClaimTypes.Sid, userId)
            }));

            // Signin message for cross service -> issuer realm == home realm == issuer url
            SignInRequestMessage signInRequestMessage = new SignInRequestMessage(new Uri(realm), realm)
            {
                CurrentTime = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "Z",
                HomeRealm   = realm
            };

            IRelyingParty rp = STSConfiguration <RelyingParty> .Current.RelyingParties.FindByName(relayingPartyName);

            if (rp == null)
            {
                throw new ConfigurationErrorsException(string.Format("Relying party with name {0} was not found", relayingPartyName));
            }

            if (FederatedAuthentication.WSFederationAuthenticationModule == null)
            {
                throw new ConfigurationErrorsException("WSFederationAuthenticationModule was not found");
            }

            var sts = new SimpleSts(rp.GetStsConfiguration());

            SignInResponseMessage signInResponseMessage = FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(signInRequestMessage, principal, sts);



            string tokenXml = signInResponseMessage.Result;

            XmlDocument xml = new XmlDocument();

            xml.LoadXml(tokenXml);

            string xmlSecurityToken = xml.DocumentElement.GetElementsByTagName("trust:RequestedSecurityToken").Item(0).InnerXml; // <Assertion>



            //WSFederationSerializer ser = new WSFederationSerializer();

            //GenericXmlSecurityToken xmlt = new GenericXmlSecurityToken()


            //string xmlSecurityToken = FederatedAuthentication.WSFederationAuthenticationModule.GetXmlTokenFromMessage(signInResponseMessage);

            var xmlSecurityTokenBase64Encoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(xmlSecurityToken));

            return(xmlSecurityTokenBase64Encoded);
        }
Пример #5
0
        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)));
            }
        }