skip to Main Content

Ive been trying to do this for a couple of days now and ive double checked everything against examples and tried searching my error response but im not able to come up with anything.

Ive succesfully added graph api calls to my appplication already, when I do a GET on the /users endpoint it returns my AD users just fine, the code below is what I am doing to try and create the user but every time i get ResourceNotFound response.

It may we worth noting that at first I was getting an error message where it wasnt stating the resource it couldnt find, but now the error message is showing ‘Resource ‘User_’ does not exist…’

The GUID changes every time suggesting that it is creating that object and then trying to do something with it but then failing on the API somewhere.

Create User Function –

Public Function CreateUser(user As User) As String
            Dim app As IConfidentialClientApplication = MsalAppBuilder.BuildConfidentialClientApplication(ClaimsPrincipal.Current)
    
            Dim accountId = ClaimsPrincipal.Current.GetMsalAccountId()            
            Dim account = app.GetAccountAsync(accountId).Result           
    
            Dim result As AuthenticationResult
            Dim scopes As String() = {"https://graph.microsoft.com/.default"}
    
            Try
                result = app.AcquireTokenSilent(scopes, account).ExecuteAsync().Result
    
            Catch msalEx As MsalUiRequiredException
                Return msalEx.Message
            Catch ex As Exception
                result = app.AcquireTokenForClient(scopes).ExecuteAsync().Result
            End Try
    
    
            Dim client = New HttpClient()
            Dim request As New HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/v1.0/users")
            request.Headers.Authorization = New AuthenticationHeaderValue("Bearer", result.AccessToken)
    
            Dim json = JsonConvert.SerializeObject(user)
            request.Content = New StringContent(json, Encoding.UTF8, "application/json")
    
            Dim response = client.SendAsync(request).Result
    
            If response.Content IsNot Nothing Then
                Dim responseString = response.Content.ReadAsStringAsync().Result
                Return responseString
            End If
            Return ""
        End Function

Something else I noticed is that the app never contains any users so the scope only token is always called.

2

Answers


  1. Chosen as BEST ANSWER

    After posting here I also requested help from the microsoft support team.

    They suggested that i use the graph explorer to try again, so after doing both that and re-sending my request in Insomnia I did in fact get a successful response when using the graph explorer and still BadRequest from Insomnia and code.

    The difference between these requests was the Request Body.

    What I initially built was using the code sample provided in the graph documentation here (Example 1) - https://learn.microsoft.com/en-us/graph/api/user-post-users?view=graph-rest-1.0&tabs=http

    To save you some time this is what it looks like -

    POST https://graph.microsoft.com/v1.0/users
    Content-type: application/json
    
    {
      "accountEnabled": true,
      "displayName": "Adele Vance",
      "mailNickname": "AdeleV",
      "userPrincipalName": "[email protected]",
      "passwordProfile" : {
        "forceChangePasswordNextSignIn": true,
        "password": "xWwvJ]6NMw+bWH-d"
      }
    }
    

    And this is what the request body looks like in graph explorer -

    {
            "accountEnabled": true,
            "city": "Seattle",
            "country": "United States",
            "department": "Sales & Marketing",
            "displayName": "Melissa Darrow",
            "givenName": "Melissa",
            "jobTitle": "Marketing Director",
            "mailNickname": "MelissaD",
            "passwordPolicies": "DisablePasswordExpiration",
            "passwordProfile": {
                "password": "b85dba0d-be1b-a59a-8332-6821b138674d",
                "forceChangePasswordNextSignIn": false
            },
            "officeLocation": "131/1105",
            "postalCode": "98052",
            "preferredLanguage": "en-US",
            "state": "WA",
            "streetAddress": "9256 Towne Center Dr., Suite 400",
            "surname": "Darrow",
            "mobilePhone": "+1 206 555 0110",
            "usageLocation": "US",
            "userPrincipalName": "MelissaD@{domain}"
    }
    

    After changing my code model to match the second request body I now get a successful response in code, and to test the theory I left my old request body in Insomnia and resent the request with a fresh token and it return BadRequest whilst the code returned Success.

    I'm not 100% sure what the missing properties are, perhaps just password policies. If Microsoft give me more insight I will update here.

    Hopefully this provides someone else with some insight as I really struggled to find information on this one myself.


  2. Try out a few things –

    1. As Tim suggested using the same token and JSON Content and see if you can leverage Postman and call the same API to validate your JSON(request body), URL, and token.
    2. Use jwt.ms and check if your token has all necessary claims.
    3. Make sure you have given required permission to your App.

    If you still face same problem, do revert with client-request-id and timestamp so that I can check it better.

    Thanks.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search