Example #1
0
        public ActionResult AddAuthenticationToken(string openid_openidAuthData)
        {
            IAuthenticationResponse response;

            if (!string.IsNullOrEmpty(openid_openidAuthData))
            {
                var auth    = new Uri(openid_openidAuthData);
                var headers = new WebHeaderCollection();
                foreach (string header in Request.Headers)
                {
                    headers[header] = Request.Headers[header];
                }

                // Always say it's a GET since the payload is all in the URL, even the large ones.
                HttpRequestBase clientResponseInfo = HttpRequestInfo.Create("GET", auth, headers: headers);
                response = this.RelyingParty.GetResponse(clientResponseInfo);
            }
            else
            {
                response = this.RelyingParty.GetResponse();
            }
            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    string identifierString = response.ClaimedIdentifier;
                    var    existing         = Database.DataContext.AuthenticationTokens.Include("User").FirstOrDefault(token => token.ClaimedIdentifier == identifierString);
                    if (existing == null)
                    {
                        Database.LoggedInUser.AuthenticationTokens.Add(new AuthenticationToken {
                            ClaimedIdentifier  = response.ClaimedIdentifier,
                            FriendlyIdentifier = response.FriendlyIdentifierForDisplay,
                        });
                        Database.DataContext.SaveChanges();
                    }
                    else
                    {
                        if (existing.User != Database.LoggedInUser)
                        {
                            // The supplied token is already bound to a different user account.
                            // TODO: communicate the problem to the user.
                        }
                    }
                    break;

                default:
                    break;
                }
            }

            return(RedirectToAction("Edit", "Account"));
        }
        void loop()
        {
            try
            {
                initHttpListener();
                while (!_disposeEvent.WaitOne(0))
                {
                    HttpListenerContext  context   = _httpListener.GetContext();
                    HttpListenerRequest  hRequest  = context.Request;
                    HttpListenerResponse hResponse = context.Response;
                    using (StreamWriter writer = new StreamWriter(context.Response.OutputStream))
                    {
                        try
                        {
                            var    endport    = hRequest.RemoteEndPoint;
                            string key        = readHeader(hRequest.Headers, "handle");
                            var    onlineInfo = key != null?OnlineMgr.Instance.GetOnlineInfo(key) : null;

                            HttpRequestInfo reqInfo = HttpRequestInfo.Create(hRequest.RawUrl);
                            var             headers = hRequest.Headers;
                            if (reqInfo == null)
                            {
                                writer.WriteLine("error,请输入有效的参数.");
                            }
                            else
                            {
                                updateMessage(hRequest, writer, key, ref onlineInfo, reqInfo, headers);
                            }
                        }
                        catch (InvalidCastException ex)
                        {
                            writer.WriteLine("error," + ex.Message);
                            Common.Log.Logger.Default.Error("error," + ex.Message);
                        }
                        catch (Exception ex)
                        {
                            writer.WriteLine("error,解析错误." + ex.Message);
                            Common.Log.Logger.Default.Error("error,解析错误," + ex.Message);
                        }
                    }
                }
                _thread = null;
                stop();
            }
            catch (Exception ex)
            {
                Common.Log.Logger.Default.Error("http server error.", ex);
                stop();
                Thread.Sleep(15000);
                loop();//15秒后自动恢复
            }
        }
Example #3
0
        /// <summary>
        /// Handles incoming HTTP requests.
        /// </summary>
        /// <param name="context">The HttpListener context.</param>
        private void RequestHandler(HttpListenerContext context)
        {
            Requires.NotNull(context, "context");
            Requires.NotNull(context.Response.OutputStream, "context.Response.OutputStream");
            Requires.NotNull(this.ProcessRequest, "this.ProcessRequest");

            Stream outputStream = context.Response.OutputStream;

            Assumes.True(outputStream != null);             // CC static verification shortcoming.

            UriBuilder providerEndpointBuilder = new UriBuilder();

            providerEndpointBuilder.Scheme = Uri.UriSchemeHttp;
            providerEndpointBuilder.Host   = "localhost";
            providerEndpointBuilder.Port   = context.Request.Url.Port;
            providerEndpointBuilder.Path   = ProviderPath;
            Uri providerEndpoint = providerEndpointBuilder.Uri;

            if (context.Request.Url.AbsolutePath == ProviderPath)
            {
                HttpRequestBase requestInfo = HttpRequestInfo.Create(context.Request);
                this.ProcessRequest(requestInfo, context.Response);
            }
            else if (context.Request.Url.AbsolutePath.StartsWith(UserIdentifierPath, StringComparison.Ordinal))
            {
                using (StreamWriter sw = new StreamWriter(outputStream)) {
                    context.Response.StatusCode = (int)HttpStatusCode.OK;

                    string localId = null;                     // string.Format("http://localhost:{0}/user", context.Request.Url.Port);
                    string html    = GenerateHtmlDiscoveryDocument(providerEndpoint, localId);
                    sw.WriteLine(html);
                }
                context.Response.OutputStream.Close();
            }
            else if (context.Request.Url == this.OPIdentifier)
            {
                context.Response.ContentType = "application/xrds+xml";
                context.Response.StatusCode  = (int)HttpStatusCode.OK;
                App.Logger.Info("Discovery on OP Identifier detected.");
                using (StreamWriter sw = new StreamWriter(outputStream)) {
                    sw.Write(GenerateXrdsOPIdentifierDocument(providerEndpoint, Enumerable.Empty <string>()));
                }
                context.Response.OutputStream.Close();
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                context.Response.OutputStream.Close();
            }
        }
