How youtube gets logged in to gmail account without getting redirected?

前端 未结 1 1941
情深已故
情深已故 2020-12-08 12:14

Step 1: i logged into my gmail account. Browser actually redirects to accounts.google.com. So i logged in there and redirected back to gmail logged in

S

相关标签:
1条回答
  • 2020-12-08 12:42

    This is the technical solution scheme to allow cross domain communication between two o more websites like youtube or gmail using a central sso domain (accounts.google.com)

    1) Login in gmail redirects to accounts.google.com, identifies you and issue an authentication token (JWT format) with your account information. The token is stored in browser localStorage

    //Store the Json Web token with accountInfo in localStorage
    localStorage.setItem('tokenId',jwt);
    

    2) Youtube checks accounts.google.com localStorage looking for auth tokens. If found, allows you to enter.

    Cookies and localStorage can be shared between domains using an intermediate domain accounts.google.com. On the home page is embedded an iframe, which accesses cookies and sends messages to the main.

    //Create iframe when page is loaded pointing to sso domain. For example in gmail.com and youtube.com pointing to accounts.google.com
    var iframe = document.createElement('iframe');
    iframe.style.display = "none";
    iframe.src = 'https://sso.domain.com/sso.html?sourceDomain=...;
    iframe.id = 'sso.iframe';
    document.body.appendChild(iframe);
    

    When iframe is loaded, sends a message with the jwt to parent page

    window.parent.postMessage(jwt, sourceDomain);
    

    The parent page receives the token

    //Message listener for SSO events (created by the sso.iframe)
    addEventListener("message", _listener, false);
    
    function _listener(event){
        //origin check
        if (  sourceDomain.lastIndexOf(event.origin ) == -1){
            return;
        }
    
        var jwt = event.data
        //do something with the token...
     }
    

    So domain1.com and domain2.com can share cookies/localStorage in this way. Open Chrome->Inspect->Resources->Local storage and you will see for example in accounts.google.com the shared info (there are many data fields).

    JWT is self contained and signed with server key. It contains the user data, and integrity and identity of the issuer can be verified

    Check out https://github.com/Aralink/ssojwt to see an implementation of SSO in this way, and resolving all issues with the different browsers

    This is the general schema used by google. If you browse the gmail or youtube code you will see many things and other additional fields. Google also add a origin restriction. If you want to use the accounts.google.com SSO you have to register in google apps, get an integration ID and specify your authorized origins

    0 讨论(0)
提交回复
热议问题