Пример #1
0
        public async Task <ActionResult> Provider()
        {
            IRequest request = await OpenIdProvider.GetRequestAsync(this.Request, this.Response.ClientDisconnectedToken);

            if (request == null)
            {
                return(View());
            }
            if (request.IsResponseReady)
            {
                var response = await OpenIdProvider.PrepareResponseAsync(request, this.Response.ClientDisconnectedToken);

                Response.ContentType = response.Content.Headers.ContentType.ToString();
                return(response.AsActionResult());
            }
            //缓存在cache 中
            ProviderEndpoint.PendingRequest = (IHostProcessedRequest)request;
            //查找pape 扩展信息
            var papeRequest = ProviderEndpoint.PendingRequest.GetExtension <PolicyRequest>();

            if (papeRequest != null && papeRequest.MaximumAuthenticationAge.HasValue)
            {
                TimeSpan timeSinceLogin = DateTime.UtcNow - (this._formsAuth.SignedInTimestampUtc ?? DateTime.UtcNow);
                if (timeSinceLogin > papeRequest.MaximumAuthenticationAge.Value)
                {
                    return(this.RedirectToAction("LogOn", "Account", new { returnUrl = this.Url.Action("ProcessAuthRequest") }));
                }
            }
            return(await this.ProcessAuthRequest());
        }
Пример #2
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);
        }
Пример #3
0
        public async Task <ActionResult> Provider()
        {
            IRequest request = await OpenIdProvider.GetRequestAsync(this.Request, this.Response.ClientDisconnectedToken);

            if (request != null)
            {
                // Some requests are automatically handled by DotNetOpenAuth.  If this is one, go ahead and let it go.
                if (request.IsResponseReady)
                {
                    var response = await OpenIdProvider.PrepareResponseAsync(request, this.Response.ClientDisconnectedToken);

                    return(response.AsActionResult());
                }

                // This is apparently one that the host (the web site itself) has to respond to.
                ProviderEndpoint.PendingRequest = (IHostProcessedRequest)request;

                // If PAPE requires that the user has logged in recently, we may be required to challenge the user to log in.
                var papeRequest = ProviderEndpoint.PendingRequest.GetExtension <PolicyRequest>();
                if (papeRequest != null && papeRequest.MaximumAuthenticationAge.HasValue)
                {
                    var signedInTimestampUtc = this.FormsAuth.SignedInTimestampUtc;
                    if (signedInTimestampUtc != null)
                    {
                        TimeSpan timeSinceLogin = DateTime.UtcNow - signedInTimestampUtc.Value;
                        if (timeSinceLogin > papeRequest.MaximumAuthenticationAge.Value)
                        {
                            // The RP wants the user to have logged in more recently than he has.
                            // We'll have to redirect the user to a login screen.
                            return(this.RedirectToAction("LogOn", "Account", new { returnUrl = this.Url.Action("ProcessAuthRequest") }));
                        }
                    }
                }

                return(await this.ProcessAuthRequest());
            }

            // No OpenID request was recognized.  This may be a user that stumbled on the OP Endpoint.
            return(this.View());
        }
Пример #4
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));
        }
Пример #5
0
        private async Task <HttpResponseMessage> HandleAsync()
        {
            var      provider = new OpenIdProvider(store);
            IRequest request  = await provider.GetRequestAsync(this.Request);

            if (request == null)
            {
                App.Logger.Error("A request came in that did not carry an OpenID message.");
                return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("<html><body>This is an OpenID Provider endpoint.</body></html>", Encoding.UTF8, "text/html"),
                });
            }

            return(await await this.MainWindow.Dispatcher.InvokeAsync(async delegate {
                if (!request.IsResponseReady)
                {
                    var authRequest = request as IAuthenticationRequest;
                    if (authRequest != null)
                    {
                        string userIdentityPageBase = this.Url.Link("default", new { controller = "user" }) + "/";
                        var userIdentityPageBaseUri = new Uri(userIdentityPageBase);
                        switch (this.MainWindow.checkidRequestList.SelectedIndex)
                        {
                        case 0:
                            if (authRequest.IsDirectedIdentity)
                            {
                                if (this.MainWindow.capitalizedHostName.IsChecked.Value)
                                {
                                    userIdentityPageBase = (userIdentityPageBaseUri.Scheme + Uri.SchemeDelimiter + userIdentityPageBaseUri.Authority).ToUpperInvariant() + userIdentityPageBaseUri.PathAndQuery;
                                }
                                string leafPath = "directedidentity";
                                if (this.MainWindow.directedIdentityTrailingPeriodsCheckbox.IsChecked.Value)
                                {
                                    leafPath += ".";
                                }
                                authRequest.ClaimedIdentifier = Identifier.Parse(userIdentityPageBase + leafPath, true);
                                authRequest.LocalIdentifier = authRequest.ClaimedIdentifier;
                            }
                            authRequest.IsAuthenticated = true;
                            break;

                        case 1:
                            authRequest.IsAuthenticated = false;
                            break;

                        case 2:
                            IntPtr oldForegroundWindow = NativeMethods.GetForegroundWindow();
                            bool stoleFocus = NativeMethods.SetForegroundWindow(this.MainWindow);
                            await CheckIdWindow.ProcessAuthenticationAsync(userIdentityPageBaseUri, authRequest, CancellationToken.None);
                            if (stoleFocus)
                            {
                                NativeMethods.SetForegroundWindow(oldForegroundWindow);
                            }
                            break;
                        }
                    }
                }

                var responseMessage = await provider.PrepareResponseAsync(request);
                return responseMessage;
            }));
        }
