MicrosoftDocs / mslearn-staticwebapp-authentication

Creative Commons Attribution 4.0 International
16 stars 14 forks source link

Get logged user's roles in Azure Function on static web app #1

Open eduardogoncalves opened 3 years ago

eduardogoncalves commented 3 years ago

Hi, I want to call the api and at the function decides what level of info to show/return based on user's roles. Can someone give a sample on how to get logged user's roles in Azure Function on static web app?

When deploying Azure Function via "Function App", I can get the roles and current username, but with "Static Web App" I haven't figured it out yet.

namespace Function1
{
    public class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ClaimsPrincipal principal)
        {

            IEnumerable<string> roles = principal.Claims.Where(e => e.Type.Equals("roles")).Select(e => e.Value);

            string name = principal.Identity.Name;

            string responseMessage = $"Hello, {name}. This HTTP triggered function executed successfully. {string.Join(',', roles)}";

            return new OkObjectResult(responseMessage);
        }
    }
}
phil-w commented 7 months ago

Ancient history, but did you figure that out?

The MS Azure docs suggest you should be able to get user details including roles in the endpoint of an authenticated Azure Function... but const header = req.headers.get('x-ms-client-principal'); fails in dev and live as the header isn't there. I can't see how that could ever be in there, as it would expose the unencrypted user ID which is somewhat against the whole point.

I mean: you could get the user ID from /.auth/me and then stick it in a header, and pull that out in the Azure Function. That wouldn't be massively secure, but ought to work. Any attacker would be legitimately authenticated so could be fairly easily detected. It seems a bit hack.

Looking at how it actually behaves (not what the docs say), the StaticWebAppsAuthCookie is the only user identifiable thing leaving the client for Azure. So that signed package presumably contains enough for Azure to work out that you're authenticated. This open issue suggests that cookie contains User ID. However in my dev & live tests, the cookie isn't passed through to the Azure Function itself. Presumably the middleware strips it.

So the only way I can see to get the user ID (or other stuff eg roles) would be to pass those things explicitly. That seems a bit unsatisfactory as if the Function knows you have an authenticated role, it must know your ID. Perhaps that's obvious: these "serverless" endpoints are not intended to be connected to [for example] database backends?

I don't know, perhaps someone can clarify that?