Exemple #1
0
        public async Task UserSetupUrl()
        {
            // Construct a V1 immediate request
            Protocol       protocol         = Protocol.V11;
            OpenIdProvider provider         = this.CreateProvider();
            var            immediateRequest = new CheckIdRequest(protocol.Version, OPUri, DotNetOpenAuth.OpenId.AuthenticationRequestMode.Immediate);

            immediateRequest.Realm           = RPRealmUri;
            immediateRequest.ReturnTo        = RPUri;
            immediateRequest.LocalIdentifier = "http://somebody";
            var request = new AuthenticationRequest(provider, immediateRequest);

            // Now simulate the request being rejected and extract the user_setup_url
            request.IsAuthenticated = false;
            Uri userSetupUrl = ((NegativeAssertionResponse)await request.GetResponseAsync(CancellationToken.None)).UserSetupUrl;

            Assert.IsNotNull(userSetupUrl);

            // Now construct a new request as if it had just come in.
            var httpRequest  = new HttpRequestMessage(HttpMethod.Get, userSetupUrl);
            var setupRequest = (AuthenticationRequest)await provider.GetRequestAsync(httpRequest);

            var setupRequestMessage = (CheckIdRequest)setupRequest.RequestMessage;

            // And make sure all the right properties are set.
            Assert.IsFalse(setupRequestMessage.Immediate);
            Assert.AreEqual(immediateRequest.Realm, setupRequestMessage.Realm);
            Assert.AreEqual(immediateRequest.ReturnTo, setupRequestMessage.ReturnTo);
            Assert.AreEqual(immediateRequest.LocalIdentifier, setupRequestMessage.LocalIdentifier);
            Assert.AreEqual(immediateRequest.Version, setupRequestMessage.Version);
        }
        public void RelyingPartyVersion()
        {
            Protocol      simulatedVersion = Protocol.v11;
            UriIdentifier id = TestSupport.GetIdentityUrl(TestSupport.Scenarios.AutoApproval, simulatedVersion.ProtocolVersion);

            // make up some OpenID 1.x looking message...
            NameValueCollection rp10Request = new NameValueCollection();

            rp10Request[simulatedVersion.openid.mode]      = simulatedVersion.Args.Mode.checkid_immediate;
            rp10Request[simulatedVersion.openid.identity]  = id;
            rp10Request[simulatedVersion.openid.return_to] = TestSupport.ReturnTo.AbsoluteUri;
            rp10Request[simulatedVersion.openid.Realm]     = TestSupport.Realm;

            OpenIdProvider op = TestSupport.CreateProvider(rp10Request);

            Assert.AreEqual(simulatedVersion.ProtocolVersion,
                            ((DotNetOpenId.Provider.IAuthenticationRequest)op.Request).RelyingPartyVersion);

            // Verify V2.0 reporting.
            var rp20Request = TestSupport.CreateRelyingPartyRequest(true, TestSupport.Scenarios.AutoApproval, ProtocolVersion.V20);

            TestSupport.CreateRelyingPartyResponseThroughProvider(rp20Request, opReq => {
                Assert.AreEqual(ProtocolVersion.V20, opReq.RelyingPartyVersion);
                opReq.IsAuthenticated = true;
            });
        }
Exemple #3
0
        public void UserSetupUrl()
        {
            // Construct a V1 immediate request
            Protocol       protocol         = Protocol.V11;
            OpenIdProvider provider         = this.CreateProvider();
            CheckIdRequest immediateRequest = new CheckIdRequest(protocol.Version, OPUri, DotNetOpenAuth.OpenId.RelyingParty.AuthenticationRequestMode.Immediate);

            immediateRequest.Realm           = RPRealmUri;
            immediateRequest.ReturnTo        = RPUri;
            immediateRequest.LocalIdentifier = "http://somebody";
            AuthenticationRequest request = new AuthenticationRequest(provider, immediateRequest);

            // Now simulate the request being rejected and extract the user_setup_url
            request.IsAuthenticated = false;
            Uri userSetupUrl = ((NegativeAssertionResponse)request.Response).UserSetupUrl;

            Assert.IsNotNull(userSetupUrl);

            // Now construct a new request as if it had just come in.
            HttpRequestInfo httpRequest = new HttpRequestInfo {
                UrlBeforeRewriting = userSetupUrl
            };
            var setupRequest = AuthenticationRequest_Accessor.AttachShadow(provider.GetRequest(httpRequest));
            CheckIdRequest_Accessor setupRequestMessage = setupRequest.RequestMessage;

            // And make sure all the right properties are set.
            Assert.IsFalse(setupRequestMessage.Immediate);
            Assert.AreEqual(immediateRequest.Realm, setupRequestMessage.Realm);
            Assert.AreEqual(immediateRequest.ReturnTo, setupRequestMessage.ReturnTo);
            Assert.AreEqual(immediateRequest.LocalIdentifier, setupRequestMessage.LocalIdentifier);
            Assert.AreEqual(immediateRequest.Version, setupRequestMessage.Version);
        }