Пример #6
0
        /// <summary>
        /// Runs a parameterized association flow test.
        /// </summary>
        /// <param name="opDescription">
        /// The description of the Provider that the relying party uses to formulate the request.
        /// The specific host is not used, but the scheme is significant.
        /// </param>
        /// <param name="expectedAssociationType">
        /// The value of the openid.assoc_type parameter expected,
        /// or null if a failure is anticipated.
        /// </param>
        private async Task ParameterizedAssociationTestAsync(
            ProviderEndpointDescription opDescription,
            string expectedAssociationType)
        {
            Protocol    protocol = Protocol.Lookup(Protocol.Lookup(opDescription.Version).ProtocolVersion);
            bool        expectSuccess = expectedAssociationType != null;
            bool        expectDiffieHellman = !opDescription.Uri.IsTransportSecure();
            Association rpAssociation = null, opAssociation;
            AssociateSuccessfulResponse   associateSuccessfulResponse = null;
            AssociateUnsuccessfulResponse associateUnsuccessfulResponse = null;
            var relyingParty = new OpenIdRelyingParty(new MemoryCryptoKeyAndNonceStore(), this.HostFactories);
            var provider = new OpenIdProvider(new MemoryCryptoKeyAndNonceStore(), this.HostFactories)
            {
                SecuritySettings = this.ProviderSecuritySettings
            };

            Handle(opDescription.Uri).By(
                async(request, ct) => {
                IRequest req = await provider.GetRequestAsync(request, ct);
                Assert.IsNotNull(req, "Expected incoming request but did not receive it.");
                Assert.IsTrue(req.IsResponseReady);
                return(await provider.PrepareResponseAsync(req, ct));
            });
            relyingParty.Channel.IncomingMessageFilter = message => {
                Assert.AreSame(opDescription.Version, message.Version, "The message was recognized as version {0} but was expected to be {1}.", message.Version, Protocol.Lookup(opDescription.Version).ProtocolVersion);
                var associateSuccess = message as AssociateSuccessfulResponse;
                var associateFailed  = message as AssociateUnsuccessfulResponse;
                if (associateSuccess != null)
                {
                    associateSuccessfulResponse = associateSuccess;
                }
                if (associateFailed != null)
                {
                    associateUnsuccessfulResponse = associateFailed;
                }
            };
            relyingParty.Channel.OutgoingMessageFilter = message => {
                Assert.AreEqual(opDescription.Version, message.Version, "The message was for version {0} but was expected to be for {1}.", message.Version, opDescription.Version);
            };

            relyingParty.SecuritySettings = this.RelyingPartySecuritySettings;
            rpAssociation = await relyingParty.AssociationManager.GetOrCreateAssociationAsync(opDescription, CancellationToken.None);

            if (expectSuccess)
            {
                Assert.IsNotNull(rpAssociation);
                Association actual = relyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, rpAssociation.Handle);
                Assert.AreEqual(rpAssociation, actual);
                opAssociation = provider.AssociationStore.Deserialize(new TestSignedDirectedMessage(), false, rpAssociation.Handle);
                Assert.IsNotNull(opAssociation, "The Provider could not decode the association handle.");

                Assert.AreEqual(opAssociation.Handle, rpAssociation.Handle);
                Assert.AreEqual(expectedAssociationType, rpAssociation.GetAssociationType(protocol));
                Assert.AreEqual(expectedAssociationType, opAssociation.GetAssociationType(protocol));
                Assert.IsTrue(Math.Abs(opAssociation.SecondsTillExpiration - rpAssociation.SecondsTillExpiration) < 60);
                Assert.IsTrue(MessagingUtilities.AreEquivalent(opAssociation.SecretKey, rpAssociation.SecretKey));

                if (expectDiffieHellman)
                {
                    Assert.IsInstanceOf <AssociateDiffieHellmanResponse>(associateSuccessfulResponse);
                    var diffieHellmanResponse = (AssociateDiffieHellmanResponse)associateSuccessfulResponse;
                    Assert.IsFalse(MessagingUtilities.AreEquivalent(diffieHellmanResponse.EncodedMacKey, rpAssociation.SecretKey), "Key should have been encrypted.");
                }
                else
                {
                    Assert.IsInstanceOf <AssociateUnencryptedResponse>(associateSuccessfulResponse);
                    var unencryptedResponse = (AssociateUnencryptedResponse)associateSuccessfulResponse;
                }
            }
            else
            {
                Assert.IsNull(relyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, new RelyingPartySecuritySettings()));
            }
        }