Getting groups of which user is apart of in python/flask

I have build a Flask app in python, using okta as user authentication.
My aim is to make parts of the App accessible only for users in a certain group, hence I need to get the groups a user is apart of.
Currently the best solution I could come up with is just looping through each group and checking if the user-id provides a match. This is very slow and clearly not an optimal solution.
Any way to speed this up? Or get the groups directly from the user?

Below is the code I am currently using

 groups_client = UserGroupsClient(https://{org}.oktapreview.com", "API_KEY")
 ids = [groups_client.get_groups(query="Group1")[0].id,groups_client.get_groups(query="Group2") 
 [0].id,groups_client.get_groups(query="Group3")[0].id,groups_client.get_groups(query="Group4") 
 [0].id,groups_client.get_groups(query="Group5")[0].id]
 group_names = ["Group1","Group2","Group3","Group4","Group5"]

@app.before_request
   def before_request():
    if oidc.user_loggedin:
           g.user = okta_client.get_user(oidc.user_getfield("sub"))
          count = 0
          for id in ids:
               users = groups_client.get_group_users(id)

                for user in users:
                   if user.id == g.user.id:
                        g.group = group_names[count]
         count = count + 1
 else:
    g.user = None

If you are using OpenID Connect in your application, you can include the user’s groups in the JWT ID token generated when they are authorized into your application by setting up a Groups Claim.

This will limit the number of additional calls your application would have to make to Okta to get information about the user, as you can include anything your application would like to know about the user within the ID token or from a /userinfo call with the Access Token.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.