How to implement RBAC in azure and flask application

139 Views Asked by At

I want to implement Azure RBAC in a flask application. How should I do it?

Inside the web app, Users can assign and remove roles to other users.

1

There are 1 best solutions below

0
On

How to implement RBAC in azure and flask application: -

To achieve your requirement, firstly install pip install Flask-OAuthlib package as it is used for flask app authorization with Oauth(Azure RBAC).

pip install Flask-OAuthlib

enter image description here

Now when it comes to implementation of RBAC in a flask app, follow below detailed steps.

  1. Register a new app under Azure AD B2C and provide a flask web app URL in Redirect URL field. Once you registered it, create a client secret and store it with you. enter image description here

  2. Now go to API permissions and add the required Graph API permissions according to the requirement.

  3. In order to use Azure AD B2C in a flask app, the main thing you need to use is oauth.remote_app function in the python code which is given below.

from flask import Flask, redirect, url_for, session
from flask_oauthlib.client import OAuth
app = Flask(__name__)
app.secret_key = 'secretxxxx'
oauth = OAuth(app)

azure = oauth.remote_app(
    'azure',
    consumer_key='client_id',
    consumer_secret='client_secret',
    request_token_params={'scope': 'openid email profile'},
    base_url='https://graph.microsoft.com/v1.0/',
    request_token_url=None,
    access_token_method='POST',
    access_token_url='https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/token',
    authorize_url='https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/authorize'
)

@app.route('/')
def index():
    return 'Azure RBAC Flask App is running'

@app.route('/login')
def login():
    return azure.authorize_redirect(redirect_uri=url_for('authorized', _external=True))

@app.route('/logout')
def logout():
    session.pop('azuretoken', None)
    return 'Logged out'

@app.route('/login/authorized')
def authorized():
    response = azure.authorized_response()
    if response is None or response.get('access_token') is None:
        return 'Access denied: reason={} error={}'.format(
            request.args['error_reason'],
            request.args['error_description']
        )
    session['azuretoken'] = response
    return 'Logged in'
python -m flask run --host localhost --port 5000

Output:

enter image description here

References:

Adding auth to a Flask App with Azure Active Directory and Oso for more relevant information.

Configuring authentication in a python app using Azure RBAC. And same will be applicable for flask web app as well.