Twitter 登录 - 将用户重定向到身份验证

Twitter Sign In - Redirecting User to Authentication

我在对 Twitter 用户进行身份验证时遇到问题。我开发了一个 Scala 代码,我在其中处理与 Twitter 的所有服务器端连接,以及一个 Angular 5+ 应用程序作为我的前端。因此,当用户单击 HTML-Twitter 按钮时,此 Angular 函数将激活:

callTwLogin(): void{
    // StepOne
    var win = window.open('','_blank','height=500,width=800'); // I open a blank popup window 
    const callback2 = 'http://127.0.0.1:8081/TwitterRedirect'; 
    this.http.get(url1+callback2, {responseType: 'text'}).subscribe(data =>{
      console.log(data); //Just for testing purposes. 
    });
   }

现在,我的 Scala/Akka 服务器端代码处理此 GET 请求并从 Twitter 获取 request_token。然后,它获得 request_token 和 token_secret 并向 oauth/authenticate 发出 GET 请求,以获得 HTML。

val route = cors(settings){
      path("requestToken"){
        get {
          parameters('callback.as[String])(cb => {
            val callback = this.encodeUriComp(cb)
            val url = "https://api.twitter.com/oauth/request_token"
            this.oauth_timestamp = this.createTimestamp()
            this.oauth_nonce = this.randomString(32)
            val authorization = headers.RawHeader("Authorization",
              """OAuth oauth_callback="""" + callback +
                """", oauth_consumer_key="""" + this.consumerKey +
                """", oauth_nonce="""" + this.oauth_nonce +
                """", oauth_signature="""" + this.encodeUriComp(this.createSignature(callback)) +
                """", oauth_signature_method="HMAC-SHA1", oauth_timestamp="""" + this.oauth_timestamp +
                """", oauth_version="1.0"""")
            val params = ByteString(callback)
            val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(HttpMethods.POST, url,
              headers = List(authorization),
              entity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, params)))

            implicit val timeout = Timeout(5, TimeUnit.SECONDS)
            try {
              val result = Await.result(responseFuture, timeout.duration)
              val uri = "http://localhost:4200"
              val Str = result.entity.httpEntity.toString()
              val response = Str.substring(Str.indexOf("o"),Str.indexOf(")")) //This is the final response.
              println(response)
              val arr = setRequestTokenRSP(response)
              this.oauth_token = arr(0)
              this.oauth_token_secret = arr(1)
              if(arr(2)=="true"){ // if oauth_callback_confirmed == true
                val uri = "https://api.twitter.com/oauth/authenticate?oauth_token="+arr(0)
                val rspFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(HttpMethods.GET, uri))
                implicit val to = Timeout(5, TimeUnit.SECONDS)
                try{
                  val res = Await.result(rspFuture,to.duration)
                  complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,res.entity.dataBytes))
                }
                catch{
                  case e: TimeoutException => complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`,"Couldn't access authentication"))
                }
               // complete(HttpResponse(status = StatusCodes.PermanentRedirect,headers = headers.Location(uri) :: Nil))
              }
              else complete("Error recieving Request Token")
              //complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`,result.entity.dataBytes))
            }
            catch{
              case e: TimeoutException => complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`,"Couldn't process request"))
            }
          })
        }
      }

这就是棘手的地方。我得到了整个 HTML 但是,当将它传递到我的前端时,它不会识别 Twitter 会话。因此,每次执行此步骤时,我都需要使用我的 Twitter user/pass 登录。

为了避免这种情况,我尝试直接将 HTTP 302 重定向到 /oauth/authenticate,以便我的前端导航到 Twitter 身份验证页面。当然,这没有帮助,因为 CORS 限制。

我应该怎么做才能让我的用户无缝访问身份验证页面?

我做到了! ... 完成此操作的最无缝方法是 return 将 URL 到我的 Angular 前端应用程序。然后,我将使用 window.location.href 将弹出窗口简单地重定向到 URL 并创建一个 EventListener 来等待我的服务器发送的消息。

这是我的网络应用程序代码:

callTwLogin(): void{
    // StepOne
    var win = window.open('','_blank','height=500,width=800'); //Open a Blank PopUp.
    /** Add a listener so Scala can send a PostMessage when completing Authorization */
    window.addEventListener("message", recieveMessage, false);
    function recieveMessage(event){
      if (~event.origin.indexOf("http://127.0.0.1:8081")) {
        console.log(event.data);
      }
      else console.log("Error");
    }
    /** Making a call to backend, specifying callback URL */
    const url = 'http://127.0.0.1:8081/requestToken?callback=';
    const callback = 'http://127.0.0.1:8081/TwitterRedirect';
    this.http.get(url+callback, {responseType: 'text'}).subscribe(data =>{
      console.log(data);
      win.location.replace(data);   
    });
   }

我的服务器代码将包含 2 个路由。第二个将处理 oauth_verifier 并向我的网络应用程序发送 PostMessage。

path("requestToken"){
        get {
          parameters('callback.as[String])(cb => {
            /**
              * I NEED TO CHANGE AWAIT TO ONCOMPLETE!!!!
              */
              val callback = this.encodeUriComp(cb)
              val url = "https://api.twitter.com/oauth/request_token"
              this.oauth_timestamp = this.createTimestamp()
              this.oauth_nonce = this.randomString(32)
              val authorization = headers.RawHeader("Authorization",
                """OAuth oauth_callback="""" + callback +
                  """", oauth_consumer_key="""" + this.consumerKey +
                  """", oauth_nonce="""" + this.oauth_nonce +
                  """", oauth_signature="""" + this.encodeUriComp(this.createSignature(callback)) +
                  """", oauth_signature_method="HMAC-SHA1", oauth_timestamp="""" + this.oauth_timestamp +
                  """", oauth_version="1.0"""")
              val params = ByteString(callback)
              val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(HttpMethods.POST, url,
                headers = List(authorization),
                entity = HttpEntity(ContentTypes.`text/plain(UTF-8)`, params)))

              implicit val timeout = Timeout(5, TimeUnit.SECONDS)
              try {
                val result = Await.result(responseFuture, timeout.duration)
                val uri = "http://localhost:4200"
                val Str = result.entity.httpEntity.toString()
                val response = Str.substring(Str.indexOf("o"), Str.indexOf(")")) //This is the final response.
                println(response)
                val arr = setRequestTokenRSP(response)
                this.oauth_token = arr(0)
                this.oauth_token_secret = arr(1)
                if (arr(2) == "true") { // if oauth_callback_confirmed == true
                  val uri = "https://api.twitter.com/oauth/authenticate?oauth_token=" + arr(0)
                  complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`, uri))
                }
                else complete("Error recieving Request Token")
                //complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`,result.entity.dataBytes))
              }
              catch {
                case e: TimeoutException => complete(HttpEntity(ContentTypes.`text/plain(UTF-8)`, "Couldn't process request"))
              }
            })
        }

      }~
      path("TwitterRedirect"){
        get{
          parameters('oauth_verifier.as[String], 'oauth_token.as[String])((verifier, token) => {
            val url = "http://127.0.0.1:8081/getVerifier?verifier="+verifier
            if(this.oauth_token==token) { // Check whether token recieved in authorization equals the previous one.
              this.oauth_verifier = verifier
              val rspToAngular = verifier + "|" + token
              val html =
                "<!doctype html>" +
                  "<html lang='en'>" +
                  "<head>" +
                  "<meta charset='UTF-8'> <title>Popup</title> </head>" +
                  "<body> <script type='text/javascript'>" +
                  "window.opener.postMessage('" + rspToAngular + "', 'http://localhost:4200');" +
                  "</script></body></html>"
              complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, html))
            }
            else {
              val html =
                "<!doctype html>" +
                  "<html lang='en'>" +
                  "<head>" +
                  "<meta charset='UTF-8'> <title>Popup</title> </head>" +
                  "<body> <script type='text/javascript'>" +
                  "window.opener.postMessage('Error: Token Mismatch', 'http://localhost:4200');" +
                  "</script></body></html>"
              complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,html))
            }
          })
        }
      }