Exemple #4
0
        public async Task UnsolicitedAssertion()
        {
            var opStore = new MemoryCryptoKeyAndNonceStore();

            Handle(RPUri).By(
                async req => {
                var rp = new OpenIdRelyingParty(new MemoryCryptoKeyAndNonceStore(), this.HostFactories);
                IAuthenticationResponse response = await rp.GetResponseAsync(req);
                Assert.That(response, Is.Not.Null);
                Assert.AreEqual(AuthenticationStatus.Authenticated, response.Status);
                return(new HttpResponseMessage());
            });
            Handle(OPUri).By(
                async(req, ct) => {
                var op = new OpenIdProvider(opStore, this.HostFactories);
                return(await this.AutoProviderActionAsync(op, req, ct));
            });
            this.RegisterMockRPDiscovery(ssl: false);

            {
                var        op        = new OpenIdProvider(opStore, this.HostFactories);
                Identifier id        = GetMockIdentifier(ProtocolVersion.V20);
                var        assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]);

                using (var httpClient = this.HostFactories.CreateHttpClient()) {
                    using (var response = await httpClient.GetAsync(assertion.Headers.Location)) {
                        response.EnsureSuccessStatusCode();
                    }
                }
            }
        }
        public void RequestNullOnEmptyRequest()
        {
            OpenIdProvider op = new OpenIdProvider(new ProviderMemoryStore(),
                                                   providerEndpoint, emptyRequestUrl, new NameValueCollection());

            Assert.IsNull(op.Request);
        }
