Search code examples
kotlinmicrosoft-graph-apimicrosoft-graph-sdks

Get a guest user by userPrincipalName with Microsoft Graph SDK with Kotlin


I have the same problem described here: Get a guest user by userPrincipalName with Microsoft Graph. I want to get a guest user from Graph but I do it with SDK, i.e. a Graph Client, and I use Kotlin. The solution provided in the above mentioned thread does not help me. I still get a 404 Not Found Response even though I am replacing # with %23.

My code looks like this:

val upn = "hans.muster_somecompany.com%23EXT%23@mydomain.onmicrosoft.com"
client.users(upn)
    .buildRequest()
    .select(USER_FIELDS)
    .get()

I've also tried val upn = "hans.muster_somecompany.com%23EXT%23%40mydomain.onmicrosoft.com". Same result.

I am sure that the account exists. When I use the same query in Graph Explorer the user can be found.


Solution

  • When encoding the UPN first it works.

    val upn = "hans.muster_somecompany.com#EXT#@mydomain.onmicrosoft.com"
    val upnEncoded = UriUtils.encodePathSegment(
        upn,
        StandardCharsets.UTF_8
    )
    // upnEncoded is now "hans.muster_somecompany.com%23EXT%23@mydomain.onmicrosoft.com"
    client.users(upnEncoded)
        .buildRequest()
        .select(USER_FIELDS)
        .get()
    

    The confusing piece for me was that the controller removes # and everything that comes afterwards. This resulted in "hans.muster_somecompany.com". When encoding the # "manually" and handing that over to the client, the result was "hans.muster_somecompany.com%25%23EXT%25%23@mydomain.onmicrosoft.com" which didn't work either. So, finally, the problem wasn't really Graph but how the client/controller handle the request parameter.