Search code examples
flaskauth0

Correct method of authorising users to certain pages using Auth0


I'm using Auth0 to create a user authorisation, I've also assigned users to groups and then roles within the group. What is the correct convention of restricting users from certain pages and routes?

Currently I am doing the following:

def requires_auth(f):
  @wraps(f)
  def decorated(*args, **kwargs):
    if 'profile' not in session:
      # Redirect to Login page here
      return redirect('/')
    return f(*args, **kwargs)
  return decorated

@app.route('/dashboard')
@requires_auth
def dashboard():
    if not authorization_check(['GroupNameExample']):
        return redirect(url_for('logout')) # instead of an error page for now
    else:
        return render_template('dashboard.html')

def authorization_check(groups):
    user_group = session['profile']['security']['groups'][0]
    if user_group not in groups:
        return False
    else:
        return True

So I'm just doing a basic IF statement, does that seem right?


Solution

  • This can be done actively through roles and direct user IDs. Below is an example that leverages the ID token for an Access Denied error:

    function (user, context, callback) {
      if (context.clientID === "BANNED_CLIENT_ID") {
        return callback(new UnauthorizedError('Access to this application has been temporarily revoked'));
      }
    
      callback(null, user, context);
    }
    

    This will cause a redirect to your callback URL with an error querystring parameter containing the message you set. (such as https://yourapp.com/callback?error=unauthorized&error_description=Access%20to%20this%20application%20has%20been%20temporarily%20revoked). Make sure to call the callback with an instance of UnauthorizedError (not Error).