425show / fastapi_microsoft_identity

MIT License
36 stars 18 forks source link

B2C _issuer URL is incorrect - perhaps an old reference #19

Open jimma72 opened 1 year ago

jimma72 commented 1 year ago

Hi.

@cmatskas , thanks for the great work on the fastapi_microsoft_identity and your associated training on TalkPython. I have managed to get access tokens working with B2C and FastAPI but was stumped for a while with 401 errors. Having worked through it and got the module to work correctly I thought I would mention it to you for an update or comment.

This is the original code in auth_service.py

    if token_version == "1.0":
        _issuer = f'https://{b2c_domain_name}.b2clogin.com/tfp/{tenant_id}/{b2c_policy_name}/v2.0/'.lower()
    else:
        _issuer = f'https://{b2c_domain_name}.b2clogin.com/{tenant_id}/v2.0/'.lower()
    try:
        payload = jwt.decode(
            token,
            rsa_key,
            algorithms=["RS256"],
            audience=client_id,
            issuer=_issuer
        )

However, when checking the access token being presented by a valid call, I noticed the version 1.0 token does not match the code above and is being presented as the second URL. By replacing the first URL with the second URL the token is accepted and operates as expected. Adjusted code below:


    if token_version == "1.0":
        _issuer = f'https://{b2c_domain_name}.b2clogin.com/{tenant_id}/v2.0/'.lower()
        #_issuer = f'https://{b2c_domain_name}.b2clogin.com/tfp/{tenant_id}/{b2c_policy_name}/v2.0/'.lower()
    else:
        _issuer = f'https://{b2c_domain_name}.b2clogin.com/{tenant_id}/v2.0/'.lower()
    try:
        payload = jwt.decode(
            token,
            rsa_key,
            algorithms=["RS256"],
            audience=client_id,
            issuer=_issuer
        )
jimma72 commented 1 year ago

Add to this the trailing '/' at the end of the _issuer lines did not exist and causes the request to fail. This is fixed in the code above.

lsmith77 commented 12 months ago

I have noticed the same thing, ie. the 1.0 URLs for issuer are incorrect.

sslivins commented 10 months ago

as an alternative (after spending waaaay too much time tracking down the issue) there is a setting in your azure portal to change the format of the iss in your token:

go to: Azure AD B2C->User Flows->[pick your flow]->properties->Token compatibility settings->Issuer (iss) claim and switch it to the one the contains your flow.