Trouble getting the user object post login



  • Hello,

    I'm using FusionAuth to handle the login and authentication functionality in my application. I've been able to successfully setup FusionAuth and a simple Flask based python application that implements the required callbacks. In the first version, the callbacks didn't perform any operation other than rendering a simple HTML template with success message. With this I was able to login and logout successfully.

    However, when I try to enhance the code to get access token and user on a successful login, I keep getting a 401 error message. I'm following the quick setup tutorial here with the exception of using corresponding functions in python. My code is as below:

    from app import app
    from flask import request, render_template
    
    from fusionauth.fusionauth_client import FusionAuthClient
    
    
    client_id = "<my-id>"
    client_secret = "<my-secret>"
    
    client = FusionAuthClient(client_id, "http://<my-ip>:9011")
    
    @app.route("/")
    def index():
        # Render a simple page with a login button
        return render_template("public/index.html")
    
    
    @app.route("/oauth-callback")
    def oauth_callback():
        resp = client.exchange_o_auth_code_for_access_token(request.args.get("code"), client_id, client_secret, "http://<my-ip>:5000/oauth-callback")
    
        print(resp.status)
        # Render a simple page with a login succeeded message and a logout button
        return render_template("public/logged_in.html")
    
    
    @app.route("/logout")
    def logout():
        # Render a simple page with a logout successful message
        return render_template("public/logged_out.html")
    

    The call to exchange_o_auth_code_for_access_token always returns 401 no matter what value I provide for the URL parameter. I'm not sure what I'm doing wrong and would appreciate any help.

    Thanks in advance!
    -N



  • Hiya,

    A few troubleshooting tips:



  • @dan Thanks for the response. I changed the call to exchange_o_auth_code_for_access_token swapping client_secret and redirect_uri args. I made sure that the user is registered with the application to which they are trying to authorize and that the redirect_uri is setup correctly in application config. I'm attaching screen shots from the FusionAuth app. I'm still getting a 401 response.

    l would also would like to mention as an aside that the user is able to login successfully to this app. I get 401 for the auth code request post successful login.

    Redirect URI setup:
    RedirecURI.jpg

    User Registration:
    UserReg.png



  • OK, so the user is able to login when you are logging them into the application directly, is that correct?

    But you get a 401 whenever you are requesting a token.

    Interesting.

    Can you try to make a different call with the client object, just to make sure you are initializing it correctly?

    client_response = client.retrieve_user_by_email('you@example.com')
    if client_response.was_successful():
        print(client_response.success_response)
    else:
        print(client_response.error_response)
    

    Can you try adding this code just after you call client.exchange_o_auth_code_for_access_token?

    if resp.was_successful():
        print("success")
        print(resp.success_response)
    else:
        print("error")
        print(resp.error_response)
    

    And let me know what you see when running your flask server.



  • @dan That is correct. Below is the output on flask server:

    <Response [401]>
    error
    <Response [401]>
    74.15.29.84 - - [24/Aug/2020 15:46:33] "GET /oauth-callback?code=q0AEmFiDNOjWiGlBa64Ea7MI2BlwotSh7AAcqqjWSt4&locale=en_US&userState=AuthenticatedNotRegistered HTTP/1.1" 200 -
    


  • @nishant said in Trouble getting the user object post login:

    &userState=AuthenticatedNotRegistered

    There's the issue. Are you sure that you:

    • registered the user to the application
    • are passing the correct client id for the application

    Because it seems like FusionAuth recognizes the user, but not that they are registered to the application.

    Can you double check both of those? (I know you checked that the user was registered before, but can you double check?)



  • @dan Thanks for the response. I did double check my application code and there was a client id mismatch in one of the URIs in my application code. I fixed that. However I'm still getting 401. Below is the flask server output:

    <Response [401]>
    error
    <Response [401]>
    74.15.29.84 - - [25/Aug/2020 22:43:04] "GET /oauth-callback?code=9E2MtFiIkFTS1uRBDjNXIOwLDuefGNLMqreSo1gZL2A&locale=en_US&userState=Authenticated HTTP/1.1" 200 -```
    

    As you can see the state has changed to Authenticated now.



  • Hiya,

    Thanks for your patience. I'm not quite sure what is going on.

    Can you provide your code in a github repo or other place I can take a look at the whole project, please?



  • @dan No worries! Thanks for all your help! You can download the application zip file from here. As you'll notice, its a pretty simple app. Also I've replaced all the ip addresses and ids for security reasons so while the app won't run as is, you would still be able to get an idea of the functionality. Thanks again for your continued support! Hoping to resolve this soon!



  • @dan Hi Dan, just circling back. Did you have a chance to look into this? Thanks!



  • OK, I did take a look.

    The issue is that there was a recent change to the client library which switched the order of arguments.

    This is the set of arguments that worked for me:

     resp = client.exchange_o_auth_code_for_access_token(request.args.get("code"), "http://localhost:5000/oauth-callback", client_id, client_secret)
    

    But I asked the engineering team when they'd be releasing the newest version of the libs, which will change it to

     resp = client.exchange_o_auth_code_for_access_token(request.args.get("code"), client_id, "http://localhost:5000/oauth-callback", client_secret)
    

    client_id and redirect_uri swapped places.

    Once I did that, when I logged in, I saw:

    success
    {'access_token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImRkMDYxMjY4YWMifQ.eyJhdWQiOiIzODU1ZGMyMC0yNzQ3LTQwYzEtYTUyMC1hODc3NzYxYmY5YjYiLCJleHAiOjE1OTg2Mzk2MTMsImlhdCI6MTU5ODYzNjAxMywiaXNzIjoiYWNtZS5jb20iLCJzdWIiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDQiLCJqdGkiOiIwYWYzNDlkMy04ZTQ5LTQ0ZDEtYmE5NS04NmM2N2I4NzAzODkiLCJhdXRoZW50aWNhdGlvblR5cGUiOiJQQVNTV09SRCIsImVtYWlsIjoiZGluZXNoQGZ1c2lvbmF1dGguaW8iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXBwbGljYXRpb25JZCI6IjM4NTVkYzIwLTI3NDctNDBjMS1hNTIwLWE4Nzc3NjFiZjliNiIsInJvbGVzIjpbXX0.RXdPUtk_vtRbNva__O8OBLFdUv8aZubewkXmK9Pnr2g', 'expires_in': 3599, 'token_type': 'Bearer', 'userId': '00000000-0000-0000-0000-000000000004'}
    

    If you want to get further user info, you can use the userId to look stuff up via the APIs. You could also make a request to the Userinfo endpoint, but if you do so, you need to request the openid scope initially.

    I also noticed that the API call was failing. Make sure you create your client with the API key, which is different than the client id:

    client = FusionAuthClient('APIKEY', "http://localhost:9011")
    

    Will let you know what I hear back, but until then you should look at https://github.com/FusionAuth/fusionauth-python-client/blob/1.18.0/src/main/python/fusionauth/fusionauth_client.py to see the proper order of args, because that is the published version.



  • OK, we just released 1.18.8 and that is the version you want to use:

    In requirements.txt:

    fusionauth-client==1.18.8
    

    And then this is the call you want to make (with client_id before redirect_uri) :

     resp = client.exchange_o_auth_code_for_access_token(request.args.get("code"), client_id, "http://localhost:5000/oauth-callback", client_secret)
    


  • Thanks Dan! It all works now.



  • Thanks all for this - I too fell into the trap. It looks like the docs I was following have the wrong signature for the exchange_o_auth_code_for_access_token function: https://fusionauth.io/blog/2020/07/14/django-and-oauth

    It should of course read:

    r = client.exchange_o_auth_code_for_access_token(
          code,
          settings.FUSION_AUTH_APP_ID,
          redirect_url,
          settings.FUSION_AUTH_CLIENT_SECRET,
        )
    

    (incidentally, the docs use CLIENT_ID in this function call, but never actually try to set it - so it should be APP_ID as here)



  • Thanks @ralph . I just updated the site ( https://github.com/FusionAuth/fusionauth-site/pull/247 ) and the fixes should go out in a day or so.



  • @dan Thank you for your support. Fixing the signature just saved me another couple of hours (also coming from https://fusionauth.io/blog/2020/07/14/django-and-oauth/) ^^