(Python/Flask) How to enable rbac login (with some sort of button login)

I am trying to rbac login with users who have been given specific roles. I am aware there is already an article or two on how to implement this, but I can’t find in that article how to enable a “login” to set this process in motion.

I am currently using the basic login setup, assuming there are users who have no roles:

oauth = OAuth(app)
oauth.register(
“auth0”,
client_id=env.get(“AUTH0_CLIENT_ID”),
client_secret=env.get(“AUTH0_CLIENT_SECRET”),
client_kwargs={
“scope”: “openid profile email”,
},
server_metadata_url=f’https://{env.get(“AUTH0_DOMAIN”)}/.well-known/openid-configuration’

@app.route(“/login”)
def login():
return oauth.auth0.authorize_redirect(
redirect_uri=url_for(“callback”, _external=True)
)
@app.route(“/callback”, methods=[“GET”, “POST”])
def callback():
token = oauth.auth0.authorize_access_token()
session[“user”] = token
return redirect(“/”)

And of course the button to set this process in motion is simple:

Login

I would essentially like to do something this button, but also use the api that maps a role to the person logging in.

Hopefully what I have said here makes some sense but please let me know if anything needs clarification. Thanks in advance for your help.

Hi @matthewdbailin,

Thanks for reaching out to the Auth0 Community!

First, have you made sure that your API has enabled RBAC?

Once you have done so, it enables the API Authorization Core feature set for RBAC.

Then in your authentication request (/authorize), you will need to include the corresponding API identifier to enforce RBAC permissions on login.

See this doc for more information.

Hoped this helps!

Please let me know if you have any further questions.

Thank you.

Hi Rueben,

Thanks very much for your response. I have already done the above suggestions. The main issue I’m having is that when I attempt to use my endpoint that requires an authorization, I get an error.

The endpoint looks like this:

  @app.route('/lists/create', methods=['POST'])
  @requires_auth('create: todolist')
  def create_todo_list():
    list_error = False
    body = {}
    try:
      name = request.get_json()['name']
      list = TodoList(name=name)
      db.session.add(list)
      db.session.commit()
      body['name'] = list.name
    except:
      list_error = True
      db.session.rollback()
      print(sys.exc_info())
    finally:
        db.session.close()
    if list_error:
        abort (400)
    else:
        return jsonify({name: list.name})

For the @requires_auth decorator, I am using the canonical solution found in Auth0’s docs here: Auth0 Python API SDK Quickstarts: Authorization. That script is being imported into the main app.py.

When I attempt to use the endpoint, I receive this error:

Error response

Error code: 400

Message: Bad request syntax (‘{“name”:“new list”}GET /lists/70 HTTP/1.1’).

Error code explanation: HTTPStatus.BAD_REQUEST - Bad request syntax or unsupported method.

I believe there might be a problem with CORS, which is why I’ve also tried this decorator at the top of the script:

@app.after_request
  def after_request(response):
    response.headers.add('Access-Control-Allow-Headers',
                          'Content-Type,Authorization,true')
    response.headers.add('Access-Control-Allow-Methods',
                          'GET,PATCH,POST,DELETE,OPTIONS')

Would you have any further advice here on how to proceed?

Update: I was able to get the correct JWT on login and the only thing left to do is to get the JWT into the authorization header of the request to the API endpoint.

I need to add something to the effect of

{‘authorization’: ‘bearer {TOKEN}’}

into the header of my request.

For verification, I have tested the endpoint on Postman and this is what I was able to find:

The response is 200, so I can make the call work manually. Now, the only thing left to do is get this working in python. Do you have any code that would help here?

1 Like

Hi @matthewdbailin,

Thank you for your response and I’m glad that you can get the correct JWT.

Since you can get it working in Postman, have you tried exporting your code snippet and embedding it into your code solution?

You will need to click on the Code snippet icon on the left column and select your Python HTTP request library.

After doing so, this should provide you with a working copy of your Postman request that you can use in your code solution.

Hoped this helps!

Please let me know if there’s anything else I can do to help.

Thanks.

Hi Rueben,

I am sorry to ask this, but which program are you finding that helpful-looking dropdown menu from? I am not seeing that menu on either Postman or Auth0.

Hi @matthewdbailin,

The dropdown menu is from the Postman application. On the left panel of Postman, click on the </> icon which opens the Code Snippet Menu.

Please see this documentation for more information.

Thank you.