Azure / static-web-apps

Azure Static Web Apps. For bugs and feature requests, please create an issue in this repo. For community discussions, latest updates, kindly refer to the Discussions Tab. To know what's new in Static Web Apps, visit https://aka.ms/swa/ThisMonth
https://aka.ms/swa
MIT License
324 stars 57 forks source link

403 Forbidden - Getroles API doesn't work for some users #812

Open chris-dnv opened 2 years ago

chris-dnv commented 2 years ago

Describe the bug

I've configured the Getroles API and custom authentication as per the documentation which works for myself and some of my colleagues however a few colleagues have told me that no matter what browser they use / if they use incognito etc they get 403 forbidden when trying to access my static site. They are a member of the same group that I am which is a generic AD group for our company, I've tried to see in the app insights logs what the issue might be but the logs aren't detailed enough / don't show what role the user has, if any.

To Reproduce the affected users have tried to clear cookies, use different browsers etc to no avail. They have the same group membership as myself.

{
  "routes": [
    {
      "route": "/*",
      "allowedRoles": [
        "reader",
        "admin"
      ]
    }
  ],
  "responseOverrides": {
    "401": {
      "statusCode": 302,
      "redirect": "/.auth/login/aad"
    }
  },
  "auth": {
    "rolesSource": "/api/GetRoles",
    "identityProviders": {
      "azureActiveDirectory": {
        "userDetailsClaim": "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
        "registration": {
          "openIdIssuer": "https://login.microsoftonline.com/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
          "clientIdSettingName": "AZURE_CLIENT_ID",
          "clientSecretSettingName": "AZURE_CLIENT_SECRET"
        },
        "login": {
          "loginParameters": [
            "resource=https://graph.microsoft.com"
          ]
        }
      }
    }
  },
  "globalHeaders": {
    "Cache-Control": "no-cache"
  }
}
const fetch = require('node-fetch').default;

// add role names to this object to map them to group ids in your AAD tenant
const roleGroupMappings = {
    'reader': 'xxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxxxxxx',
    'admin': 'xxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxxxxxx'
};

module.exports = async function (context, req) {
    const user = req.body || {};
    const roles = [];

    for (const [role, groupId] of Object.entries(roleGroupMappings)) {
        if (await isUserInGroup(groupId, user.accessToken)) {
            roles.push(role);
        }
    }

    context.res.json({
        roles
    });
}

async function isUserInGroup(groupId, bearerToken) {
    const url = new URL('https://graph.microsoft.com/v1.0/me/memberOf');
    url.searchParams.append('$filter', `id eq '${groupId}'`);
    const response = await fetch(url, {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${bearerToken}`
        },
    });

    if (response.status !== 200) {
        return false;
    }

    const graphResponse = await response.json();
    const matchingGroups = graphResponse.value.filter(group => group.id === groupId);
    return matchingGroups.length > 0;
}

Expected behavior I expect that these users can login to the site as expected as they should be granted the reader role.

Screenshots If applicable, add screenshots to help explain your problem.

Device info (if applicable):

Additional context Site works fine for a majority of users, is it possible to view the App/API logs to see why the role isn't set for these specific users? EDIT - I just found this issue which looks to be very similar / the same as mine : https://github.com/staticwebdev/roles-function/issues/3 users in our tenant with the issue also have over 100 groups but not everyone with over 100 groups is affected like myself.....

sedvardsen commented 2 years ago

As out of curiosity - do the affected users have any "special" characters in their name? Typically æ or ł (or anything that will serialize as two bytes not one)

Azuredevmuc commented 2 years ago

I have also an issue to add roles programatically to users. I drilled down to the issue and logging says: Exception: System.AggregateException: One or more errors occurred. (Code: BadRequest Message: /me request is only valid with delegated authentication flow.

So - this worked before, but now, it seems to behave strange.

My GetRoles looks similiar to the one above - with the difference, i'm using GraphServiceClient. This is a major issue, and i tried several things, but nothing worked.

chris-dnv commented 2 years ago

As out of curiosity - do the affected users have any "special" characters in their name? Typically æ or ł (or anything that will serialize as two bytes not one)

A couple of the users with this issue have the same first name: Øystein however not all users that have reported this issue have a name with special characters in Azure AD

Azuredevmuc commented 2 years ago

Ok - i have solved the issue i had wih it. That must not be related to the above topic. Error Message was correct. I doulbe checked my implementation and figured out, i was using App Credentials to call /me with Graph Client. My fault on this. Sorry to waste your time.

C# = Initialize the GraphServiceClient like so: var _client = new GraphServiceClient(new TokenAuthenticationProvider(accessToken));

accessToken is in ths case is in the body of the request to GetRoles. It contains UserId and AccessToken, if the Application is registered correctly: https://docs.microsoft.com/en-us/azure/static-web-apps/assign-roles-microsoft-graph

Additional: i found also threads, where a large number of groups can't be handled.

chris-dnv commented 2 years ago

i've opened a case in the Azure Portal as this is still an issue, would really like to get this fixed so that we can use the roles API as per the microsoft docs