Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Building an external login URL #76

Closed
normal1ze opened this issue Jan 5, 2022 · 9 comments
Closed

Building an external login URL #76

normal1ze opened this issue Jan 5, 2022 · 9 comments

Comments

@normal1ze
Copy link

I am building an endpoint that will just return the login URL returned from build_oauth_url

Heres the code:

def get_auth_link():
    code_verifier = audible.login.create_code_verifier()

    oauth_url = audible.login.build_oauth_url(
        country_code=COUNTRY_CODE,
        domain=DOMAIN,
        market_place_id=MARKETPLACE_ID,
        code_verifier=code_verifier,
        with_username=False
    )

    return oauth_url

When I use the link, sign in and get the address bar URL to use from_login_external I get this as a return exception:

Exception: {'response': {'error': {'code': 'InvalidValue', 'index': 'tGP0Ha5AGkt8rT5f6GvjpwAAAAAAAAABCoOqqcjUmA7AKfxjSct01Cg_pilnvd6EEVWx2HFy9kOVWSGENsmEtLsb4T6TZHp8zL_c87GaD91q9qFKypHaaxu34HHfFjfv5gRHpfla80sRtMspddIA8e63XKV7tPaiRy3JG-wkH8mu1UgOHYwpgnWjmeKY-gSC9oVhl0e86leJkMF25Lluxz-fBorjbap52nclsr9Ml6FmSkUKVLWdbQ==', 'message': 'One or more provided values are invalid.'}}, 'request_id': 'fcd9fbe1-2432-4af5-bfc1-6cf3d1e42ebb'}

I am using the callback on from_login_external to pass in the URL from my custom endpoint like so:

def audible_login(): 
    #{ id: str, url: str }
    params = request.json

    print(params['url'])

    def auth_link_url_callback(login_url: str):
        print(login_url)
        return params['url']

    auth = audible.Authenticator.from_login_external(COUNTRY_CODE, login_url_callback=auth_link_url_callback)

    auth.to_file(params['id'])

I am posting the URL and via a CURL command for testing:

curl -X POST -H "Content-Type: application/json" -d '{
  "url": "https://www.amazon.com.au/ap/maplanding?openid.assoc_handle=amzn_audible_ios_au&openid.claimed_id=https%3A%2F%2Fwww.amazon.com.au%2Fap%2Fid%2Famzn1.account.AHDJ2REEGR72DEJEMJDUBHMW4PUA&openid.identity=https%3A%2F%2Fwww.amazon.com.au%2Fap%2Fid%2Famzn1.account.AHDJ2REEGR72DEJEMJDUBHMW4PUA&openid.mode=id_res&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.op_endpoint=https%3A%2F%2Fwww.amazon.com.au%2Fap%2Fsignin&openid.response_nonce=2022-01-05T07%3A35%3A16Z-1504074421391324938&openid.return_to=https%3A%2F%2Fwww.amazon.com.au%2Fap%2Fmaplanding&openid.signed=assoc_handle%2Cclaimed_id%2Cidentity%2Cmode%2Cns%2Cop_endpoint%2Cresponse_nonce%2Creturn_to%2Cns.pape%2Cpape.auth_policies%2Cpape.auth_time%2Coa2.authorization_code%2Ccaptcha_verified%2Csigned&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.auth_policies=http%3A%2F%2Fschemas.openid.net%2Fpape%2Fpolicies%2F2007%2F06%2Fnone&openid.pape.auth_time=2022-01-05T07%3A35%3A16Z&openid.sig=kHOEjSvIPKmMI6r1FfL2SjC6fKeRFFkbwFbXkO6t1zs%3D&serial=&openid.oa2.authorization_code=SRCSCKBUVJDQKPfDDWMZAUSg&openid.ns.oa2=http%3A%2F%2Fwww.amazon.com%2Fap%2Fext%2Foauth%2F2&captcha_verified=1&",
  "id": "1"
}' http://localhost:5000/login_with_url

Am I building up the URL wrong? Any advice would be appreciated.

@normal1ze normal1ze changed the title Building a external login URL Building an external login URL Jan 5, 2022
@normal1ze
Copy link
Author

Update.

I am using constants for testing with Australia only.

COUNTRY_CODE = "au"
DOMAIN = "com.au"
MARKETPLACE_ID = "AN7EY7DTAW63G"

@mkb79
Copy link
Owner

mkb79 commented Jan 5, 2022

Hi. This does not work!

You create a login url with a specific code verifier. This code verifier must be reused in the login_external function. But the function has no option for this. Instead it creates a new code verifier.

You can now rewrite the callback, so the callback will open the webserver and wait for your curl command.
Or you rewrite the login_external function so it will accept the code verifier as an additional kwargs and then reuse it.

Edit:
FYI - The specific code verifier is bound on the URL (better on the authorization code) you got after a successful login!

@mkb79
Copy link
Owner

mkb79 commented Jan 5, 2022

Oh, I saw you are from Australia. Then it's important that you reuse the serial from the audible.login.build_oauth_url function. Otherwise the external_login function will create a new one and this will not work for your target marketplace.

In my opinion the callback solution is the best way.

@normal1ze
Copy link
Author

Thanks for the advice.

In the end, I wont be using CURL, i'll be putting it under an API endpoint using Flask.