Exemple #6
0
        public async Task AssertionWithEndpointFilter()
        {
            var opStore = new MemoryCryptoKeyAndNonceStore();

            Handle(RPUri).By(
                async req => {
                var rp = new OpenIdRelyingParty(new MemoryCryptoKeyAndNonceStore(), this.HostFactories);

                // Rig it to always deny the incoming OP
                rp.EndpointFilter = op => false;

                // Receive the unsolicited assertion
                var response = await rp.GetResponseAsync(req);
                Assert.That(response, Is.Not.Null);
                Assert.AreEqual(AuthenticationStatus.Failed, response.Status);
                return(new HttpResponseMessage());
            });
            this.RegisterAutoProvider();
            {
                var        op        = new OpenIdProvider(opStore, this.HostFactories);
                Identifier id        = GetMockIdentifier(ProtocolVersion.V20);
                var        assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, GetMockRealm(false), id, id);

                using (var httpClient = this.HostFactories.CreateHttpClient()) {
                    using (var response = await httpClient.GetAsync(assertion.Headers.Location)) {
                        response.EnsureSuccessStatusCode();
                    }
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Creates a standard <see cref="OpenIdProvider"/> instance for general testing.
        /// </summary>
        /// <returns>The new instance.</returns>
        protected OpenIdProvider CreateProvider()
        {
            var op = new OpenIdProvider(new StandardProviderApplicationStore());

            op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler;
            op.DiscoveryServices.Add(new MockIdentifierDiscoveryService());
            return(op);
        }
Exemple #8
0
 /// <summary>
 /// Gets a default implementation of a simple provider that responds to authentication requests
 /// per the scenario that is being simulated.
 /// </summary>
 /// <remarks>
 /// This is a very useful method to pass to the OpenIdCoordinator constructor for the Provider argument.
 /// </remarks>
 internal void RegisterAutoProvider()
 {
     this.Handle(OPUri).By(
         async(req, ct) => {
         var provider = new OpenIdProvider(new MemoryCryptoKeyAndNonceStore(), this.HostFactories);
         return(await this.AutoProviderActionAsync(provider, req, ct));
     });
 }
        public async Task ExtensionsAreIdentifiedAsSignedOrUnsigned()
        {
            Protocol protocol = Protocol.Default;
            var      opStore  = new MemoryCryptoKeyAndNonceStore();
            int      rpStep   = 0;

            Handle(RPUri).By(
                async req => {
                var rp = new OpenIdRelyingParty(new MemoryCryptoKeyAndNonceStore(), this.HostFactories);
                RegisterMockExtension(rp.Channel);

                switch (++rpStep)
                {
                case 1:
                    var response = await rp.Channel.ReadFromRequestAsync <IndirectSignedResponse>(req, CancellationToken.None);
                    Assert.AreEqual(1, response.SignedExtensions.Count(), "Signed extension should have been received.");
                    Assert.AreEqual(0, response.UnsignedExtensions.Count(), "No unsigned extension should be present.");
                    break;

                case 2:
                    response = await rp.Channel.ReadFromRequestAsync <IndirectSignedResponse>(req, CancellationToken.None);
                    Assert.AreEqual(0, response.SignedExtensions.Count(), "No signed extension should have been received.");
                    Assert.AreEqual(1, response.UnsignedExtensions.Count(), "Unsigned extension should have been received.");
                    break;

                default:
                    throw Assumes.NotReachable();
                }

                return(new HttpResponseMessage());
            });
            Handle(OPUri).By(
                async req => {
                var op = new OpenIdProvider(opStore, this.HostFactories);
                return(await AutoProviderActionAsync(op, req, CancellationToken.None));
            });

            {
                var op = new OpenIdProvider(opStore, this.HostFactories);
                RegisterMockExtension(op.Channel);
                var redirectingResponse = await op.Channel.PrepareResponseAsync(this.CreateResponseWithExtensions(protocol));

                using (var httpClient = this.HostFactories.CreateHttpClient()) {
                    using (var response = await httpClient.GetAsync(redirectingResponse.Headers.Location)) {
                        response.EnsureSuccessStatusCode();
                    }
                }

                op.SecuritySettings.SignOutgoingExtensions = false;
                redirectingResponse = await op.Channel.PrepareResponseAsync(this.CreateResponseWithExtensions(protocol));

                using (var httpClient = this.HostFactories.CreateHttpClient()) {
                    using (var response = await httpClient.GetAsync(redirectingResponse.Headers.Location)) {
                        response.EnsureSuccessStatusCode();
                    }
                }
            }
        }
Exemple #10
0
        public static void Register(OpenIdProvider provider)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            provider.ExtensionFactories.Add(new Acme());
        }
Exemple #11
0
    internal static OpenIdProvider CreateProvider(NameValueCollection fields, bool useSsl)
    {
        Protocol protocol = fields != null?Protocol.Detect(fields.ToDictionary()) : Protocol.v20;

        Uri opEndpoint = GetFullUrl(ProviderPage, null, useSsl);
        var provider   = new OpenIdProvider(ProviderStore, opEndpoint, opEndpoint, fields ?? new NameValueCollection());

        return(provider);
    }
Exemple #12
0
        /// <summary>
        /// Gets the URL of the RP icon for the OP to display.
        /// </summary>
        /// <param name="realm">The realm of the RP where the authentication request originated.</param>
        /// <param name="provider">The Provider instance used to obtain the authentication request.</param>
        /// <returns>
        /// A sequence of the RP's icons it has available for the Provider to display, in decreasing preferred order.
        /// </returns>
        /// <value>The icon URL.</value>
        /// <remarks>
        /// This property is automatically set for the OP with the result of RP discovery.
        /// RPs should set this value by including an entry such as this in their XRDS document.
        /// <example>
        /// &lt;Service xmlns="xri://$xrd*($v*2.0)"&gt;
        /// &lt;Type&gt;http://specs.openid.net/extensions/ui/icon&lt;/Type&gt;
        /// &lt;URI&gt;http://consumer.example.com/images/image.jpg&lt;/URI&gt;
        /// &lt;/Service&gt;
        /// </example>
        /// </remarks>
        public static IEnumerable <Uri> GetRelyingPartyIconUrls(Realm realm, OpenIdProvider provider)
        {
            Contract.Requires(realm != null);
            Contract.Requires(provider != null);
            ErrorUtilities.VerifyArgumentNotNull(realm, "realm");
            ErrorUtilities.VerifyArgumentNotNull(provider, "provider");

            return(GetRelyingPartyIconUrls(realm, provider.Channel.WebRequestHandler));
        }
Exemple #13
0
    internal static OpenIdProvider CreateProviderForRequest(DotNetOpenId.RelyingParty.IAuthenticationRequest request)
    {
        IResponse relyingPartyAuthenticationRequest = request.RedirectingResponse;
        var       rpWebMessageToOP = (Response)relyingPartyAuthenticationRequest;
        var       rpMessageToOP    = (IndirectMessageRequest)rpWebMessageToOP.EncodableMessage;
        var       opEndpoint       = (ServiceEndpoint)request.Provider;
        var       provider         = new OpenIdProvider(ProviderStore, opEndpoint.ProviderEndpoint,
                                                        opEndpoint.ProviderEndpoint, rpMessageToOP.EncodedFields.ToNameValueCollection());

        return(provider);
    }
Exemple #14
0
        public override void SetUp()
        {
            base.SetUp();

            this.protocol                = Protocol.Default;
            this.provider                = this.CreateProvider();
            this.checkIdRequest          = new CheckIdRequest(this.protocol.Version, OPUri, AuthenticationRequestMode.Setup);
            this.checkIdRequest.Realm    = RPRealmUri;
            this.checkIdRequest.ReturnTo = RPUri;
            this.request = new AuthenticationRequest(this.provider, this.checkIdRequest);
        }
        public IDictionary <string, string> SendDirectMessageAndGetResponse(ServiceEndpoint providerEndpoint, IDictionary <string, string> fields)
        {
            OpenIdProvider provider = new OpenIdProvider(providerStore, providerEndpoint.ProviderEndpoint,
                                                         providerEndpoint.ProviderEndpoint, fields.ToNameValueCollection());

            Debug.Assert(provider.Request.IsResponseReady, "Direct messages should always have an immediately available response.");
            Response          webResponse    = (Response)provider.Request.Response;
            EncodableResponse opAuthResponse = (EncodableResponse)webResponse.EncodableMessage;

            return(opAuthResponse.EncodedFields);
        }
        public void BasicUnsolicitedAssertion()
        {
            Mocks.MockHttpRequest.RegisterMockRPDiscovery();
            TestSupport.Scenarios scenario  = TestSupport.Scenarios.AutoApproval;
            Identifier            claimedId = TestSupport.GetMockIdentifier(scenario, ProtocolVersion.V20);
            Identifier            localId   = TestSupport.GetDelegateUrl(scenario);

            OpenIdProvider op         = TestSupport.CreateProvider(null);
            IResponse      assertion  = op.PrepareUnsolicitedAssertion(TestSupport.Realm, claimedId, localId);
            var            rpResponse = TestSupport.CreateRelyingPartyResponse(TestSupport.RelyingPartyStore, assertion);

            Assert.AreEqual(AuthenticationStatus.Authenticated, rpResponse.Status);
            Assert.AreEqual(claimedId, rpResponse.ClaimedIdentifier);
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        TestSupport.Scenarios scenario         = (TestSupport.Scenarios)Enum.Parse(typeof(TestSupport.Scenarios), Request.QueryString["user"]);
        UriBuilder            providerEndpoint = new UriBuilder(Request.Url);

        providerEndpoint.Query = "user="******"GET" ? Request.QueryString : Request.Form);

        if (provider.Request != null)
        {
            if (!provider.Request.IsResponseReady)
            {
                var idreq = provider.Request as IAuthenticationRequest;
                idreq.ClaimedIdentifier = new Uri(Request.Url, Page.ResolveUrl("~/DirectedIdentityEndpoint.aspx?user="******"&version=" + ProtocolVersion.V20));

                switch (scenario)
                {
                case TestSupport.Scenarios.AutoApproval:
                    // immediately approve
                    idreq.IsAuthenticated = true;
                    break;

                case TestSupport.Scenarios.AutoApprovalAddFragment:
                    idreq.SetClaimedIdentifierFragment("frag");
                    idreq.IsAuthenticated = true;
                    break;

                case TestSupport.Scenarios.ApproveOnSetup:
                    idreq.IsAuthenticated = !idreq.Immediate;
                    break;

                case TestSupport.Scenarios.AlwaysDeny:
                    idreq.IsAuthenticated = false;
                    break;

                case TestSupport.Scenarios.ExtensionFullCooperation:
                case TestSupport.Scenarios.ExtensionPartialCooperation:
                    throw new NotImplementedException();

                //idreq.IsAuthenticated = true;
                //break;
                default:
                    throw new InvalidOperationException("Unrecognized scenario");
                }
            }
            provider.Request.Response.Send();
        }
    }
        public void UnsolicitedAssertionWithBadCapitalization()
        {
            Mocks.MockHttpRequest.RegisterMockRPDiscovery();
            TestSupport.Scenarios scenario  = TestSupport.Scenarios.AutoApproval;
            Identifier            claimedId = TestSupport.GetMockIdentifier(scenario, ProtocolVersion.V20);

            claimedId = claimedId.ToString().ToUpper();             // make all caps, which is not right
            Identifier localId = TestSupport.GetDelegateUrl(scenario);

            OpenIdProvider op         = TestSupport.CreateProvider(null);
            IResponse      assertion  = op.PrepareUnsolicitedAssertion(TestSupport.Realm, claimedId, localId);
            var            rpResponse = TestSupport.CreateRelyingPartyResponse(TestSupport.RelyingPartyStore, assertion);

            Assert.AreEqual(AuthenticationStatus.Failed, rpResponse.Status);
        }
