An API that connects multiple Microsoft services, enabling data access and automation across platforms
Need help with my Microsoft Graph API
Hello, I made a sample API in which I am able to read the users from azure ad, and able to create them in my local db by calling another API . I need help with the login page it shows after executing.
I don't need that microsoft -signin/login pop up after running my api
In my application I am able to get the token value . Could you please help me that ?
Below is the code from my startup file of my sample api, I am also posting another way I tried for the same and I am getting the token value.
1st Way -> startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Add Microsoft Identity Platform sign-in
services
.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options => {
Configuration.Bind("AzureAd", options);
options.Prompt = "select_account";
options.Events.OnTokenValidated = async context => {
var tokenAcquisition = context.HttpContext.RequestServices
.GetRequiredService<ITokenAcquisition>();
var graphClient = new GraphServiceClient(
new DelegateAuthenticationProvider(async (request) => {
var token = await tokenAcquisition
.GetAccessTokenForUserAsync(DefaultScopes, user: context.Principal);
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", token);
})
);
// Get user information from Graph
var users = graphClient.Users.Request().Select(x => new
{
x.DisplayName,
x.Mail,
x.Id,
x.Identities
}).GetAsync().Result;
var client = new RestClient("https://localhost:44374/api/User/SaveUsers");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
List<UTEN_T017> userlist = new List<UTEN_T017>();
foreach (var item in users)
{
UTEN_T017 user = new UTEN_T017()
{
C_USER = item.DisplayName,
S_EMAIL = item.Mail,
S_PSW = "",
S_NOM = item.Id,
S_UTEN = item.DisplayName,
};
userlist.Add(user);
}
var body = JsonConvert.SerializeObject(userlist).ToString();
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
//return View();
};
options.Events.OnAuthenticationFailed = context => {
var error = WebUtility.UrlEncode(context.Exception.Message);
context.Response
.Redirect($"/Home/ErrorWithMessage?message=Authentication+error&debug={error}");
context.HandleResponse();
return Task.FromResult(0);
};
options.Events.OnRemoteFailure = context => {
if (context.Failure is OpenIdConnectProtocolException)
{
var error = WebUtility.UrlEncode(context.Failure.Message);
context.Response
.Redirect($"/Home/ErrorWithMessage?message=Sign+in+error&debug={error}");
context.HandleResponse();
}
return Task.FromResult(0);
};
})
// Add ability to call web API (Graph)
// and get access tokens
.EnableTokenAcquisitionToCallDownstreamApi(options => {
Configuration.Bind("AzureAd", options);
})
.AddInMemoryTokenCaches()
// Add a GraphServiceClient via dependency injection
.AddMicrosoftGraph(x =>
{
string tenantId = Configuration.GetValue<string>("AzureAd:TenantId");
string clientId = Configuration.GetValue<string>("AzureAd:ClientId");
string clientSecret = Configuration.GetValue<string>("AzureAd:ClientSecret");
ClientSecretCredential clientSecretCred = new ClientSecretCredential(tenantId, clientId, clientSecret);
return new GraphServiceClient(clientSecretCred);
}, new string[] { ".default" });
// Use in-memory token cache
// See https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization
// Require authentication
services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddRazorPages();
}
2nd way-> startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches()
.AddMicrosoftGraph(x =>
{
string tenantId = Configuration.GetValue<string>("AzureAd:TenantId");
string clientId = Configuration.GetValue<string>("AzureAd:ClientId");
string clientSecret = Configuration.GetValue<string>("AzureAd:ClientSecret");
ClientSecretCredential clientSecretCred = new ClientSecretCredential(tenantId, clientId, clientSecret);
return new GraphServiceClient(clientSecretCred);
}, new string[] { ".default" });
services.AddMvc(options=>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
}
---homecontroller.cs->
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create("9ae0f571-f512-464b-94e4-d2871a6c6061")
.WithClientSecret("zEH7Q~z8A1dxot5~rxozVbVPPCbhmhjBR84y2")
.WithAuthority(new Uri("https://login.microsoftonline.com/1b7fe149-a9a3-4f60-a028-290a55be1a59"))
.Build();
AuthenticationResult result;
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
string access_token = result.AccessToken;
//ClientCredentialProvider authProvider = new ClientCredentialProvider(app);
//GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var users = _graphServiceClient.Users.Request().Select(x => new
{
x.DisplayName,
x.Mail,
x.Id,
x.Identities
}).GetAsync().Result;
var client = new RestClient("https://localhost:44374/api/User/SaveUsers");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + access_token);
List<UTEN_T017> userlist = new List<UTEN_T017>();
foreach (var item in users)
{
UTEN_T017 user = new UTEN_T017() { C_USER = item.DisplayName,
S_EMAIL = item.Mail,
S_PSW = "",
S_NOM = item.Id,
S_UTEN = item.DisplayName,
};
userlist.Add(user);
}
var body = JsonConvert.SerializeObject(userlist).ToString();
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
//return Ok(users);
return View();
}