Example #4
0
        public ActionResult LogOnPostAssertion(string openid_openidAuthData)
        {
            IAuthenticationResponse response;

            if (!string.IsNullOrEmpty(openid_openidAuthData))
            {
                // Always say it's a GET since the payload is all in the URL, even the large ones.
                var             auth = new Uri(openid_openidAuthData);
                HttpRequestBase clientResponseInfo = HttpRequestInfo.Create("GET", auth, headers: Request.Headers);
                response = this.RelyingParty.GetResponse(clientResponseInfo);
            }
            else
            {
                response = this.RelyingParty.GetResponse();
            }
            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    var token = RelyingPartyLogic.User.ProcessUserLogin(response);
                    this.FormsAuth.SignIn(token.ClaimedIdentifier, false);
                    string returnUrl = Request.Form["returnUrl"];
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }

                case AuthenticationStatus.Canceled:
                    ModelState.AddModelError("OpenID", "It looks like you canceled login at your OpenID Provider.");
                    break;

                case AuthenticationStatus.Failed:
                    ModelState.AddModelError("OpenID", response.Exception.Message);
                    break;
                }
            }

            // If we're to this point, login didn't complete successfully.
            // Show the LogOn view again to show the user any errors and
            // give another chance to complete login.
            return(View("LogOn"));
        }
Example #5
0
        public async Task <ActionResult> AuthorizeWithMicrosoftAccount(string nestedAuth)
        {
            var authorizationState = LiveConnectClient.ProcessUserAuthorization(this.Request);
            var accessToken        = authorizationState.AccessToken;

            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentNullException("accessToken");
            }

            // Rebuild the original authorization request from the client.
            var reconstitutedRequestUri = new UriBuilder(this.Request.Url);

            reconstitutedRequestUri.Query = nestedAuth.Substring(1);
            var reconstitutedRequestInfo = HttpRequestInfo.Create("GET", reconstitutedRequestUri.Uri);
            var incomingAuthzRequest     = this.authorizationServer.ReadAuthorizationRequest(reconstitutedRequestInfo);

            if (incomingAuthzRequest == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Missing authorization request"));
            }

            // Since this authz request has gone through at least one untrusted leg, make sure it's following our rules.
            // We're auto-approving this, but only want to do so if it's the client we trust.
            if (incomingAuthzRequest.ClientIdentifier != ConfigurationManager.AppSettings["TrustedClientPackageId"])
            {
                return(new HttpUnauthorizedResult("Not a trusted client."));
            }

            var uri    = new Uri("https://apis.live.net/v5.0/me?access_token=" + Uri.EscapeDataString(accessToken));
            var result = await this.HttpClient.GetAsync(uri);

            result.EnsureSuccessStatusCode();
            string jsonUserInfo = await result.Content.ReadAsStringAsync();

            var serializer           = new JsonSerializer();
            var jsonReader           = new JsonTextReader(new StringReader(jsonUserInfo));
            var microsoftAccountInfo = serializer.Deserialize <MicrosoftAccountInfo>(jsonReader);

            await this.SaveAccountInfoAsync(microsoftAccountInfo);

            var response = this.authorizationServer.PrepareApproveAuthorizationRequest(incomingAuthzRequest, microsoftAccountInfo.Id, new[] { "AddressBook" });

            return(this.authorizationServer.Channel.PrepareResponse(response).AsActionResult());
        }
Example #6
0
        public ActionResult LogOnPostAssertion(string openid_openidAuthData)
        {
            IAuthenticationResponse response;

            if (!string.IsNullOrEmpty(openid_openidAuthData))
            {
                var auth    = new Uri(openid_openidAuthData);
                var headers = new WebHeaderCollection();
                foreach (string header in Request.Headers)
                {
                    headers[header] = Request.Headers[header];
                }

                // Always say it's a GET since the payload is all in the URL, even the large ones.
                HttpRequestInfo clientResponseInfo = HttpRequestInfo.Create("GET", auth, null, headers) as HttpRequestInfo;
                response = RelyingParty.GetResponse(clientResponseInfo);
            }
            else
            {
                response = RelyingParty.GetResponse();
            }
            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    string alias = response.FriendlyIdentifierForDisplay;
                    string email = string.Empty;
                    var    sreg  = response.GetExtension <ClaimsResponse>();
                    if (sreg != null && sreg.MailAddress != null)
                    {
                        alias = sreg.MailAddress.User;
                        email = sreg.Email;
                    }
                    if (sreg != null && !string.IsNullOrEmpty(sreg.FullName))
                    {
                        alias = sreg.FullName;
                    }

                    FormsAuthenticationTicket authTicket = new
                                                           FormsAuthenticationTicket(1,                           //version
                                                                                     response.ClaimedIdentifier,  // user name
                                                                                     DateTime.Now,                //creation
                                                                                     DateTime.Now.AddMinutes(30), //Expiration
                                                                                     false,                       //Persistent
                                                                                     alias);

                    string encTicket = FormsAuthentication.Encrypt(authTicket);

                    this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                    createUserIfNotExist(alias, email);
                    SetUserIdentityForView(alias);
                    string returnUrl = Request.Form["returnUrl"];
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return(Redirect(returnUrl));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }

                case AuthenticationStatus.Canceled:
                    ModelState.AddModelError("OpenID", "It looks like you canceled login at your OpenID Provider.");
                    break;

                case AuthenticationStatus.Failed:
                    ModelState.AddModelError("OpenID", response.Exception.Message);
                    break;
                }
            }

            // If we're to this point, login didn't complete successfully.
            // Show the LogOn view again to show the user any errors and
            // give another chance to complete login.
            return(View("LogOn"));
        }