I'll have a go at using the callback and making sure the serial and verifier codes all match all the way through.

@mkb79
Copy link
Owner

mkb79 commented Jan 6, 2022

Okay. If you need help, feel free to contact me!

@normal1ze
Copy link
Author

Thanks!

I have an endpoint now that returns the URL, code and serial which can be used to build up a web-view on a mobile app.

However, Im not sure how the callback is going to help, as you said, the code isn't an attribute I can pass in like serial is, the callback simply asks for another code_verifier and returns it bypassing the callback anyway (

"code_verifier": code_verifier,
)

Would you have any advice on how to implement the callback system that would help with what I am trying to achieve?

@mkb79
Copy link
Owner

mkb79 commented Jan 7, 2022

I saw you submit the filename too. This is not possible with the callback, since it only accepts a url.

So I rewritten your code.

from urllib.parse import parse_qs

import audible.localization
import audible.login
import httpx
from audible.register import register as register_device


COUNTRY_CODE = "au"


def get_auth_link():
    locale = audible.localization.Locale(COUNTRY_CODE)
    code_verifier = audible.login.create_code_verifier()

    oauth_url, serial = audible.login.build_oauth_url(
        country_code=locale.country_code,
        domain=locale.domain,
        market_place_id=locale.market_place_id,
        code_verifier=code_verifier,
        with_username=False
    )

    return {
        "code_verifier": code_verifier,
        "login_url": oauth_url,
        "serial": serial
    }


class Authenticator(audible.Authenticator):
    @classmethod
    def custom_login(
        cls, code_verifier: bytes, response_url: str, serial: str
    ):
        auth = cls()
        auth.locale = COUNTRY_CODE

        response_url = httpx.URL(response_url)
        parsed_url = parse_qs(response_url.query.decode())
        authorization_code = parsed_url["openid.oa2.authorization_code"][0]

        registration_data = register_device(
            authorization_code=authorization_code,
            code_verifier=code_verifier,
            domain=auth.locale.domain,
            serial=serial
        )
        auth._update_attrs(**registration_data)

        return auth


def audible_login(request):
    # { id: str, url: str, code_verifier: bytes, serial: str}
    params = request.json

    auth = Authenticator.custom_login(
        code_verifier=params['code_verifier'],
        response_url=params['url'],
        serial=params['serial']
    )

    auth.to_file(params['id'])

That should actually work.

But if you use Flask, you can also use a kind of proxy to login. Take a look at alexaproxy. I do the same with my private Audible Django project. And it runs fine.
The server request the page at Amazon and rewrite the html code. The prepared html code will send to the clients webbrowser. So the client think, he communicate directly with Amazon.

@normal1ze
Copy link
Author

normal1ze commented Jan 7, 2022

Wow thank you! That worked a treat!!! Thanks for taking the time out and pointing me in the right direction. I really appreciate it.

@mkb79
Copy link
Owner

mkb79 commented Jan 7, 2022

Great to hear that. You have inspires me. I've wrote a POC with playwright in some minutes and it works.

import asyncio
from urllib.parse import parse_qs

import audible.localization
import audible.login
import httpx
from audible.register import register as register_device
from playwright.async_api import async_playwright


COUNTRY_CODE = "de"


def get_auth_link():
    locale = audible.localization.Locale(COUNTRY_CODE)
    code_verifier = audible.login.create_code_verifier()

    oauth_url, serial = audible.login.build_oauth_url(
        country_code=locale.country_code,
        domain=locale.domain,
        market_place_id=locale.market_place_id,
        code_verifier=code_verifier,
        with_username=False
    )

    return {
        "code_verifier": code_verifier,
        "login_url": oauth_url,
        "serial": serial
    }


class Authenticator(audible.Authenticator):
    @classmethod
    def custom_login(
        cls, code_verifier: bytes, response_url: str, serial: str
    ):
        auth = cls()
        auth.locale = COUNTRY_CODE

        response_url = httpx.URL(response_url)
        parsed_url = parse_qs(response_url.query.decode())
        authorization_code = parsed_url["openid.oa2.authorization_code"][0]

        registration_data = register_device(
            authorization_code=authorization_code,
            code_verifier=code_verifier,
            domain=auth.locale.domain,
            serial=serial
        )
        auth._update_attrs(**registration_data)

        return auth


def audible_login(data):
    # { fn: str, url: str, code_verifier: bytes, serial: str}
    params = data
    print(params)

    auth = Authenticator.custom_login(
        code_verifier=params['code_verifier'],
        response_url=params['url'],
        serial=params['serial']
    )

    auth.to_file(params['fn'])


async def main():
    async with async_playwright() as p:
        iphone = p.devices["iPhone 12 Pro"]
        browser = await p.webkit.launch(headless=False)
        context = await browser.new_context(
            **iphone,
            locale="de-DE"
        )
        page = await browser.new_page()

        login_data = get_auth_link()

        await page.goto(login_data["login_url"])

        while True:
            await page.wait_for_timeout(600)
            if "/ap/maplanding" in page.url:
                data = {
                    "fn": "credentials.json",
                    "url": page.url,
                    "code_verifier": login_data["code_verifier"],
                    "serial": login_data["serial"]
                }
                audible_login(data)
                break
            continue

        await browser.close()


asyncio.run(main())

If you are interessting in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants