2016-09-11 7 views
3

以前はADAL(Active Directory認証ライブラリ)を使用してユーザーをプログラムで追加していましたが、今は "signInNames"電子メール)、それはADALで可能ではないようです(間違っているかどうか教えてください)。http投稿要求を使用して、Azure Active Directory(B2C)with Graph APIで新しいユーザーを作成する

今、the documentation on MSDNに続いて、HTTP POSTを使用してプログラムで新しいユーザー(ローカルアカウント)を追加しようとしています。

//Get access token (using ADAL) 
var authenticationContext = new AuthenticationContext(AuthString, false); 
var clientCred = new ClientCredential(ClientId, ClientSecret); 
var authenticationResult = authenticationContext.AcquireTokenAsync(ResourceUrl, clientCred); 
var token = authenticationResult.Result.AccessToken; 


//HTTP POST CODE 
const string mail = "[email protected]"; 
// Create a new user object. 
var user = new CustomUser 
{ 
    accountEnabled = true, 
    country = "MS", 
    creationType = "LocalAccount", 
    displayName = mail, 
    passwordPolicies = "DisablePasswordExpiration,DisableStrongPassword", 
    passwordProfile = new passwordProfile { password = "jVPmEm)6Bh", forceChangePasswordNextLogin = true }, 
    signInNames = new signInNames { type = "emailAddress", value = mail } 
}; 

var url = "https://graph.windows.net/" + TenantId + "/users?api-version=1.6"; 

var jsonObject = JsonConvert.SerializeObject(user); 

using (var client = new HttpClient()) 
{ 
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); 

    var response = client.PostAsync(url, 
     new StringContent(JsonConvert.SerializeObject(user).ToString(), 
      Encoding.UTF8, "application/json")) 
      .Result; 

    if (response.IsSuccessStatusCode) 
    { 
     dynamic content = JsonConvert.DeserializeObject(
      response.Content.ReadAsStringAsync() 
      .Result); 

     // Access variables from the returned JSON object 
     var appHref = content.links.applications.href; 
    } 
} 

しかし、私はこの応答を取得し、何の成功を持っていない:

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content:....} 

任意のアイデアを私は何をすべきか?私はPowershellスクリプトを使用して成功しましたが、私はC#アプリケーションでこれを行う必要があります。

答えて

1

は、あなたの応答飛雪をありがとう私は正しい権限があると信じています。私は自分の問題を解決するために何をしたのですか?

私は自分のカスタムクラス "NewUser"を削除してから、このサンプルプロジェクトをダウンロードしました:https://github.com/AzureADQuickStarts/B2C-GraphAPI-DotNet/blob/master/B2CGraphClient/B2CGraphClient.cs私のコードが間違っていたというリスクを排除してください。これは最終的にすべての私の問題を解決し

 private async Task<string> SendGraphPostRequest(string api, string json) 
    { 
     // NOTE: This client uses ADAL v2, not ADAL v4 
     var result = authContext.AcquireToken(Globals.aadGraphResourceId, credential); 
     var http = new HttpClient(); 
     var url = Globals.aadGraphEndpoint + tenant + api + "?" + Globals.aadGraphVersion; 

     var request = new HttpRequestMessage(HttpMethod.Post, url); 
     request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken); 
     request.Content = new StringContent(json, Encoding.UTF8, "application/json"); 
     var response = await http.SendAsync(request); 

     if (!response.IsSuccessStatusCode) 
     { 
      var error = await response.Content.ReadAsStringAsync(); 
      var formatted = JsonConvert.DeserializeObject(error); 
      //Console.WriteLine("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented)); 
      Logger.Error("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented)); 
     } 
     Logger.Info((int)response.StatusCode + ": " + response.ReasonPhrase); 

     return await response.Content.ReadAsStringAsync(); 
    } 

B2CGraphClient.csから

var jsonObject = new JObject 
         { 
          {"accountEnabled", true}, 
          {"country", customer.CustomerBase.Company}, 
          {"creationType", "LocalAccount"}, 
          {"displayName", pendingCustomer.Email.Trim()}, 
          {"passwordPolicies", "DisablePasswordExpiration,DisableStrongPassword"}, 
          {"passwordProfile", new JObject 
          { 
           {"password", pwd}, 
           {"forceChangePasswordNextLogin", true} 
          } }, 
          {"signInNames", new JArray 
           { 
            new JObject 
            { 
             {"value", pendingCustomer.Email.Trim()}, 
             {"type", "emailAddress"} 
            } 
           } 
          } 
         }; 

client = new B2CGraphClient(ClientId, ClientSecret, TenantId); 
var response = await client.CreateUser(jsonObject.ToString()); 
var newUser = JsonConvert.DeserializeObject<User>(response); 

が、それはおそらく連載でフォーマットエラーだった:私は私のニーズをサポートするためにそれを変更し、それから私は、単純なjオブジェクトを作成しました私のNewCustomerクラスはAPIによって拒否されました。

2

ユーザーに操作を許可する十分な許可をアプリケーションに与えましたか? create user REST APIは、私にとってB2Cテナントにとってうまく機能します。

1.Create

PowerShell: 

$bytes = New-Object Byte[] 32 
$rand = [System.Security.Cryptography.RandomNumberGenerator]::Create() 
$rand.GetBytes($bytes) 
$rand.Dispose() 
$newClientSecret = [System.Convert]::ToBase64String($bytes) 

New-MsolServicePrincipal -DisplayName "My New B2C Graph API App" -Type password -Value 

2.Grantユーザーアカウント管理者の役割にアプリを以下のPowerShell経由でアプリ:

は、ここで私がテスト段階です。以下のRESTを使用してクライアントの資格情報の流れと

アプリのトークン3.Get
Add-MsolRoleMember -RoleObjectId fe930be7-5e62-47db-91af-98c3a49a38b1 -RoleMemberObjectId 7311370c-dac3-4f34-b2ce-b22c2a5a811e -RoleMemberType servicePrincipal 

POST: https://login.microsoftonline.com/adb2cfei.onmicrosoft.com/oauth2/token 
grant_type=client_credentials&client_id={AppPrincipalId return by PowerShell}&client_secret={client_secret}&resource=https%3A%2F%2Fgraph.windows.net 

4.Createユーザー:

POST: https://graph.windows.net/adb2cfei.onmicrosoft.com/users?api-version=1.6 
authorization: bearer {token} 
content-type: application/json 

{ 
    "accountEnabled": true, 
    "creationType": "LocalAccount", 
    "displayName": "Alex Wu", 
    "passwordProfile": { 
    "password": "Test1234", 
    "forceChangePasswordNextLogin": false 
    }, 
    "signInNames": [ 
    { 
     "type": "userName", 
     "value": "AlexW" 
    }, 
    { 
     "type": "emailAddress", 
     "value": "[email protected]" 
    } 
    ] 
} 
関連する問題