Exemple #19
0
        private void SendAssertion(string relyingPartyRealm)
        {
            Uri            providerEndpoint = new Uri(Request.Url, Page.ResolveUrl("~/server.aspx"));
            OpenIdProvider op = new OpenIdProvider();

            try {
                // Send user input through identifier parser so we accept more free-form input.
                string rpSite = Identifier.Parse(relyingPartyRealm);
                op.PrepareUnsolicitedAssertion(providerEndpoint, rpSite, Util.BuildIdentityUrl(), Util.BuildIdentityUrl()).Send();
            } catch (ProtocolException ex) {
                Label errorLabel = (Label)this.loginView.FindControl("errorLabel");
                errorLabel.Visible = true;
                errorLabel.Text    = ex.Message;
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CheckAuthenticationResponse"/> class
        /// for use by the Provider.
        /// </summary>
        /// <param name="request">The request that this message is responding to.</param>
        /// <param name="provider">The OpenID Provider that is preparing to send this response.</param>
        internal CheckAuthenticationResponse(CheckAuthenticationRequest request, OpenIdProvider provider)
            : base(request.Version, request)
        {
            ErrorUtilities.VerifyArgumentNotNull(provider, "provider");

            // The channel's binding elements have already set the request's IsValid property
            // appropriately.  We just copy it into the response message.
            this.IsValid = request.IsValid;

            // Confirm the RP should invalidate the association handle only if the association
            // really doesn't exist.  OpenID 2.0 section 11.4.2.2.
            IndirectSignedResponse signedResponse = new IndirectSignedResponse(request);
            string invalidateHandle = ((ITamperResistantOpenIdMessage)signedResponse).InvalidateHandle;

            if (invalidateHandle != null && provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, invalidateHandle) == null)
            {
                this.InvalidateHandle = invalidateHandle;
            }
        }
Exemple #21
0
        public void ProcessRequest(HttpContext context)
        {
            OpenIdProvider provider = new OpenIdProvider();

            if (provider.Request != null)
            {
                // Some OpenID requests are automatable and can be responded to immediately.
                if (!provider.Request.IsResponseReady)
                {
                    // But authentication requests cannot be responded to until something on
                    // this site decides whether to approve or disapprove the authentication.
                    var idrequest = (IAuthenticationRequest)provider.Request;
                    // We store the authentication request in the user's session so that
                    // redirects and user prompts can appear and eventually some page can decide
                    // to respond to the OpenID authentication request either affirmatively or
                    // negatively.
                    ProviderEndpoint.PendingAuthenticationRequest = idrequest;
                    // We delegate that approval process to our utility method that we share
                    // with our other Provider sample page server.aspx.
                    Util.ProcessAuthenticationChallenge(idrequest);
                    // As part of authentication approval, the user may need to authenticate
                    // to this Provider and/or decide whether to allow the requesting RP site
                    // to log this user in.  If any UI needs to be presented to the user,
                    // the previous call to ProcessAuthenticationChallenge MAY not return
                    // due to a redirect to some ASPX page.
                }
                else
                {
                    // Some other automatable OpenID request is coming down, so clear
                    // any previously session stored authentication request that might be
                    // stored for this user.
                    ProviderEndpoint.PendingAuthenticationRequest = null;
                }
                // Whether this was an automated message or an authentication message,
                // if there is a response ready to send back immediately, do so.
                if (provider.Request.IsResponseReady)
                {
                    provider.Request.Response.Send();
                    ProviderEndpoint.PendingAuthenticationRequest = null;
                }
            }
        }
Exemple #22
0
        public void Serializable()
        {
            OpenIdProvider provider         = this.CreateProvider();
            CheckIdRequest immediateRequest = new CheckIdRequest(Protocol.Default.Version, OPUri, DotNetOpenAuth.OpenId.AuthenticationRequestMode.Immediate);

            immediateRequest.Realm           = RPRealmUri;
            immediateRequest.ReturnTo        = RPUri;
            immediateRequest.LocalIdentifier = "http://somebody";
            AuthenticationRequest request = new AuthenticationRequest(provider, immediateRequest);

            MemoryStream ms        = new MemoryStream();
            IFormatter   formatter = new BinaryFormatter();

            formatter.Serialize(ms, request);

            ms.Position = 0;
            var req2 = (AuthenticationRequest)formatter.Deserialize(ms);

            Assert.That(req2, Is.Not.Null);
        }
Exemple #23
0
        /// <summary>
        /// A default implementation of a simple provider that responds to authentication requests
        /// per the scenario that is being simulated.
        /// </summary>
        /// <param name="provider">The OpenIdProvider on which the process messages.</param>
        /// <remarks>
        /// This is a very useful method to pass to the OpenIdCoordinator constructor for the Provider argument.
        /// </remarks>
        internal void AutoProvider(OpenIdProvider provider)
        {
            while (!((CoordinatingChannel)provider.Channel).RemoteChannel.IsDisposed)
            {
                IRequest request = provider.GetRequest();
                if (request == null)
                {
                    continue;
                }

                if (!request.IsResponseReady)
                {
                    var authRequest = (DotNetOpenAuth.OpenId.Provider.IAuthenticationRequest)request;
                    switch (this.AutoProviderScenario)
                    {
                    case Scenarios.AutoApproval:
                        authRequest.IsAuthenticated = true;
                        break;

                    case Scenarios.AutoApprovalAddFragment:
                        authRequest.SetClaimedIdentifierFragment("frag");
                        authRequest.IsAuthenticated = true;
                        break;

                    case Scenarios.ApproveOnSetup:
                        authRequest.IsAuthenticated = !authRequest.Immediate;
                        break;

                    case Scenarios.AlwaysDeny:
                        authRequest.IsAuthenticated = false;
                        break;

                    default:
                        // All other scenarios are done programmatically only.
                        throw new InvalidOperationException("Unrecognized scenario");
                    }
                }

                provider.SendResponse(request);
            }
        }
Exemple #24
0
        /// <summary>
        /// Gets a default implementation of a simple provider that responds to authentication requests
        /// per the scenario that is being simulated.
        /// </summary>
        /// <remarks>
        /// This is a very useful method to pass to the OpenIdCoordinator constructor for the Provider argument.
        /// </remarks>
        internal async Task <HttpResponseMessage> AutoProviderActionAsync(OpenIdProvider provider, HttpRequestMessage req, CancellationToken ct)
        {
            IRequest request = await provider.GetRequestAsync(req, ct);

            Assert.That(request, Is.Not.Null);

            if (!request.IsResponseReady)
            {
                var authRequest = (IAuthenticationRequest)request;
                switch (this.AutoProviderScenario)
                {
                case Scenarios.AutoApproval:
                    authRequest.IsAuthenticated = true;
                    break;

                case Scenarios.AutoApprovalAddFragment:
                    authRequest.SetClaimedIdentifierFragment("frag");
                    authRequest.IsAuthenticated = true;
                    break;

                case Scenarios.ApproveOnSetup:
                    authRequest.IsAuthenticated = !authRequest.Immediate;
                    break;

                case Scenarios.AlwaysDeny:
                    authRequest.IsAuthenticated = false;
                    break;

                default:
                    // All other scenarios are done programmatically only.
                    throw new InvalidOperationException("Unrecognized scenario");
                }
            }

            return(await provider.PrepareResponseAsync(request, ct));
        }
Exemple #25
0
 public override void SetUp()
 {
     base.SetUp();
     SuspendLogging();
     this.provider = CreateProvider();
 }
        public override void SetUp()
        {
            base.SetUp();

            this.provider = this.CreateProvider();
        }
Exemple #27
0
        /// <summary>
        /// Handles all GET and POST requests for OpenID identifier pages and endpoint
        /// server communication
        /// </summary>
        protected override void ProcessRequest(
            string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
        {
            Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath));

            // Defult to returning HTML content
            httpResponse.ContentType = ContentType;

            try
            {
                string forPost;
                using (StreamReader sr = new StreamReader(httpRequest.InputStream))
                    forPost = sr.ReadToEnd();
                NameValueCollection postQuery   = HttpUtility.ParseQueryString(forPost);
                NameValueCollection getQuery    = HttpUtility.ParseQueryString(httpRequest.Url.Query);
                NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery);

                OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery);

                if (provider.Request != null)
                {
                    if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest)
                    {
                        IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request;
                        string[] passwordValues            = postQuery.GetValues("pass");

                        UserAccount account;
                        if (TryGetAccount(new Uri(authRequest.ClaimedIdentifier.ToString()), out account))
                        {
                            // Check for form POST data
                            if (passwordValues != null && passwordValues.Length == 1)
                            {
                                if (account != null &&
                                    (m_authenticationService.Authenticate(account.PrincipalID, Util.Md5Hash(passwordValues[0]), 30) != string.Empty))
                                {
                                    authRequest.IsAuthenticated = true;
                                }
                                else
                                {
                                    authRequest.IsAuthenticated = false;
                                }
                            }
                            else
                            {
                                // Authentication was requested, send the client a login form
                                using (StreamWriter writer = new StreamWriter(response))
                                    writer.Write(String.Format(LOGIN_PAGE, account.FirstName, account.LastName));
                                return;
                            }
                        }
                        else
                        {
                            // Cannot find an avatar matching the claimed identifier
                            authRequest.IsAuthenticated = false;
                        }
                    }

                    // Add OpenID headers to the response
                    foreach (string key in provider.Request.Response.Headers.Keys)
                    {
                        httpResponse.AddHeader(key, provider.Request.Response.Headers[key]);
                    }

                    string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type");
                    if (contentTypeValues != null && contentTypeValues.Length == 1)
                    {
                        httpResponse.ContentType = contentTypeValues[0];
                    }

                    // Set the response code and document body based on the OpenID result
                    httpResponse.StatusCode = (int)provider.Request.Response.Code;
                    response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length);
                    response.Close();
                }
                else if (httpRequest.Url.AbsolutePath.Contains("/openid/server"))
                {
                    // Standard HTTP GET was made on the OpenID endpoint, send the client the default error page
                    using (StreamWriter writer = new StreamWriter(response))
                        writer.Write(ENDPOINT_PAGE);
                }
                else
                {
                    // Try and lookup this avatar
                    UserAccount account;
                    if (TryGetAccount(httpRequest.Url, out account))
                    {
                        using (StreamWriter writer = new StreamWriter(response))
                        {
                            // TODO: Print out a full profile page for this avatar
                            writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme,
                                                       httpRequest.Url.Authority, account.FirstName, account.LastName));
                        }
                    }
                    else
                    {
                        // Couldn't parse an avatar name, or couldn't find the avatar in the user server
                        using (StreamWriter writer = new StreamWriter(response))
                            writer.Write(INVALID_OPENID_PAGE);
                    }
                }
            }
            catch (Exception ex)
            {
                httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
                using (StreamWriter writer = new StreamWriter(response))
                    writer.Write(ex.Message);
            }
        }
            public void GivenAValidHttpOpenIdIdentifier_RedirectToAuthenticate_ReturnsAValidEndPoint()
            {
                // Arrange.
                const string xrdsLocation = "https://www.myopenid.com/xrds";

                // 302 Redirect :P
                var mockRestResponseRedirect = new Mock<IRestResponse>();
                mockRestResponseRedirect.Setup(x => x.StatusCode).Returns(HttpStatusCode.Redirect);
                mockRestResponseRedirect.Setup(x => x.Headers)
                                        .Returns(new List<Parameter>
                                        {
                                            new Parameter
                                            {
                                                Name = "Location",
                                                Type = ParameterType.HttpHeader,
                                                Value = "https://myopenid.com/"
                                            }
                                        });
                var mockRestClientRedirect = new Mock<IRestClient>();
                mockRestClientRedirect.Setup(x => x.BaseUrl).Returns("http://myopenId.com/");
                mockRestClientRedirect.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                                      .Returns(mockRestResponseRedirect.Object);

                // 200 OK with the Xrds location.
                var mockRestResponseOk = new Mock<IRestResponse>();
                mockRestResponseOk.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponseOk.Setup(x => x.Headers)
                                  .Returns(new List<Parameter>
                                  {
                                      new Parameter
                                      {
                                          Name = "X-XRDS-Location",
                                          Type = ParameterType.HttpHeader,
                                          Value = xrdsLocation
                                      }
                                  });
                var mockRestClientOk = new Mock<IRestClient>();
                mockRestClientOk.Setup(x => x.BaseUrl).Returns("https://myopenId.com/");
                mockRestClientOk.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                                .Returns(mockRestResponseOk.Object);


                const string yahooXrdsXml =
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xrds:XRDS    xmlns:xrds=\"xri://$xrds\" xmlns:openid=\"http://openid.net/xmlns/1.0\" xmlns=\"xri://$xrd*($v*2.0)\"><XRD><Service priority=\"0\"><Type>http://specs.openid.net/auth/2.0/server</Type><Type>http://specs.openid.net/extensions/pape/1.0</Type><Type>http://openid.net/srv/ax/1.0</Type><Type>http://specs.openid.net/extensions/oauth/1.0</Type><Type>http://specs.openid.net/extensions/ui/1.0/lang-pref</Type><Type>http://specs.openid.net/extensions/ui/1.0/mode/popup</Type><Type>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier</Type><Type>http://www.idmanagement.gov/schema/2009/05/icam/no-pii.pdf</Type><Type>http://www.idmanagement.gov/schema/2009/05/icam/openid-trust-level1.pdf</Type><Type>http://csrc.nist.gov/publications/nistpubs/800-63/SP800-63V1_0_2.pdf</Type><URI>https://open.login.yahooapis.com/openid/op/auth</URI></Service></XRD></xrds:XRDS>";
                const string myOpenIdXrdsXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xrds:XRDS xmlns:xrds=\"xri://$xrds\" xmlns:ux=\"http://specs.openid.net/extensions/ux/1.0\" xmlns=\"xri://$xrd*($v*2.0)\"> <XRD> <Service priority=\"0\"><Type>http://specs.openid.net/auth/2.0/server</Type><Type>http://openid.net/sreg/1.0</Type><URI priority=\"0\">https://www.myopenid.com/server</URI></Service><Service><Type>http://specs.openid.net/extensions/ux/1.0/friendlyname</Type><ux:friendlyname>MyOpenID</ux:friendlyname></Service><Service><Type>http://specs.openid.net/extensions/ux/1.0/img</Type><ux:img url=\"https://www.myopenid.com/static/images/myopenid_selector.png\" width=\"48\" height=\"48\"></ux:img></Service></XRD></xrds:XRDS>";
                var mockRestResponseXrds = new Mock<IRestResponse>();
                mockRestResponseXrds.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK);
                mockRestResponseXrds.Setup(x => x.Content).Returns(myOpenIdXrdsXml);

                var mockRestClientXrds = new Mock<IRestClient>();
                mockRestClientXrds.Setup(x => x.BaseUrl).Returns(xrdsLocation);
                mockRestClientXrds.Setup(x => x.Execute(It.IsAny<IRestRequest>()))
                                  .Returns(mockRestResponseXrds.Object);

                var mockRestClients = new List<IRestClient>
                                      {
                                          mockRestClientRedirect.Object,
                                          mockRestClientOk.Object,
                                          mockRestClientXrds.Object
                                      };
                var openIdProvider = new OpenIdProvider
                {
                    RestClientFactory = new RestClientFactory(mockRestClients)
                };
                var authenticationServiceSettings = new OpenIdAuthenticationServiceSettings
                {
                    Identifier = new Uri("http://myopenId.com/"),
                    CallBackUri = new Uri("http://whatever.com:9999")
                };
                
                
                // Act.
                var result = openIdProvider.RedirectToAuthenticate(authenticationServiceSettings);

                // Assert.
                Assert.NotNull(result);
                Assert.Equal("https://www.myopenid.com/server?openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.mode=checkid_setup&openid.ns=http://specs.openid.net/auth/2.0&openid.ns.sreg=http://openid.net/extensions/sreg/1.1&openid.sreg.required=nickname&openid.sreg.optional=email,fullname,gender,language&no_ssl=true&openid.return_to=http://whatever.com:9999/&openid.realm=http://whatever.com:9999/",
                    result.AbsoluteUri);
            }
 public void CtorNullStore()
 {
     OpenIdProvider op = new OpenIdProvider(null, providerEndpoint,
                                            emptyRequestUrl, new NameValueCollection());
 }
 public void CtorNullQuery()
 {
     OpenIdProvider op = new OpenIdProvider(new ProviderMemoryStore(),
                                            providerEndpoint, emptyRequestUrl, null);
 }
 public void CtorNullRequestUrl()
 {
     OpenIdProvider op = new OpenIdProvider(new ProviderMemoryStore(),
                                            providerEndpoint, null, new NameValueCollection());
 }